three-render-objects 1.32.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- // Version 1.32.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||"default");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 bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n}\n\n.scene-tooltip {\n top: 0;\n color: lavender;\n font-size: 15px;\n}\n\n.scene-nav-info, .scene-tooltip {\n position: absolute;\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="171",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,S=303,w=304,M=1e3,N=1001,A=1002,E=1003,C=1004,R=1005,P=1006,B=1007,F=1008,I=1009,U=1010,D=1011,O=1012,L=1013,k=1014,z=1015,G=1016,V=1020,j=1022,H=1023,W=1026,$=1027,q=1028,Y=1029,X=1030,K=1031,Z=1033,Q=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",Se="srgb",we=7680,Me=512,Ne=513,Ae=514,Ee=515,Ce=516,Re=517,Pe=518,Be=519,Fe=35044,Ie=35048,Ue=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){if(void 0===this._listeners)return!1;const s=this._listeners;return void 0!==s[e]&&-1!==s[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const s=this._listeners[e];if(void 0!==s){const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const s=t.slice(0);for(let t=0,i=s.length;t<i;t++)s[t].call(this,e);e.target=null}}}const Le=["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 ke=1234567;const ze=Math.PI/180,Ge=180/Math.PI;function Ve(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Le[255&e]+Le[e>>8&255]+Le[e>>16&255]+Le[e>>24&255]+"-"+Le[255&t]+Le[t>>8&255]+"-"+Le[t>>16&15|64]+Le[t>>24&255]+"-"+Le[63&s|128]+Le[s>>8&255]+"-"+Le[s>>16&255]+Le[s>>24&255]+Le[255&i]+Le[i>>8&255]+Le[i>>16&255]+Le[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 Ye={DEG2RAD:ze,RAD2DEG:Ge,generateUUID:Ve,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&&(ke=e);let t=ke+=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*Ge},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 Xe{constructor(e=0,t=0){Xe.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(Ze.makeScale(e,t)),this}rotate(e){return this.premultiply(Ze.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ze.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 Ze=new Ke;function Qe(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const Je={};const et=(new Ke).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),tt=(new Ke).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function st(){const e={enabled:!0,workingColorSpace:ve,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Se&&(e.r=rt(e.r),e.g=rt(e.g),e.b=rt(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===Se&&(e.r=nt(e.r),e.g=nt(e.g),e.b=nt(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:et,fromXYZ:tt,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:_e},outputColorSpaceConfig:{drawingBufferColorSpace:_e}},[_e]:{primaries:t,whitePoint:i,transfer:Se,toXYZ:et,fromXYZ:tt,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:_e}}}),e}const it=st();function rt(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function nt(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let ot;class at{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===ot&&(ot=Qe("canvas")),ot.width=e.width,ot.height=e.height;const s=ot.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=ot}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Qe("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*rt(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*rt(t[e]/255)):t[e]=rt(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 ht=0;class lt{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ht++}),this.uuid=Ve(),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(ut(i[t].image)):e.push(ut(i[t]))}else e=ut(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function ut(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?at.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 ct=0;class dt extends Oe{constructor(e=dt.DEFAULT_IMAGE,t=dt.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,o=1023,a=1009,h=dt.DEFAULT_ANISOTROPY,l=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:ct++}),this.uuid=Ve(),this.name="",this.source=new lt(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 Xe(0,0),this.repeat=new Xe(1,1),this.center=new Xe(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.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.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 A: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 A: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++}}dt.DEFAULT_IMAGE=null,dt.DEFAULT_MAPPING=300,dt.DEFAULT_ANISOTROPY=1;class pt{constructor(e=0,t=0,s=0,i=1){pt.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 mt extends Oe{constructor(e=1,t=1,s={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new pt(0,0,e,t),this.scissorTest=!1,this.viewport=new pt(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 dt(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.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}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;const t=Object.assign({},e.texture.image);return this.texture.source=new lt(t),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 gt extends mt{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class ft extends dt{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=E,this.minFilter=E,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 yt{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 bt{constructor(e=0,t=0,s=0){bt.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(_t.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_t.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 xt.copy(this).projectOnVector(e),this.sub(xt)}reflect(e){return this.sub(xt.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 xt=new bt,_t=new yt;class vt{constructor(e=new bt(1/0,1/0,1/0),t=new bt(-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(St.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(St.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=St.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,St):St.fromBufferAttribute(i,t),St.applyMatrix4(e.matrixWorld),this.expandByPoint(St);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),wt.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),wt.copy(s.boundingBox)),wt.applyMatrix4(e.matrixWorld),this.union(wt)}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,St),St.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(Pt),Bt.subVectors(this.max,Pt),Mt.subVectors(e.a,Pt),Nt.subVectors(e.b,Pt),At.subVectors(e.c,Pt),Et.subVectors(Nt,Mt),Ct.subVectors(At,Nt),Rt.subVectors(Mt,At);let t=[0,-Et.z,Et.y,0,-Ct.z,Ct.y,0,-Rt.z,Rt.y,Et.z,0,-Et.x,Ct.z,0,-Ct.x,Rt.z,0,-Rt.x,-Et.y,Et.x,0,-Ct.y,Ct.x,0,-Rt.y,Rt.x,0];return!!Ut(t,Mt,Nt,At,Bt)&&(t=[1,0,0,0,1,0,0,0,1],!!Ut(t,Mt,Nt,At,Bt)&&(Ft.crossVectors(Et,Ct),t=[Ft.x,Ft.y,Ft.z],Ut(t,Mt,Nt,At,Bt)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,St).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(St).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()||(Tt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Tt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Tt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Tt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Tt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Tt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Tt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Tt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Tt)),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 Tt=[new bt,new bt,new bt,new bt,new bt,new bt,new bt,new bt],St=new bt,wt=new vt,Mt=new bt,Nt=new bt,At=new bt,Et=new bt,Ct=new bt,Rt=new bt,Pt=new bt,Bt=new bt,Ft=new bt,It=new bt;function Ut(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){It.fromArray(e,n);const o=r.x*Math.abs(It.x)+r.y*Math.abs(It.y)+r.z*Math.abs(It.z),a=t.dot(It),h=s.dot(It),l=i.dot(It);if(Math.max(-Math.max(a,h,l),Math.min(a,h,l))>o)return!1}return!0}const Dt=new vt,Ot=new bt,Lt=new bt;class kt{constructor(e=new bt,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):Dt.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;Ot.subVectors(e,this.center);const t=Ot.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Ot,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):(Lt.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ot.copy(e.center).add(Lt)),this.expandByPoint(Ot.copy(e.center).sub(Lt))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const zt=new bt,Gt=new bt,Vt=new bt,jt=new bt,Ht=new bt,Wt=new bt,$t=new bt;class qt{constructor(e=new bt,t=new bt(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,zt)),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=zt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(zt.copy(this.origin).addScaledVector(this.direction,t),zt.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Gt.copy(e).add(t).multiplyScalar(.5),Vt.copy(t).sub(e).normalize(),jt.copy(this.origin).sub(Gt);const r=.5*e.distanceTo(t),n=-this.direction.dot(Vt),o=jt.dot(this.direction),a=-jt.dot(Vt),h=jt.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(Gt).addScaledVector(Vt,c),d}intersectSphere(e,t){zt.subVectors(e.center,this.origin);const s=zt.dot(this.direction),i=zt.dot(zt)-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,zt)}intersectTriangle(e,t,s,i,r){Ht.subVectors(t,e),Wt.subVectors(s,e),$t.crossVectors(Ht,Wt);let n,o=this.direction.dot($t);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}jt.subVectors(this.origin,e);const a=n*this.direction.dot(Wt.crossVectors(jt,Wt));if(a<0)return null;const h=n*this.direction.dot(Ht.cross(jt));if(h<0)return null;if(a+h>o)return null;const l=-n*jt.dot($t);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 Yt{constructor(e,t,s,i,r,n,o,a,h,l,u,c,d,p,m,g){Yt.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 Yt).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/Xt.setFromMatrixColumn(e,0).length(),r=1/Xt.setFromMatrixColumn(e,1).length(),n=1/Xt.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(Zt,e,Qt)}lookAt(e,t,s){const i=this.elements;return ts.subVectors(e,t),0===ts.lengthSq()&&(ts.z=1),ts.normalize(),Jt.crossVectors(s,ts),0===Jt.lengthSq()&&(1===Math.abs(s.z)?ts.x+=1e-4:ts.z+=1e-4,ts.normalize(),Jt.crossVectors(s,ts)),Jt.normalize(),es.crossVectors(ts,Jt),i[0]=Jt.x,i[4]=es.x,i[8]=ts.x,i[1]=Jt.y,i[5]=es.y,i[9]=ts.y,i[2]=Jt.z,i[6]=es.z,i[10]=ts.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],S=i[8],w=i[12],M=i[1],N=i[5],A=i[9],E=i[13],C=i[2],R=i[6],P=i[10],B=i[14],F=i[3],I=i[7],U=i[11],D=i[15];return r[0]=n*v+o*M+a*C+h*F,r[4]=n*T+o*N+a*R+h*I,r[8]=n*S+o*A+a*P+h*U,r[12]=n*w+o*E+a*B+h*D,r[1]=l*v+u*M+c*C+d*F,r[5]=l*T+u*N+c*R+d*I,r[9]=l*S+u*A+c*P+d*U,r[13]=l*w+u*E+c*B+d*D,r[2]=p*v+m*M+g*C+f*F,r[6]=p*T+m*N+g*R+f*I,r[10]=p*S+m*A+g*P+f*U,r[14]=p*w+m*E+g*B+f*D,r[3]=y*v+b*M+x*C+_*F,r[7]=y*T+b*N+x*R+_*I,r[11]=y*S+b*A+x*P+_*U,r[15]=y*w+b*E+x*B+_*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=Xt.set(i[0],i[1],i[2]).length();const n=Xt.set(i[4],i[5],i[6]).length(),o=Xt.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],Kt.copy(this);const a=1/r,h=1/n,l=1/o;return Kt.elements[0]*=a,Kt.elements[1]*=a,Kt.elements[2]*=a,Kt.elements[4]*=h,Kt.elements[5]*=h,Kt.elements[6]*=h,Kt.elements[8]*=l,Kt.elements[9]*=l,Kt.elements[10]*=l,t.setFromRotationMatrix(Kt),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===Ue)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===Ue)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 Xt=new bt,Kt=new Yt,Zt=new bt(0,0,0),Qt=new bt(1,1,1),Jt=new bt,es=new bt,ts=new bt,ss=new Yt,is=new yt;class rs{constructor(e=0,t=0,s=0,i=rs.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 ss.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ss,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return is.setFromEuler(this),this.setFromQuaternion(is,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}}rs.DEFAULT_ORDER="XYZ";class ns{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 os=0;const as=new bt,hs=new yt,ls=new Yt,us=new bt,cs=new bt,ds=new bt,ps=new yt,ms=new bt(1,0,0),gs=new bt(0,1,0),fs=new bt(0,0,1),ys={type:"added"},bs={type:"removed"},xs={type:"childadded",child:null},_s={type:"childremoved",child:null};class vs extends Oe{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:os++}),this.uuid=Ve(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=vs.DEFAULT_UP.clone();const e=new bt,t=new rs,s=new yt,i=new bt(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 Yt},normalMatrix:{value:new Ke}}),this.matrix=new Yt,this.matrixWorld=new Yt,this.matrixAutoUpdate=vs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=vs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ns,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],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 hs.setFromAxisAngle(e,t),this.quaternion.multiply(hs),this}rotateOnWorldAxis(e,t){return hs.setFromAxisAngle(e,t),this.quaternion.premultiply(hs),this}rotateX(e){return this.rotateOnAxis(ms,e)}rotateY(e){return this.rotateOnAxis(gs,e)}rotateZ(e){return this.rotateOnAxis(fs,e)}translateOnAxis(e,t){return as.copy(e).applyQuaternion(this.quaternion),this.position.add(as.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ms,e)}translateY(e){return this.translateOnAxis(gs,e)}translateZ(e){return this.translateOnAxis(fs,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ls.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?us.copy(e):us.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),cs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ls.lookAt(cs,us,this.up):ls.lookAt(us,cs,this.up),this.quaternion.setFromRotationMatrix(ls),i&&(ls.extractRotation(i.matrixWorld),hs.setFromRotationMatrix(ls),this.quaternion.premultiply(hs.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(ys),xs.child=e,this.dispatchEvent(xs),xs.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(bs),_s.child=e,this.dispatchEvent(_s),_s.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),ls.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),ls.multiply(e.parent.matrixWorld)),e.applyMatrix4(ls),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(ys),xs.child=e,this.dispatchEvent(xs),xs.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(cs,e,ds),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(cs,ps,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}}vs.DEFAULT_UP=new bt(0,1,0),vs.DEFAULT_MATRIX_AUTO_UPDATE=!0,vs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Ts=new bt,Ss=new bt,ws=new bt,Ms=new bt,Ns=new bt,As=new bt,Es=new bt,Cs=new bt,Rs=new bt,Ps=new bt,Bs=new pt,Fs=new pt,Is=new pt;class Us{constructor(e=new bt,t=new bt,s=new bt){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Ts.subVectors(e,t),i.cross(Ts);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){Ts.subVectors(i,t),Ss.subVectors(s,t),ws.subVectors(e,t);const n=Ts.dot(Ts),o=Ts.dot(Ss),a=Ts.dot(ws),h=Ss.dot(Ss),l=Ss.dot(ws),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,Ms)&&(Ms.x>=0&&Ms.y>=0&&Ms.x+Ms.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Ms)?(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,Ms.x),a.addScaledVector(n,Ms.y),a.addScaledVector(o,Ms.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Bs.setScalar(0),Fs.setScalar(0),Is.setScalar(0),Bs.fromBufferAttribute(e,t),Fs.fromBufferAttribute(e,s),Is.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Bs,r.x),n.addScaledVector(Fs,r.y),n.addScaledVector(Is,r.z),n}static isFrontFacing(e,t,s,i){return Ts.subVectors(s,t),Ss.subVectors(e,t),Ts.cross(Ss).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 Ts.subVectors(this.c,this.b),Ss.subVectors(this.a,this.b),.5*Ts.cross(Ss).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Us.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Us.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Us.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Us.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Us.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;Ns.subVectors(i,s),As.subVectors(r,s),Cs.subVectors(e,s);const a=Ns.dot(Cs),h=As.dot(Cs);if(a<=0&&h<=0)return t.copy(s);Rs.subVectors(e,i);const l=Ns.dot(Rs),u=As.dot(Rs);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(Ns,n);Ps.subVectors(e,r);const d=Ns.dot(Ps),p=As.dot(Ps);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(As,o);const g=l*p-d*u;if(g<=0&&u-l>=0&&d-p>=0)return Es.subVectors(r,i),o=(u-l)/(u-l+(d-p)),t.copy(i).addScaledVector(Es,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(Ns,n).addScaledVector(As,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Ds={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Os={h:0,s:0,l:0},Ls={h:0,s:0,l:0};function ks(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class zs{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=_e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,it.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=it.workingColorSpace){return this.r=e,this.g=t,this.b=s,it.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=it.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=ks(r,i,e+1/3),this.g=ks(r,i,e),this.b=ks(r,i,e-1/3)}return it.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=Ds[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=rt(e.r),this.g=rt(e.g),this.b=rt(e.b),this}copyLinearToSRGB(e){return this.r=nt(e.r),this.g=nt(e.g),this.b=nt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=_e){return it.fromWorkingColorSpace(Gs.copy(this),e),65536*Math.round(je(255*Gs.r,0,255))+256*Math.round(je(255*Gs.g,0,255))+Math.round(je(255*Gs.b,0,255))}getHexString(e=_e){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=it.workingColorSpace){it.fromWorkingColorSpace(Gs.copy(this),t);const s=Gs.r,i=Gs.g,r=Gs.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=it.workingColorSpace){return it.fromWorkingColorSpace(Gs.copy(this),t),e.r=Gs.r,e.g=Gs.g,e.b=Gs.b,e}getStyle(e=_e){it.fromWorkingColorSpace(Gs.copy(this),e);const t=Gs.r,s=Gs.g,i=Gs.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(Os),this.setHSL(Os.h+e,Os.s+t,Os.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(Os),e.getHSL(Ls);const s=We(Os.h,Ls.h,t),i=We(Os.s,Ls.s,t),r=We(Os.l,Ls.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Gs=new zs;zs.NAMES=Ds;let Vs=0;class js extends Oe{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Vs++}),this.uuid=Ve(),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 zs(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=we,this.stencilZFail=we,this.stencilZPass=we,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.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!==we&&(s.stencilFail=this.stencilFail),this.stencilZFail!==we&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==we&&(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 Hs extends js{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new zs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rs,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 Ws=$s();function $s(){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 qs(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=je(e,-65504,65504),Ws.floatView[0]=e;const t=Ws.uint32View[0],s=t>>23&511;return Ws.baseTable[s]+((8388607&t)>>Ws.shiftTable[s])}function Ys(e){const t=e>>10;return Ws.uint32View[0]=Ws.mantissaTable[Ws.offsetTable[t]+(1023&e)]+Ws.exponentTable[t],Ws.floatView[0]}const Xs=new bt,Ks=new Xe;class Zs{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Fe,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++)Ks.fromBufferAttribute(this,t),Ks.applyMatrix3(e),this.setXY(t,Ks.x,Ks.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.applyMatrix3(e),this.setXYZ(t,Xs.x,Xs.y,Xs.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.applyMatrix4(e),this.setXYZ(t,Xs.x,Xs.y,Xs.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.applyNormalMatrix(e),this.setXYZ(t,Xs.x,Xs.y,Xs.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.transformDirection(e),this.setXYZ(t,Xs.x,Xs.y,Xs.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!==Fe&&(e.usage=this.usage),e}}class Qs extends Zs{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Js extends Zs{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class ei extends Zs{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Ys(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]=qs(t),this}getY(e){let t=Ys(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]=qs(t),this}getZ(e){let t=Ys(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]=qs(t),this}getW(e){let t=Ys(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]=qs(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]=qs(t),this.array[e+1]=qs(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]=qs(t),this.array[e+1]=qs(s),this.array[e+2]=qs(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]=qs(t),this.array[e+1]=qs(s),this.array[e+2]=qs(i),this.array[e+3]=qs(r),this}}class ti extends Zs{constructor(e,t,s){super(new Float32Array(e),t,s)}}let si=0;const ii=new Yt,ri=new vs,ni=new bt,oi=new vt,ai=new vt,hi=new bt;class li extends Oe{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:si++}),this.uuid=Ve(),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(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?Js:Qs)(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 ii.makeRotationFromQuaternion(e),this.applyMatrix4(ii),this}rotateX(e){return ii.makeRotationX(e),this.applyMatrix4(ii),this}rotateY(e){return ii.makeRotationY(e),this.applyMatrix4(ii),this}rotateZ(e){return ii.makeRotationZ(e),this.applyMatrix4(ii),this}translate(e,t,s){return ii.makeTranslation(e,t,s),this.applyMatrix4(ii),this}scale(e,t,s){return ii.makeScale(e,t,s),this.applyMatrix4(ii),this}lookAt(e){return ri.lookAt(e),ri.updateMatrix(),this.applyMatrix4(ri.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ni).negate(),this.translate(ni.x,ni.y,ni.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 ti(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 vt);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 bt(-1/0,-1/0,-1/0),new bt(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];oi.setFromBufferAttribute(s),this.morphTargetsRelative?(hi.addVectors(this.boundingBox.min,oi.min),this.boundingBox.expandByPoint(hi),hi.addVectors(this.boundingBox.max,oi.max),this.boundingBox.expandByPoint(hi)):(this.boundingBox.expandByPoint(oi.min),this.boundingBox.expandByPoint(oi.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 kt);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 bt,1/0);if(e){const s=this.boundingSphere.center;if(oi.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];ai.setFromBufferAttribute(s),this.morphTargetsRelative?(hi.addVectors(oi.min,ai.min),oi.expandByPoint(hi),hi.addVectors(oi.max,ai.max),oi.expandByPoint(hi)):(oi.expandByPoint(ai.min),oi.expandByPoint(ai.max))}oi.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)hi.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(hi));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++)hi.fromBufferAttribute(n,t),o&&(ni.fromBufferAttribute(e,t),hi.add(ni)),i=Math.max(i,s.distanceToSquared(hi))}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 Zs(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),o=[],a=[];for(let e=0;e<s.count;e++)o[e]=new bt,a[e]=new bt;const h=new bt,l=new bt,u=new bt,c=new Xe,d=new Xe,p=new Xe,m=new bt,g=new bt;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 bt,x=new bt,_=new bt,v=new bt;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 Zs(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 bt,r=new bt,n=new bt,o=new bt,a=new bt,h=new bt,l=new bt,u=new bt;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++)hi.fromBufferAttribute(e,t),hi.normalize(),e.setXYZ(t,hi.x,hi.y,hi.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 Zs(n,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new li,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(t));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 ui=new Yt,ci=new qt,di=new kt,pi=new bt,mi=new bt,gi=new bt,fi=new bt,yi=new bt,bi=new bt,xi=new bt,_i=new bt;class vi extends vs{constructor(e=new li,t=new Hs){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,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){bi.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=o[s],a=r[s];0!==i&&(yi.fromBufferAttribute(a,e),n?bi.addScaledVector(yi,i):bi.addScaledVector(yi.sub(t),i))}t.add(bi)}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(),di.copy(s.boundingSphere),di.applyMatrix4(r),ci.copy(e.ray).recast(e.near),!1===di.containsPoint(ci.origin)){if(null===ci.intersectSphere(di,pi))return;if(ci.origin.distanceToSquared(pi)>(e.far-e.near)**2)return}ui.copy(r).invert(),ci.copy(e.ray).applyMatrix4(ui),null!==s.boundingBox&&!1===ci.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,ci)}}_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=Ti(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=Ti(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=Ti(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=Ti(this,n,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Ti(e,t,s,i,r,n,o,a,h,l){e.getVertexPosition(a,mi),e.getVertexPosition(h,gi),e.getVertexPosition(l,fi);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;_i.copy(a),_i.applyMatrix4(e.matrixWorld);const l=s.ray.origin.distanceTo(_i);return l<s.near||l>s.far?null:{distance:l,point:_i.clone(),object:e}}(e,t,s,i,mi,gi,fi,xi);if(u){const e=new bt;Us.getBarycoord(xi,mi,gi,fi,e),r&&(u.uv=Us.getInterpolatedAttribute(r,a,h,l,e,new Xe)),n&&(u.uv1=Us.getInterpolatedAttribute(n,a,h,l,e,new Xe)),o&&(u.normal=Us.getInterpolatedAttribute(o,a,h,l,e,new bt),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:a,b:h,c:l,normal:new bt,materialIndex:0};Us.getNormal(mi,gi,fi,t.normal),u.face=t,u.barycoord=e}return u}class Si extends li{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,S=g+1,w=f+1;let M=0,N=0;const A=new bt;for(let n=0;n<w;n++){const o=n*x-v;for(let a=0;a<S;a++){const c=a*b-_;A[e]=c*i,A[t]=o*r,A[s]=T,h.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[s]=m>0?1:-1,l.push(A.x,A.y,A.z),u.push(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+S*e,i=c+t+S*(e+1),r=c+(t+1)+S*(e+1),n=c+(t+1)+S*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 ti(h,3)),this.setAttribute("normal",new ti(l,3)),this.setAttribute("uv",new ti(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Si(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function wi(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 Mi extends js{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=wi(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 Ni extends vs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Yt,this.projectionMatrix=new Yt,this.projectionMatrixInverse=new Yt,this.coordinateSystem=Ue}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 Ai=new bt,Ei=new Xe,Ci=new Xe;class Ri extends Ni{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*Ge*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*ze*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Ge*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){Ai.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ai.x,Ai.y).multiplyScalar(-e/Ai.z),Ai.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Ai.x,Ai.y).multiplyScalar(-e/Ai.z)}getViewSize(e,t){return this.getViewBounds(e,Ei,Ci),t.subVectors(Ci,Ei)}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 Pi=-90;class Bi extends vs{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ri(Pi,1,e,t);i.layers=this.layers,this.add(i);const r=new Ri(Pi,1,e,t);r.layers=this.layers,this.add(r);const n=new Ri(Pi,1,e,t);n.layers=this.layers,this.add(n);const o=new Ri(Pi,1,e,t);o.layers=this.layers,this.add(o);const a=new Ri(Pi,1,e,t);a.layers=this.layers,this.add(a);const h=new Ri(Pi,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===Ue)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 Fi extends dt{constructor(e,t,s,i,r,n,o,a,h,l){super(e=void 0!==e?e:[],t=void 0!==t?t:v,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 Ii extends gt{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 Fi(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 Si(5,5,5),r=new Mi({name:"CubemapFromEquirect",uniforms:wi(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new vi(i,r),o=t.minFilter;t.minFilter===F&&(t.minFilter=P);return new Bi(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t,s,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Ui extends vs{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 rs,this.environmentIntensity=1,this.environmentRotation=new rs,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 Di{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Fe,this.updateRanges=[],this.version=0,this.uuid=Ve()}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=Ve()),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=Ve()),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 Oi=new bt;class Li{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++)Oi.fromBufferAttribute(this,t),Oi.applyMatrix4(e),this.setXYZ(t,Oi.x,Oi.y,Oi.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Oi.fromBufferAttribute(this,t),Oi.applyNormalMatrix(e),this.setXYZ(t,Oi.x,Oi.y,Oi.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Oi.fromBufferAttribute(this,t),Oi.transformDirection(e),this.setXYZ(t,Oi.x,Oi.y,Oi.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 Zs(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 Li(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 ki extends js{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new zs(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class zi extends dt{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 Gi extends Zs{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 Vi=new bt,ji=new bt,Hi=new Ke;class Wi{constructor(e=new bt(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=Vi.subVectors(s,t).cross(ji.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(Vi),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||Hi.getNormalMatrix(e),i=this.coplanarPoint(Vi).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 $i=new kt,qi=new bt;class Yi{constructor(e=new Wi,t=new Wi,s=new Wi,i=new Wi,r=new Wi,n=new Wi){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===Ue)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(),$i.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),$i.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere($i)}intersectsSprite(e){return $i.center.set(0,0,0),$i.radius=.7071067811865476,$i.applyMatrix4(e.matrixWorld),this.intersectsSphere($i)}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(qi.x=i.normal.x>0?e.max.x:e.min.x,qi.y=i.normal.y>0?e.max.y:e.min.y,qi.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(qi)<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 Xi extends js{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new zs(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class Ki extends js{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new zs(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class Zi extends dt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=E,this.minFilter=E,this.generateMipmaps=!1,this.needsUpdate=!0}}class Qi extends dt{constructor(e,t,s,i,r,n,o,a,h,l=1026){if(l!==W&&l!==$)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===s&&l===W&&(s=k),void 0===s&&l===$&&(s=V),super(null,i,r,n,o,a,l,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==o?o:E,this.minFilter=void 0!==a?a:E,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Ji extends li{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 bt,c=new bt,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 ti(p,3)),this.setAttribute("normal",new ti(m,3)),this.setAttribute("uv",new ti(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ji(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class er extends js{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new zs(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class tr extends js{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new zs(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 rs,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 sr extends tr{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 Xe(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 zs(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new zs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new zs(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class ir extends js{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new zs(16777215),this.specular=new zs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rs,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 rr extends js{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new zs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 nr extends js{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 or extends js{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new zs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rs,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 ar extends js{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new zs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 hr extends Xi{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 lr extends vs{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new zs(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 ur extends lr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(vs.DEFAULT_UP),this.updateMatrix(),this.groundColor=new zs(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const cr=new Yt,dr=new bt,pr=new bt;class mr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Xe(512,512),this.map=null,this.mapPass=null,this.matrix=new Yt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Yi,this._frameExtents=new Xe(1,1),this._viewportCount=1,this._viewports=[new pt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;dr.setFromMatrixPosition(e.matrixWorld),t.position.copy(dr),pr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(pr),t.updateMatrixWorld(),cr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(cr),s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(cr)}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 gr extends mr{constructor(){super(new Ri(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,s=2*Ge*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 fr extends lr{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(vs.DEFAULT_UP),this.updateMatrix(),this.target=new vs,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new gr}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 yr=new Yt,br=new bt,xr=new bt;class _r extends mr{constructor(){super(new Ri(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Xe(4,2),this._viewportCount=6,this._viewports=[new pt(2,1,1,1),new pt(0,1,1,1),new pt(3,1,1,1),new pt(1,1,1,1),new pt(3,0,1,1),new pt(1,0,1,1)],this._cubeDirections=[new bt(1,0,0),new bt(-1,0,0),new bt(0,0,1),new bt(0,0,-1),new bt(0,1,0),new bt(0,-1,0)],this._cubeUps=[new bt(0,1,0),new bt(0,1,0),new bt(0,1,0),new bt(0,1,0),new bt(0,0,1),new bt(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()),br.setFromMatrixPosition(e.matrixWorld),s.position.copy(br),xr.copy(s.position),xr.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(xr),s.updateMatrixWorld(),i.makeTranslation(-br.x,-br.y,-br.z),yr.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(yr)}}class vr extends lr{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 _r}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 Tr extends Ni{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 Sr extends mr{constructor(){super(new Tr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class wr extends lr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(vs.DEFAULT_UP),this.updateMatrix(),this.target=new vs,this.shadow=new Sr}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Mr extends lr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Nr extends lr{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 Ar{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new bt)}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 Er extends lr{constructor(e=new Ar,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 Cr extends Di{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}}"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 Rr=["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 Pr{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Rr,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:{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(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 Br(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 Fr=e=>Br(e),Ir=(...e)=>Br(e);function Ur(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of Dr(e))s.push(s,Br(i.slice(0,-4)),r.getCacheKey(t));return Br(s)}function*Dr(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 Or=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]);function Lr(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.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 zs(...t):"vec2"===s?new Xe(...t):"vec3"===s?new bt(...t):"vec4"===s?new pt(...t):"mat3"===s?new Ke(...t):"mat4"===s?new Yt(...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}const zr="vertex",Gr="none",Vr="frame",jr="render",Hr="object",Wr="readOnly",$r="writeOnly",qr="readWrite",Yr=["setup","analyze","generate"],Xr=["fragment","vertex","compute"],Kr=["x","y","z","w"];let Zr=0;class Qr extends Oe{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Gr,this.updateBeforeType=Gr,this.updateAfterType=Gr,this.uuid=Ye.generateUUID(),this.version=0,this._cacheKey=null,this._cacheKeyVersion=0,this.global=!1,this.isNode=!0,Object.defineProperty(this,"id",{value:Zr++})}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,Vr)}onRenderUpdate(e){return this.onUpdate(e,jr)}onObjectUpdate(e){return this.onUpdate(e,Hr)}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 Dr(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=Ur(this,e),this._cacheKeyVersion=this.version),this._cacheKey}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)}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 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){e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length;for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}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?(i=this.generate(e)||"",r.snippet=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 Dr(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 Jr extends Qr{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){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class en extends Qr{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 tn extends Qr{static get type(){return"TempNode"}constructor(e){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 sn extends tn{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=this.nodes,r=e.getComponentType(s),n=[];for(const t of i){let s=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(s=e.format(s,i,r)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}const rn=Kr.join("");class nn extends Qr{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(Kr.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===rn.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 on extends tn{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.getTypeFromLength(s.length,i.getNodeType(e)),o=i.build(e,n),a=t.build(e,r),h=e.getTypeLength(r),l=[];for(let e=0;e<h;e++){const t=Kr[e];t===s[0]?(l.push(o),e+=s.length-1):l.push(a+"."+t)}return`${e.getType(r)}( ${l.join(", ")} )`}}class an extends tn{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=Kr[e];s===t[l]?(h.push("1.0 - "+o+"."+s),l++):h.push(o+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class hn extends Qr{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?Lr(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=Lr(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.")}}class ln extends hn{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 e.format(this.generateConst(e),s,t)}}let un=null;const cn=new Map;function dn(e,t){if(cn.has(e))console.warn(`Redefinition of method chaining ${e}`);else{if("function"!=typeof t)throw new Error(`Node element ${e} is not a function`);cn.set(e,t)}}const pn=e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),mn=e=>pn(e).split("").sort().join(""),gn={setup(e,t){const s=t.shift();return e(kn(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(un.assign(s,...e),s);if(cn.has(t)){const i=cn.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&cn.has(t.slice(0,t.length-6))){const i=cn.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=pn(t),Ln(new nn(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=mn(t.slice(3).toLowerCase()),s=>Ln(new on(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=mn(t.slice(4).toLowerCase()),()=>Ln(new an(Ln(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Ln(new nn(e,t));if(!0===/^\d+$/.test(t))return Ln(new Jr(s,new ln(Number(t),"uint")))}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)},fn=new WeakMap,yn=new WeakMap,bn=function(e,t=null){for(const s in e)e[s]=Ln(e[s],t);return e},xn=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=Ln(e[i],t);return e},_n=function(e,t=null,s=null,i=null){const r=e=>Ln(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...zn(t))):null!==s?(s=Ln(s),(...i)=>r(new e(t,...zn(i),s))):(...s)=>r(new e(t,...zn(s)))},vn=function(e,...t){return Ln(new e(...zn(t)))};class Tn extends Qr{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}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=yn.get(e.constructor);void 0===i&&(i=new WeakMap,yn.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=Ln(e.buildFunctionNode(t)),i.set(t,n)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(n),r=Ln(n.call(s))}else{const i=t.jsFunc,n=null!==s?i(s,e):i(e);r=Ln(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 Sn extends Qr{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 kn(e),Ln(new Tn(this,e))}setup(){return this.call()}}const wn=[!1,!0],Mn=[0,1,2,3],Nn=[-1,-2],An=[.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],En=new Map;for(const e of wn)En.set(e,new ln(e));const Cn=new Map;for(const e of Mn)Cn.set(e,new ln(e,"uint"));const Rn=new Map([...Cn].map((e=>new ln(e.value,"int"))));for(const e of Nn)Rn.set(e,new ln(e,"int"));const Pn=new Map([...Rn].map((e=>new ln(e.value))));for(const e of An)Pn.set(e,new ln(e));for(const e of An)Pn.set(-e,new ln(-e));const Bn={bool:En,uint:Cn,ints:Rn,float:Pn},Fn=new Map([...En,...Pn]),In=(e,t)=>Fn.has(e)?Fn.get(e):!0===e.isNode?e:new ln(e,t),Un=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 Ln(t.get(s[0]));if(1===s.length){const t=In(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Ln(t):Ln(new en(t,e))}const i=s.map((e=>In(e)));return Ln(new sn(i,e))}},Dn=e=>"object"==typeof e&&null!==e?e.value:e;function On(e,t){return new Proxy(new Sn(e,t),gn)}const Ln=(e,t=null)=>function(e,t=null){const s=Lr(e);if("node"===s){let t=fn.get(e);return void 0===t&&(t=new Proxy(e,gn),fn.set(e,t),fn.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?Ln(In(e,t)):"shader"===s?jn(e):e}(e,t),kn=(e,t=null)=>new bn(e,t),zn=(e,t=null)=>new xn(e,t),Gn=(...e)=>new _n(...e),Vn=(...e)=>new vn(...e),jn=(e,t)=>{const s=new On(e,t),i=(...e)=>{let t;return kn(e),t=e[0]&&e[0].isNode?[...e]:e[0],s.call(t)};return i.shaderNode=s,i.setLayout=e=>(s.setLayout(e),i),i.once=()=>(s.once=!0,i),i};dn("toGlobal",(e=>(e.global=!0,e)));const Hn=e=>{un=e},Wn=()=>un,$n=(...e)=>un.If(...e);dn("append",(function(e){return un&&un.add(e),e}));const qn=new Un("color"),Yn=new Un("float",Bn.float),Xn=new Un("int",Bn.ints),Kn=new Un("uint",Bn.uint),Zn=new Un("bool",Bn.bool),Qn=new Un("vec2"),Jn=new Un("ivec2"),eo=new Un("uvec2"),to=new Un("bvec2"),so=new Un("vec3"),io=new Un("ivec3"),ro=new Un("uvec3"),no=new Un("bvec3"),oo=new Un("vec4"),ao=new Un("ivec4"),ho=new Un("uvec4"),lo=new Un("bvec4"),uo=new Un("mat2"),co=new Un("mat3"),po=new Un("mat4");dn("toColor",qn),dn("toFloat",Yn),dn("toInt",Xn),dn("toUint",Kn),dn("toBool",Zn),dn("toVec2",Qn),dn("toIVec2",Jn),dn("toUVec2",eo),dn("toBVec2",to),dn("toVec3",so),dn("toIVec3",io),dn("toUVec3",ro),dn("toBVec3",no),dn("toVec4",oo),dn("toIVec4",ao),dn("toUVec4",ho),dn("toBVec4",lo),dn("toMat2",uo),dn("toMat3",co),dn("toMat4",po);dn("element",Gn(Jr)),dn("convert",((e,t)=>Ln(new en(Ln(e),t))));class mo extends Qr{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.version=0,this.shared=t,this.order=s,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}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 go=e=>new mo(e),fo=(e,t=0)=>new mo(e,!0,t),yo=fo("frame"),bo=fo("render"),xo=go("object");class _o extends hn{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=xo}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 vo=(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 Ln(new _o(i,s))};class To extends Qr{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 So=(e,t)=>Ln(new To(e,t,!0)),wo=Vn(To,"vec4","DiffuseColor"),Mo=Vn(To,"vec3","EmissiveColor"),No=Vn(To,"float","Roughness"),Ao=Vn(To,"float","Metalness"),Eo=Vn(To,"float","Clearcoat"),Co=Vn(To,"float","ClearcoatRoughness"),Ro=Vn(To,"vec3","Sheen"),Po=Vn(To,"float","SheenRoughness"),Bo=Vn(To,"float","Iridescence"),Fo=Vn(To,"float","IridescenceIOR"),Io=Vn(To,"float","IridescenceThickness"),Uo=Vn(To,"float","AlphaT"),Do=Vn(To,"float","Anisotropy"),Oo=Vn(To,"vec3","AnisotropyT"),Lo=Vn(To,"vec3","AnisotropyB"),ko=Vn(To,"color","SpecularColor"),zo=Vn(To,"float","SpecularF90"),Go=Vn(To,"float","Shininess"),Vo=Vn(To,"vec4","Output"),jo=Vn(To,"float","dashSize"),Ho=Vn(To,"float","gapSize"),Wo=Vn(To,"float","IOR"),$o=Vn(To,"float","Transmission"),qo=Vn(To,"float","Thickness"),Yo=Vn(To,"float","AttenuationDistance"),Xo=Vn(To,"color","AttenuationColor"),Ko=Vn(To,"float","Dispersion");class Zo extends tn{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 Kr.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)}}dn("assign",Gn(Zo));class Qo extends tn{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))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];if(void 0===s)throw new Error(`FunctionCallNode: Input '${e.name}' not found in FunctionNode.`);t.push(n(s,e))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}dn("call",((e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?zn(t):kn(t[0]),Ln(new Qo(Ln(e),t)))));class Jo extends tn{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Jo(e,t,s);for(let t=0;t<i.length-1;t++)r=new Jo(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s}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)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"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):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?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):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);return"void"!==t?"<"===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} < ${l} )`,n,t):"<="===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} <= ${l} )`,n,t):">"===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} > ${l} )`,n,t):">="===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} >= ${l} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${h})`,o,t):c?e.format(`${c}( ${h}, ${l} )`,n,t):e.format(`( ${h} ${s} ${l} )`,n,t):"void"!==o?c?e.format(`${c}( ${h}, ${l} )`,n,t):e.format(`${h} ${s} ${l}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const ea=Gn(Jo,"+"),ta=Gn(Jo,"-"),sa=Gn(Jo,"*"),ia=Gn(Jo,"/"),ra=Gn(Jo,"%"),na=Gn(Jo,"=="),oa=Gn(Jo,"!="),aa=Gn(Jo,"<"),ha=Gn(Jo,">"),la=Gn(Jo,"<="),ua=Gn(Jo,">="),ca=Gn(Jo,"&&"),da=Gn(Jo,"||"),pa=Gn(Jo,"!"),ma=Gn(Jo,"^^"),ga=Gn(Jo,"&"),fa=Gn(Jo,"~"),ya=Gn(Jo,"|"),ba=Gn(Jo,"^"),xa=Gn(Jo,"<<"),_a=Gn(Jo,">>");dn("add",ea),dn("sub",ta),dn("mul",sa),dn("div",ia),dn("modInt",ra),dn("equal",na),dn("notEqual",oa),dn("lessThan",aa),dn("greaterThan",ha),dn("lessThanEqual",la),dn("greaterThanEqual",ua),dn("and",ca),dn("or",da),dn("not",pa),dn("xor",ma),dn("bitAnd",ga),dn("bitNot",fa),dn("bitOr",ya),dn("bitXor",ba),dn("shiftLeft",xa),dn("shiftRight",_a);dn("remainder",((...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),ra(...e))));class va extends tn{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=i}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===va.LENGTH||t===va.DISTANCE||t===va.DOT?"float":t===va.CROSS?"vec3":t===va.ALL?"bool":t===va.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===va.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,h=!0===e.renderer.isWebGLRenderer;if(s===va.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=oo(so(i),0):s=oo(so(s),0);const r=sa(s,i).xyz;return Oa(r).build(e,t)}if(s===va.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===va.ONE_MINUS)return ta(1,n).build(e,t);if(s===va.RECIPROCAL)return ia(1,n).build(e,t);if(s===va.DIFFERENCE)return Wa(ta(n,o)).build(e,t);{const l=[];return s===va.CROSS||s===va.MOD?l.push(n.build(e,i),o.build(e,i)):h&&s===va.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h&&(s===va.MIN||s===va.MAX)||s===va.MOD?l.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):s===va.REFRACT?l.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===va.MIX?l.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(l.push(n.build(e,r)),null!==o&&l.push(o.build(e,r)),null!==a&&l.push(a.build(e,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}}va.ALL="all",va.ANY="any",va.EQUALS="equals",va.RADIANS="radians",va.DEGREES="degrees",va.EXP="exp",va.EXP2="exp2",va.LOG="log",va.LOG2="log2",va.SQRT="sqrt",va.INVERSE_SQRT="inversesqrt",va.FLOOR="floor",va.CEIL="ceil",va.NORMALIZE="normalize",va.FRACT="fract",va.SIN="sin",va.COS="cos",va.TAN="tan",va.ASIN="asin",va.ACOS="acos",va.ATAN="atan",va.ABS="abs",va.SIGN="sign",va.LENGTH="length",va.NEGATE="negate",va.ONE_MINUS="oneMinus",va.DFDX="dFdx",va.DFDY="dFdy",va.ROUND="round",va.RECIPROCAL="reciprocal",va.TRUNC="trunc",va.FWIDTH="fwidth",va.BITCAST="bitcast",va.TRANSPOSE="transpose",va.ATAN2="atan2",va.MIN="min",va.MAX="max",va.MOD="mod",va.STEP="step",va.REFLECT="reflect",va.DISTANCE="distance",va.DIFFERENCE="difference",va.DOT="dot",va.CROSS="cross",va.POW="pow",va.TRANSFORM_DIRECTION="transformDirection",va.MIX="mix",va.CLAMP="clamp",va.REFRACT="refract",va.SMOOTHSTEP="smoothstep",va.FACEFORWARD="faceforward";const Ta=Yn(1e-6),Sa=Yn(Math.PI),wa=Gn(va,va.ALL),Ma=Gn(va,va.ANY),Na=Gn(va,va.EQUALS),Aa=Gn(va,va.RADIANS),Ea=Gn(va,va.DEGREES),Ca=Gn(va,va.EXP),Ra=Gn(va,va.EXP2),Pa=Gn(va,va.LOG),Ba=Gn(va,va.LOG2),Fa=Gn(va,va.SQRT),Ia=Gn(va,va.INVERSE_SQRT),Ua=Gn(va,va.FLOOR),Da=Gn(va,va.CEIL),Oa=Gn(va,va.NORMALIZE),La=Gn(va,va.FRACT),ka=Gn(va,va.SIN),za=Gn(va,va.COS),Ga=Gn(va,va.TAN),Va=Gn(va,va.ASIN),ja=Gn(va,va.ACOS),Ha=Gn(va,va.ATAN),Wa=Gn(va,va.ABS),$a=Gn(va,va.SIGN),qa=Gn(va,va.LENGTH),Ya=Gn(va,va.NEGATE),Xa=Gn(va,va.ONE_MINUS),Ka=Gn(va,va.DFDX),Za=Gn(va,va.DFDY),Qa=Gn(va,va.ROUND),Ja=Gn(va,va.RECIPROCAL),eh=Gn(va,va.TRUNC),th=Gn(va,va.FWIDTH);va.BITCAST;const sh=Gn(va,va.TRANSPOSE),ih=Gn(va,va.ATAN2),rh=Gn(va,va.MIN),nh=Gn(va,va.MAX),oh=Gn(va,va.MOD),ah=Gn(va,va.STEP),hh=Gn(va,va.REFLECT),lh=Gn(va,va.DISTANCE),uh=Gn(va,va.DIFFERENCE),ch=Gn(va,va.DOT),dh=Gn(va,va.CROSS),ph=Gn(va,va.POW),mh=Gn(va,va.POW,2),gh=Gn(va,va.POW,3),fh=Gn(va,va.POW,4),yh=Gn(va,va.TRANSFORM_DIRECTION),bh=Gn(va,va.MIX),xh=(e,t=0,s=1)=>Ln(new va(va.CLAMP,Ln(e),Ln(t),Ln(s))),_h=Gn(va,va.REFRACT),vh=Gn(va,va.SMOOTHSTEP),Th=Gn(va,va.FACEFORWARD),Sh=jn((([e])=>{const t=ch(e.xy,Qn(12.9898,78.233)),s=oh(t,Sa);return La(ka(s).mul(43758.5453))}));dn("all",wa),dn("any",Ma),dn("equals",Na),dn("radians",Aa),dn("degrees",Ea),dn("exp",Ca),dn("exp2",Ra),dn("log",Pa),dn("log2",Ba),dn("sqrt",Fa),dn("inverseSqrt",Ia),dn("floor",Ua),dn("ceil",Da),dn("normalize",Oa),dn("fract",La),dn("sin",ka),dn("cos",za),dn("tan",Ga),dn("asin",Va),dn("acos",ja),dn("atan",Ha),dn("abs",Wa),dn("sign",$a),dn("length",qa),dn("lengthSq",(e=>ch(e,e))),dn("negate",Ya),dn("oneMinus",Xa),dn("dFdx",Ka),dn("dFdy",Za),dn("round",Qa),dn("reciprocal",Ja),dn("trunc",eh),dn("fwidth",th),dn("atan2",ih),dn("min",rh),dn("max",nh),dn("mod",oh),dn("step",ah),dn("reflect",hh),dn("distance",lh),dn("dot",ch),dn("cross",dh),dn("pow",ph),dn("pow2",mh),dn("pow3",gh),dn("pow4",fh),dn("transformDirection",yh),dn("mix",((e,t,s)=>bh(t,s,e))),dn("clamp",xh),dn("refract",_h),dn("smoothstep",((e,t,s)=>vh(t,s,e))),dn("faceForward",Th),dn("difference",uh),dn("saturate",(e=>xh(e))),dn("cbrt",(e=>sa($a(e),ph(Wa(e),1/3)))),dn("transpose",sh),dn("rand",Sh);class wh extends Qr{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}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="void"!==t,h=a?((e,t)=>Ln(new To(e,t)))(s).build(e):"";i.nodeProperty=h;const l=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${l} ) {\n\n`).addFlowTab();let u=n.build(e,s);if(u&&(u=a?h+" = "+u+";":"return "+u+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+u+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(t=a?h+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const Mh=Gn(wh);dn("select",Mh);dn("cond",((...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),Mh(...e))));class Nh extends Qr{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 Ah=Gn(Nh);dn("context",Ah),dn("label",((e,t)=>Ah(e,{label:t})));class Eh extends Qr{static get type(){return"VarNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,i=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),n=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${n}`,this),r}}const Ch=Gn(Eh);dn("toVar",((...e)=>Ch(...e).append()));dn("temp",(e=>(console.warn('TSL: "temp" is deprecated. Use ".toVar()" instead.'),Ch(e))));class Rh extends Qr{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);if(void 0===t.propertyName){const i=this.getNodeType(e),r=e.getPropertyName(s,zr);e.flowNodeFromShaderStage(zr,this.node,i,r),t.propertyName=r}return e.getPropertyName(s)}}const Ph=Gn(Rh);dn("varying",Ph);const Bh=jn((([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"}]}),Fh=jn((([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"}]}),Ih="WorkingColorSpace",Uh="OutputColorSpace";class Dh extends tn{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===Ih?it.workingColorSpace:t===Uh?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!==it.enabled&&s!==i&&s&&i?(it.getTransfer(s)===Se&&(r=oo(Bh(r.rgb),r.a)),it.getPrimaries(s)!==it.getPrimaries(i)&&(r=oo(co(it._getMatrix(new Ke,s,i)).mul(r.rgb),r.a)),it.getTransfer(i)===Se&&(r=oo(Fh(r.rgb),r.a)),r):r}}const Oh=(e,t)=>Ln(new Dh(Ln(e),t,Ih));dn("toOutputColorSpace",(e=>Ln(new Dh(Ln(e),Ih,Uh)))),dn("toWorkingColorSpace",(e=>Ln(new Dh(Ln(e),Uh,Ih)))),dn("workingToColorSpace",((e,t)=>Ln(new Dh(Ln(e),Ih,t)))),dn("colorSpaceToWorking",Oh);let Lh=class extends Jr{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 kh extends Qr{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=Hr}setGroup(e){return this.group=e,this}element(e){return Ln(new Lh(this,Ln(e)))}setNodeType(e){const t=vo(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 zh extends kh{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(bo)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const Gh=(e,t,s)=>Ln(new zh(e,t,s));class Vh extends tn{static get type(){return"ToneMappingNode"}constructor(e,t=jh,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){return Ir(super.getCacheKey(),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=oo(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const jh=Gh("toneMappingExposure","float");dn("toneMapping",((e,t,s)=>((e,t,s)=>Ln(new Vh(e,Ln(t),Ln(s))))(t,s,e)));class Hh extends hn{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=Fe,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 Di(s,r),a=new Li(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=Ph(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 Wh=(e,t,s,i)=>Ln(new Hh(e,t,s,i)),$h=(e,t,s,i)=>Wh(e,t,s,i).setInstanced(!0),qh=(e,t,s,i)=>((e,t,s,i)=>Wh(e,t,s,i).setUsage(Ie))(e,t,s,i).setInstanced(!0);dn("toAttribute",(e=>Wh(e.value)));class Yh extends Qr{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.updateBeforeType=Hr,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}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)}generate(e){const{shaderStage:t}=e;if("compute"===t){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}}}dn("compute",((e,t,s)=>Ln(new Yh(Ln(e),t,s))));class Xh extends Qr{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){return this.node.getNodeType(e)}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 Kh=(e,...t)=>Ln(new Xh(Ln(e),...t));dn("cache",Kh);class Zh extends Qr{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)}}dn("bypass",Gn(Zh));class Qh extends Qr{static get type(){return"RemapNode"}constructor(e,t,s,i=Yn(0),r=Yn(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 Jh=Gn(Qh,null,null,{doClamp:!1}),el=Gn(Qh);dn("remap",Jh),dn("remapClamp",el);class tl extends Qr{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 sl=Gn(tl);dn("discard",(e=>(e?Mh(e,sl("discard")):sl("discard")).append()));class il extends tn{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutput=!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!==it.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}dn("renderOutput",((e,t=null,s=null)=>Ln(new il(Ln(e),t,s))));class rl extends Qr{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 Ph(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 nl=(e,t)=>Ln(new rl(e,t)),ol=e=>nl("uv"+(e>0?e:""),"vec2");class al extends Qr{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 hl=Gn(al);class ll extends _o{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vr}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 ul=Gn(ll);class cl extends _o{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=Gr,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===k?"uvec4":this.value.type===L?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return ol(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=vo(this.value.matrix)),this._matrixUniform.mul(so(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Vr:Gr,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(Xn(hl(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,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=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===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:i,biasNode:a,compareNode:h,depthNode:l,gradNode:u}=s,c=this.generateUV(e,t),d=i?i.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(i)&&(a=Oh(sl(a,h),i.colorSpace).setup(e).build(e,h)),e.format(a,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=Ln(e),t.referenceNode=this.getSelf(),Ln(t)}blur(e){const t=this.clone();return t.biasNode=Ln(e).mul(ul(t)),t.referenceNode=this.getSelf(),Ln(t)}level(e){const t=this.clone();return t.levelNode=Ln(e),t.referenceNode=this.getSelf(),Ln(t)}size(e){return hl(this,e)}bias(e){const t=this.clone();return t.biasNode=Ln(e),t.referenceNode=this.getSelf(),Ln(t)}compare(e){const t=this.clone();return t.compareNode=Ln(e),t.referenceNode=this.getSelf(),Ln(t)}grad(e,t){const s=this.clone();return s.gradNode=[Ln(e),Ln(t)],s.referenceNode=this.getSelf(),Ln(s)}depth(e){const t=this.clone();return t.depthNode=Ln(e),t.referenceNode=this.getSelf(),Ln(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 dl=Gn(cl),pl=(...e)=>dl(...e).setSampler(!1),ml=vo("float").label("cameraNear").setGroup(bo).onRenderUpdate((({camera:e})=>e.near)),gl=vo("float").label("cameraFar").setGroup(bo).onRenderUpdate((({camera:e})=>e.far)),fl=vo("mat4").label("cameraProjectionMatrix").setGroup(bo).onRenderUpdate((({camera:e})=>e.projectionMatrix)),yl=vo("mat4").label("cameraViewMatrix").setGroup(bo).onRenderUpdate((({camera:e})=>e.matrixWorldInverse)),bl=vo(new bt).label("cameraPosition").setGroup(bo).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));class xl extends Qr{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Hr,this._uniformNode=new _o(null)}getNodeType(){const e=this.scope;return e===xl.WORLD_MATRIX?"mat4":e===xl.POSITION||e===xl.VIEW_POSITION||e===xl.DIRECTION||e===xl.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===xl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===xl.POSITION)s.value=s.value||new bt,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===xl.SCALE)s.value=s.value||new bt,s.value.setFromMatrixScale(t.matrixWorld);else if(i===xl.DIRECTION)s.value=s.value||new bt,t.getWorldDirection(s.value);else if(i===xl.VIEW_POSITION){const i=e.camera;s.value=s.value||new bt,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===xl.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t!==xl.POSITION&&t!==xl.VIEW_POSITION&&t!==xl.DIRECTION&&t!==xl.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}xl.WORLD_MATRIX="worldMatrix",xl.POSITION="position",xl.SCALE="scale",xl.VIEW_POSITION="viewPosition",xl.DIRECTION="direction",xl.DIRECTION,xl.WORLD_MATRIX;const _l=Gn(xl,xl.POSITION);xl.SCALE,xl.VIEW_POSITION;class vl extends xl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Tl=Vn(vl,vl.WORLD_MATRIX),Sl=vo(new Ke).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),wl=yl.mul(Tl).toVar("modelViewMatrix"),Ml=nl("position","vec3"),Nl=Ml.varying("positionLocal"),Al=Ml.varying("positionPrevious"),El=Tl.mul(Nl).xyz.varying("v_positionWorld"),Cl=Nl.transformDirection(Tl).varying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),Rl=wl.mul(Nl).xyz.varying("v_positionView"),Pl=Rl.negate().varying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Bl extends Qr{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Ue&&1===s.side?"false":e.getFrontFacing()}}const Fl=Yn(Vn(Bl)).mul(2).sub(1),Il=nl("normal","vec3"),Ul=jn((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),so(0,1,0)):Il),"vec3").once()().toVar("normalLocal"),Dl=Rl.dFdx().cross(Rl.dFdy()).normalize().toVar("normalFlat"),Ol=jn((e=>{let t;return t=!0===e.material.flatShading?Dl:Ph(jl(Ul),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),Ll=Ph(Ol.transformDirection(yl),"v_normalWorld").normalize().toVar("normalWorld"),kl=jn((e=>e.context.setupNormal()),"vec3").once()().mul(Fl).toVar("transformedNormalView"),zl=kl.transformDirection(yl).toVar("transformedNormalWorld"),Gl=jn((e=>e.context.setupClearcoatNormal()),"vec3").once()().mul(Fl).toVar("transformedClearcoatNormalView"),Vl=jn((([e,t=Tl])=>{const s=co(t),i=e.div(so(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),jl=jn((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=Sl.mul(e);return yl.transformDirection(i)})),Hl=vo(0).onReference((({material:e})=>e)).onRenderUpdate((({material:e})=>e.refractionRatio)),Wl=Pl.negate().reflect(kl),$l=Pl.negate().refract(kl,Hl),ql=Wl.transformDirection(yl).toVar("reflectVector"),Yl=$l.transformDirection(yl).toVar("reflectVector");class Xl extends cl{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?ql:e.mapping===T?Yl:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),so(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==De&&s.isRenderTargetTexture?t:so(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Kl=Gn(Xl);class Zl extends _o{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 Ql=(e,t,s)=>Ln(new Zl(e,t,s));class Jl extends Jr{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType();return e.format(t,"vec4",s)}}class eu extends Zl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=jr,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,s=this.getElementLength(),i=this.getElementType();if(1===s)for(let s=0;s<e.length;s++){t[4*s]=e[s]}else if("color"===i)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 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;this._elementType=null===this.elementType?Lr(this.array[0]):this.elementType,this._elementLength=e.getTypeLength(this._elementType);let s=Float32Array;return"i"===this._elementType.charAt(0)?s=Int32Array:"u"===this._elementType.charAt(0)&&(s=Uint32Array),this.value=new s(4*t),this.bufferCount=t,this.bufferType=e.changeComponentType("vec4",e.getComponentType(this._elementType)),super.setup(e)}element(e){return Ln(new Jl(this,Ln(e)))}}const tu=(e,t)=>Ln(new eu(e,t));class su extends Jr{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 iu extends Qr{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=Hr}element(e){return Ln(new su(this,Ln(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Ql(null,e,this.count):Array.isArray(this.getValueFromReference())?tu(null,e):"texture"===e?dl(null):"cubeTexture"===e?Kl(null):vo(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 ru=(e,t,s)=>Ln(new iu(e,t,s)),nu=(e,t,s,i)=>Ln(new iu(e,t,i,s));class ou extends iu{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 au=(e,t,s)=>Ln(new ou(e,t,s)),hu=jn((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),nl("tangent","vec4"))))(),lu=hu.xyz.toVar("tangentLocal"),uu=wl.mul(oo(lu,0)).xyz.varying("v_tangentView").normalize().toVar("tangentView");var cu;const du=co(uu,Ph((cu=Ol.cross(uu),cu.mul(hu.w).xyz),"v_bitangentView").normalize().toVar("bitangentView"),Ol),pu=(()=>{let e=Lo.cross(Pl);return e=e.cross(Lo).normalize(),e=bh(e,kl,Do.mul(No.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),mu=jn((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=Fl.mul(m.inverseSqrt());return ea(d.mul(i.x,g),p.mul(i.y,g),l.mul(i.z)).normalize()}));class gu extends tn{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=so(i.xy.mul(s),i.z));let r=null;if(1===t)r=jl(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?du.mul(i).normalize():mu({eye_pos:Rl,surf_norm:Ol,mapN:i,uv:ol()})}return r}}const fu=Gn(gu),yu=jn((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||ol()),forceUVContext:!0}),i=Yn(s((e=>e)));return Qn(Yn(s((e=>e.add(e.dFdx())))).sub(i),Yn(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),bu=jn((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(Fl),l=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(l).normalize()}));class xu extends tn{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=yu({textureNode:this.textureNode,bumpScale:e});return bu({surf_pos:Rl,surf_norm:Ol,dHdxy:t})}}const _u=Gn(xu),vu=new Map;class Tu extends Qr{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=vu.get(e);return void 0===s&&(s=au(e,t),vu.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===Tu.COLOR){const e=void 0!==t.color?this.getColor(s):so();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===Tu.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===Tu.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Yn(1);else if(s===Tu.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularMap?e.mul(this.getTexture(s).a):e}else if(s===Tu.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===Tu.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===Tu.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===Tu.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===Tu.NORMAL)t.normalMap?(i=fu(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?_u(this.getTexture("bump").r,this.getFloat("bumpScale")):Ol;else if(s===Tu.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Tu.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Tu.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?fu(this.getTexture(s),this.getCache(s+"Scale","vec2")):Ol;else if(s===Tu.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===Tu.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===Tu.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=uo(rc.x,rc.y,rc.y.negate(),rc.x).mul(e.rg.mul(2).sub(Qn(1)).normalize().mul(e.b))}else i=rc;else if(s===Tu.IRIDESCENCE_THICKNESS){const e=ru("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=ru("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===Tu.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===Tu.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===Tu.IOR)i=this.getFloat(s);else if(s===Tu.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===Tu.AO_MAP)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}}Tu.ALPHA_TEST="alphaTest",Tu.COLOR="color",Tu.OPACITY="opacity",Tu.SHININESS="shininess",Tu.SPECULAR="specular",Tu.SPECULAR_STRENGTH="specularStrength",Tu.SPECULAR_INTENSITY="specularIntensity",Tu.SPECULAR_COLOR="specularColor",Tu.REFLECTIVITY="reflectivity",Tu.ROUGHNESS="roughness",Tu.METALNESS="metalness",Tu.NORMAL="normal",Tu.CLEARCOAT="clearcoat",Tu.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Tu.CLEARCOAT_NORMAL="clearcoatNormal",Tu.EMISSIVE="emissive",Tu.ROTATION="rotation",Tu.SHEEN="sheen",Tu.SHEEN_ROUGHNESS="sheenRoughness",Tu.ANISOTROPY="anisotropy",Tu.IRIDESCENCE="iridescence",Tu.IRIDESCENCE_IOR="iridescenceIOR",Tu.IRIDESCENCE_THICKNESS="iridescenceThickness",Tu.IOR="ior",Tu.TRANSMISSION="transmission",Tu.THICKNESS="thickness",Tu.ATTENUATION_DISTANCE="attenuationDistance",Tu.ATTENUATION_COLOR="attenuationColor",Tu.LINE_SCALE="scale",Tu.LINE_DASH_SIZE="dashSize",Tu.LINE_GAP_SIZE="gapSize",Tu.LINE_WIDTH="linewidth",Tu.LINE_DASH_OFFSET="dashOffset",Tu.POINT_WIDTH="pointWidth",Tu.DISPERSION="dispersion",Tu.LIGHT_MAP="light",Tu.AO_MAP="ao";const Su=Vn(Tu,Tu.ALPHA_TEST),wu=Vn(Tu,Tu.COLOR),Mu=Vn(Tu,Tu.SHININESS),Nu=Vn(Tu,Tu.EMISSIVE),Au=Vn(Tu,Tu.OPACITY),Eu=Vn(Tu,Tu.SPECULAR),Cu=Vn(Tu,Tu.SPECULAR_INTENSITY),Ru=Vn(Tu,Tu.SPECULAR_COLOR),Pu=Vn(Tu,Tu.SPECULAR_STRENGTH),Bu=Vn(Tu,Tu.REFLECTIVITY),Fu=Vn(Tu,Tu.ROUGHNESS),Iu=Vn(Tu,Tu.METALNESS),Uu=Vn(Tu,Tu.NORMAL).context({getUV:null}),Du=Vn(Tu,Tu.CLEARCOAT),Ou=Vn(Tu,Tu.CLEARCOAT_ROUGHNESS),Lu=Vn(Tu,Tu.CLEARCOAT_NORMAL).context({getUV:null}),ku=Vn(Tu,Tu.ROTATION),zu=Vn(Tu,Tu.SHEEN),Gu=Vn(Tu,Tu.SHEEN_ROUGHNESS),Vu=Vn(Tu,Tu.ANISOTROPY),ju=Vn(Tu,Tu.IRIDESCENCE),Hu=Vn(Tu,Tu.IRIDESCENCE_IOR),Wu=Vn(Tu,Tu.IRIDESCENCE_THICKNESS),$u=Vn(Tu,Tu.TRANSMISSION),qu=Vn(Tu,Tu.THICKNESS),Yu=Vn(Tu,Tu.IOR),Xu=Vn(Tu,Tu.ATTENUATION_DISTANCE),Ku=Vn(Tu,Tu.ATTENUATION_COLOR),Zu=Vn(Tu,Tu.LINE_SCALE),Qu=Vn(Tu,Tu.LINE_DASH_SIZE),Ju=Vn(Tu,Tu.LINE_GAP_SIZE);Tu.LINE_WIDTH;const ec=Vn(Tu,Tu.LINE_DASH_OFFSET);Tu.POINT_WIDTH;const tc=Vn(Tu,Tu.DISPERSION),sc=Vn(Tu,Tu.LIGHT_MAP),ic=Vn(Tu,Tu.AO_MAP),rc=vo(new Xe).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))}));class nc extends tn{static get type(){return"ModelViewProjectionNode"}constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return Ph(e.context.mvp);const t=this.positionNode||Nl,s=e.renderer.nodes.modelViewMatrix||wl;return fl.mul(s).mul(t)}}const oc=Gn(nc);class ac extends Qr{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===ac.VERTEX)i=e.getVertexIndex();else if(s===ac.INSTANCE)i=e.getInstanceIndex();else if(s===ac.DRAW)i=e.getDrawIndex();else if(s===ac.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===ac.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==ac.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Ph(this).build(e,t)}return r}}ac.VERTEX="vertex",ac.INSTANCE="instance",ac.SUBGROUP="subgroup",ac.INVOCATION_LOCAL="invocationLocal",ac.INVOCATION_SUBGROUP="invocationSubgroup",ac.DRAW="draw";const hc=Vn(ac,ac.VERTEX),lc=Vn(ac,ac.INSTANCE);ac.SUBGROUP,ac.INVOCATION_SUBGROUP,ac.INVOCATION_LOCAL;const uc=Vn(ac,ac.DRAW);class cc extends Qr{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=Vr,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=Ql(s.array,"mat4",Math.max(t,1)).element(lc);else{const e=new Cr(s.array,16,1);this.buffer=e;const t=s.usage===Ie?qh:$h,i=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];r=po(...i)}this.instanceMatrixNode=r}if(i&&null===n){const e=new Gi(i.array,3),t=i.usage===Ie?qh:$h;this.bufferColor=e,n=so(t(e,"vec3",3,0)),this.instanceColorNode=n}const o=r.mul(Nl).xyz;if(Nl.assign(o),e.hasGeometryAttribute("normal")){const e=Vl(Ul,r);Ul.assign(e)}null!==this.instanceColorNode&&So("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 dc extends cc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instanceMesh=e}}const pc=Gn(dc);class mc extends Qr{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=lc:this.batchingIdNode=uc);const t=jn((([e])=>{const t=hl(pl(this.batchMesh._indirectTexture),0),s=Xn(e).modInt(Xn(t)),i=Xn(e).div(Xn(t));return pl(this.batchMesh._indirectTexture,Jn(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(Xn(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=hl(pl(i),0),n=Yn(s).mul(4).toInt().toVar(),o=n.modInt(r),a=n.div(Xn(r)),h=po(pl(i,Jn(o,a)),pl(i,Jn(o.add(1),a)),pl(i,Jn(o.add(2),a)),pl(i,Jn(o.add(3),a))),l=this.batchMesh._colorsTexture;if(null!==l){const e=jn((([e])=>{const t=hl(pl(l),0).x,s=e,i=s.modInt(t),r=s.div(t);return pl(l,Jn(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);So("vec3","vBatchColor").assign(t)}const u=co(h);Nl.assign(h.mul(Nl));const c=Ul.div(so(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),d=u.mul(c).xyz;Ul.assign(d),e.hasGeometryAttribute("tangent")&&lu.mulAssign(u)}}const gc=Gn(mc),fc=new WeakMap;class yc extends Qr{static get type(){return"SkinningNode"}constructor(e,t=!1){let s,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Hr,this.skinIndexNode=nl("skinIndex","uvec4"),this.skinWeightNode=nl("skinWeight","vec4"),t?(s=ru("bindMatrix","mat4"),i=ru("bindMatrixInverse","mat4"),r=nu("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=vo(e.bindMatrix,"mat4"),i=vo(e.bindMatrixInverse,"mat4"),r=Ql(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=Nl){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=ea(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=Ul){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=ea(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=nu("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Al)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")}setup(e){this.needsPreviousBoneMatrices(e)&&Al.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(Nl.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Ul.assign(t),e.hasGeometryAttribute("tangent")&&lu.assign(t)}}generate(e,t){if("void"!==t)return Nl.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;fc.get(t)!==e.frameId&&(fc.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class bc extends Qr{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+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]=sl(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=null,n=null,o=null,a=null,h=null,l=null;i.isNode?(a="int",o=this.getVarName(t),r="0",n=i.build(e,a),h="<"):(a=i.type||"int",o=i.name||this.getVarName(t),r=i.start,n=i.end,h=i.condition,l=i.update,"number"==typeof r?r=e.generateConst(a,r):r&&r.isNode&&(r=r.build(e,a)),"number"==typeof n?n=e.generateConst(a,n):n&&n.isNode&&(n=n.build(e,a)),void 0!==r&&void 0===n?(r+=" - 1",n="0",h=">="):void 0!==n&&void 0===r&&(r="0",h="<"),void 0===h&&(h=Number(r)>Number(n)?">=":"<"));const u={start:r,end:n,condition:h},c=u.start,d=u.end;let p="",m="",g="";l||(l="int"===a||"uint"===a?h.includes("<")?"++":"--":h.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+c,m+=o+" "+h+" "+d,g+=o+" "+l;const f=`for ( ${p}; ${m}; ${g} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\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 xc=(...e)=>Ln(new bc(zn(e,"int"))).append(),_c=new WeakMap,vc=new pt,Tc=jn((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Xn(hc).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return pl(e,Jn(h,a)).depth(r).mul(t)}));class Sc extends Qr{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=vo(1),this.updateType=Hr}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=_c.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 ft(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 S=0;S<x.count;S++){const w=S*f;!0===t&&(vc.fromBufferAttribute(x,S),m[T+w+0]=vc.x,m[T+w+1]=vc.y,m[T+w+2]=vc.z,m[T+w+3]=0),!0===s&&(vc.fromBufferAttribute(_,S),m[T+w+4]=vc.x,m[T+w+5]=vc.y,m[T+w+6]=vc.z,m[T+w+7]=0),!0===i&&(vc.fromBufferAttribute(v,S),m[T+w+8]=vc.x,m[T+w+9]=vc.y,m[T+w+10]=vc.z,m[T+w+11]=4===v.itemSize?vc.w:1)}}function y(){g.dispose(),_c.delete(e),e.removeEventListener("dispose",y)}o={count:n,texture:g,stride:u,size:new Xe(c,d)},_c.set(e,o),e.addEventListener("dispose",y)}return o}(t);!0===s&&Nl.mulAssign(this.morphBaseInfluence),!0===i&&Ul.mulAssign(this.morphBaseInfluence);const l=Xn(h.width);xc(n,(({i:e})=>{const t=Yn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(pl(this.mesh.morphTexture,Jn(Xn(e).add(1),Xn(lc))).r):t.assign(ru("morphTargetInfluences","float").element(e).toVar()),!0===s&&Nl.addAssign(Tc({bufferMap:o,influence:t,stride:a,width:l,depth:e,offset:Xn(0)})),!0===i&&Ul.addAssign(Tc({bufferMap:o,influence:t,stride:a,width:l,depth:e,offset:Xn(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 wc=Gn(Sc);class Mc extends Qr{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}generate(){console.warn("Abstract function.")}}class Nc extends Mc{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Ac extends Nh{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:so().toVar("directDiffuse"),directSpecular:so().toVar("directSpecular"),indirectDiffuse:so().toVar("indirectDiffuse"),indirectSpecular:so().toVar("indirectSpecular")};return{radiance:so().toVar("radiance"),irradiance:so().toVar("irradiance"),iblIrradiance:so().toVar("iblIrradiance"),ambientOcclusion:Yn(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 Ec=Gn(Ac);class Cc extends Mc{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Rc,Pc;class Bc extends Qr{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Bc.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Gr;return this.scope!==Bc.SIZE&&this.scope!==Bc.VIEWPORT||(e=jr),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Bc.VIEWPORT?null!==t?Pc.copy(t.viewport):(e.getViewport(Pc),Pc.multiplyScalar(e.getPixelRatio())):null!==t?(Rc.width=t.width,Rc.height=t.height):e.getDrawingBufferSize(Rc)}setup(){const e=this.scope;let t=null;return t=e===Bc.SIZE?vo(Rc||(Rc=new Xe)):e===Bc.VIEWPORT?vo(Pc||(Pc=new pt)):Qn(Uc.div(Ic)),t}generate(e){if(this.scope===Bc.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Ic).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Bc.COORDINATE="coordinate",Bc.VIEWPORT="viewport",Bc.SIZE="size",Bc.UV="uv";const Fc=Vn(Bc,Bc.UV),Ic=Vn(Bc,Bc.SIZE),Uc=Vn(Bc,Bc.COORDINATE),Dc=Vn(Bc,Bc.VIEWPORT);Dc.zw,Dc.xy;const Oc=new Xe;class Lc extends cl{static get type(){return"ViewportTextureNode"}constructor(e=Fc,t=null,s=null){null===s&&((s=new Zi).minFilter=F),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Vr}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Oc);const s=this.value;s.image.width===Oc.width&&s.image.height===Oc.height||(s.image.width=Oc.width,s.image.height=Oc.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 kc=Gn(Lc,null,null,{generateMipmaps:!0});let zc=null;class Gc extends Lc{static get type(){return"ViewportDepthTextureNode"}constructor(e=Fc,t=null){null===zc&&(zc=new Qi),super(e,t,zc)}}const Vc=Gn(Gc);class jc extends Qr{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===jc.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===jc.DEPTH_BASE)null!==s&&(i=Yc().assign(s));else if(t===jc.DEPTH)i=e.isPerspectiveCamera?Wc(Rl.z,ml,gl):Hc(Rl.z,ml,gl);else if(t===jc.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=$c(s,ml,gl);i=Hc(e,ml,gl)}else i=s;else i=Hc(Rl.z,ml,gl);return i}}jc.DEPTH_BASE="depthBase",jc.DEPTH="depth",jc.LINEAR_DEPTH="linearDepth";const Hc=(e,t,s)=>e.add(t).div(t.sub(s)),Wc=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),$c=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),qc=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Ba(e.negate().div(t)),r=Ba(s.div(t));return i.div(r)},Yc=Gn(jc,jc.DEPTH_BASE),Xc=Vn(jc,jc.DEPTH);jc.LINEAR_DEPTH;Vc(),Xc.assign=e=>Yc(e);const Kc=Gn(class extends Qr{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}});class Zc extends Qr{static get type(){return"ClippingNode"}constructor(e=Zc.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===Zc.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Zc.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return jn((()=>{const s=Yn().toVar("distanceToPlane"),i=Yn().toVar("distanceToGradient"),r=Yn(1).toVar("clipOpacity"),n=t.length;if(!this.hardwareClipping&&n>0){const e=tu(t);xc(n,(({i:t})=>{const n=e.element(t);s.assign(Rl.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(vh(i.negate(),i,s))}))}const o=e.length;if(o>0){const t=tu(e),n=Yn(1).toVar("intersectionClipOpacity");xc(o,(({i:e})=>{const r=t.element(e);s.assign(Rl.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(vh(i.negate(),i,s).oneMinus())})),r.mulAssign(n.oneMinus())}wo.a.mulAssign(r),wo.a.equal(0).discard()}))()}setupDefault(e,t){return jn((()=>{const s=t.length;if(!this.hardwareClipping&&s>0){const e=tu(t);xc(s,(({i:t})=>{const s=e.element(t);Rl.dot(s.xyz).greaterThan(s.w).discard()}))}const i=e.length;if(i>0){const t=tu(e),s=Zn(!0).toVar("clipped");xc(i,(({i:e})=>{const i=t.element(e);s.assign(Rl.dot(i.xyz).greaterThan(i.w).and(s))})),s.discard()}}))()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),jn((()=>{const i=tu(e),r=Kc(t.getClipDistance());xc(s,(({i:e})=>{const t=i.element(e),s=Rl.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)}))}))()}}Zc.ALPHA_TO_COVERAGE="alphaToCoverage",Zc.DEFAULT="default",Zc.HARDWARE="hardware";const Qc=jn((([e])=>La(sa(1e4,ka(sa(17,e.x).add(sa(.1,e.y)))).mul(ea(.1,Wa(ka(sa(13,e.y).add(e.x)))))))),Jc=jn((([e])=>Qc(Qn(Qc(e.xy),e.z)))),ed=jn((([e])=>{const t=nh(qa(Ka(e.xyz)),qa(Za(e.xyz))),s=Yn(1).div(Yn(.05).mul(t)).toVar("pixScale"),i=Qn(Ra(Ua(Ba(s))),Ra(Da(Ba(s)))),r=Qn(Jc(Ua(i.x.mul(e.xyz))),Jc(Ua(i.y.mul(e.xyz)))),n=La(Ba(s)),o=ea(sa(n.oneMinus(),r.x),sa(n,r.y)),a=rh(n,n.oneMinus()),h=so(o.mul(o).div(sa(2,a).mul(ta(1,a))),o.sub(sa(.5,a)).div(ta(1,a)),ta(1,ta(1,o).mul(ta(1,o)).div(sa(2,a).mul(ta(1,a))))),l=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(h.x,h.y),h.z);return xh(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class td extends js{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.forceSinglePass=!1,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+Ur(this)}build(e){this.setup(e)}setupObserver(e){return new Pr(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e);const t=e.renderer,s=t.getRenderTarget();let i;e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const r=this.setupClipping(e);if(!0===this.depthWrite&&(null!==s?!0===s.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const n=this.setupLighting(e);null!==r&&e.stack.add(r);const o=oo(n,wo.a).max(0);if(i=this.setupOutput(e,o),Vo.assign(i),null!==this.outputNode&&(i=this.outputNode),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(i=e,null!==s&&(i=e.merge(s))):null!==s&&(i=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=oo(t)),i=this.setupOutput(e,t)}e.stack.outputNode=i,e.addFlow("fragment",e.removeStack()),e.monitor=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=Ln(new Zc(Zc.ALPHA_TO_COVERAGE)):e.stack.add(Ln(new Zc))}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(Ln(new Zc(Zc.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?qc(Rl.z,ml,gl):Hc(Rl.z,ml,gl))}null!==i&&Xc.assign(i).append()}setupPosition(e){const{object:t}=e,s=t.geometry;var i;if(e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&wc(t).append(),!0===t.isSkinnedMesh&&(i=t,Ln(new yc(i,!0))).append(),this.displacementMap){const e=au("displacementMap","texture"),t=au("displacementScale","float"),s=au("displacementBias","float");Nl.addAssign(Ul.normalize().mul(e.x.mul(t).add(s)))}t.isBatchedMesh&&gc(t).append(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&pc(t).append(),null!==this.positionNode&&Nl.assign(this.positionNode),this.setupHardwareClipping(e);const r=oc();return e.context.vertex=e.removeStack(),e.context.mvp=r,r}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?oo(this.colorNode):wu;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=oo(s.xyz.mul(nl("color","vec3")),s.a)),e.instanceColor){s=So("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=So("vec3","vBatchColor").mul(s)}wo.assign(s);const i=this.opacityNode?Yn(this.opacityNode):Au;if(wo.a.assign(wo.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Yn(this.alphaTestNode):Su;wo.a.lessThanEqual(e).discard()}!0===this.alphaHash&&wo.a.lessThan(ed(Nl)).discard(),!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&wo.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?so(0):wo.rgb}setupNormal(){return this.normalNode?so(this.normalNode):Uu}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?au("envMap","cubeTexture"):au("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Cc(sc)),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:ic;t.push(new Nc(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);o=Ec(n,t,s,i)}else null!==s&&(o=so(null!==i?bh(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Mo.assign(so(r||Nu)),o=o.add(Mo)),o}setupOutput(e,t){if(!0===this.fog){const s=e.fogNode;s&&(t=oo(s.mix(t.rgb,s.colorNode),t.a))}return 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=js.prototype.toJSON.call(this,e),i=Dr(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 sd=new Xi;class id extends td{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(sd),this.setValues(e)}}const rd=new hr;class nd extends td{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.setDefaultValues(rd),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Yn(this.offsetNodeNode):ec,t=this.dashScaleNode?Yn(this.dashScaleNode):Zu,s=this.dashSizeNode?Yn(this.dashSizeNode):Qu,i=this.dashSizeNode?Yn(this.dashGapNode):Ju;jo.assign(s),Ho.assign(i);const r=Ph(nl("lineDistance").mul(t));(e?r.add(e):r).mod(jo.add(Ho)).greaterThan(jo).discard()}}const od=new nr;class ad extends td{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(od),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Yn(this.opacityNode):Au;wo.assign(oo(Ln(kl).mul(.5).add(.5),e))}}class hd extends tn{static get type(){return"EquirectUVNode"}constructor(e=Cl){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Qn(t,s)}}const ld=Gn(hd);class ud extends Ii{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 Si(5,5,5),n=ld(Cl),o=new td;o.colorNode=dl(t,n,0),o.side=1,o.blending=0;const a=new vi(r,o),h=new Ui;h.add(a),t.minFilter===F&&(t.minFilter=P);const l=new Bi(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 cd=new WeakMap;class dd extends tn{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Kl();const t=new Fi;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=jr}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===S||s===w){if(cd.has(e)){const t=cd.get(e);md(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new ud(s.height);i.fromEquirectangularTexture(t,e),md(i.texture,e.mapping),this._cubeTexture=i.texture,cd.set(e,i.texture),e.addEventListener("dispose",pd)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function pd(e){const t=e.target;t.removeEventListener("dispose",pd);const s=cd.get(t);void 0!==s&&(cd.delete(t),s.dispose())}function md(e,t){t===S?e.mapping=v:t===w&&(e.mapping=T)}const gd=Gn(dd);class fd extends Mc{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=gd(this.envNode)}}class yd extends Mc{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Yn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class bd{start(){}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class xd extends bd{constructor(){super()}indirect(e,t,s){const i=e.ambientOcclusion,r=e.reflectedLight,n=s.context.irradianceLightMap;r.indirectDiffuse.assign(oo(0)),n?r.indirectDiffuse.addAssign(n):r.indirectDiffuse.addAssign(oo(1,1,1,0)),r.indirectDiffuse.mulAssign(i),r.indirectDiffuse.mulAssign(wo.rgb)}finish(e,t,s){const i=s.material,r=e.outgoingLight,n=s.context.environment;if(n)switch(i.combine){case 0:r.rgb.assign(bh(r.rgb,r.rgb.mul(n.rgb),Pu.mul(Bu)));break;case 1:r.rgb.assign(bh(r.rgb,n.rgb,Pu.mul(Bu)));break;case 2:r.rgb.addAssign(n.rgb.mul(Pu.mul(Bu)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",i.combine)}}}const _d=new Hs;class vd extends td{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(_d),this.setValues(e)}setupNormal(){return Ol}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new fd(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new yd(sc)),t}setupOutgoingLight(){return wo.rgb}setupLightingModel(){return new xd}}const Td=jn((({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))})),Sd=jn((e=>e.diffuseColor.mul(1/Math.PI))),wd=jn((({dotNH:e})=>Go.mul(Yn(.5)).add(1).mul(Yn(1/Math.PI)).mul(e.pow(Go)))),Md=jn((({lightDirection:e})=>{const t=e.add(Pl).normalize(),s=kl.dot(t).clamp(),i=Pl.dot(t).clamp(),r=Td({f0:ko,f90:1,dotVH:i}),n=Yn(.25),o=wd({dotNH:s});return r.mul(n).mul(o)}));class Nd extends xd{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=kl.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(Sd({diffuseColor:wo.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Md({lightDirection:e})).mul(Pu))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(Sd({diffuseColor:wo}))),s.indirectDiffuse.mulAssign(e)}}const Ad=new or;class Ed extends td{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ad),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new fd(t):null}setupLightingModel(){return new Nd(!1)}}const Cd=new ir;class Rd extends td{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Cd),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new fd(t):null}setupLightingModel(){return new Nd}setupVariants(){const e=(this.shininessNode?Yn(this.shininessNode):Mu).max(1e-4);Go.assign(e);const t=this.specularNode||Eu;ko.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Pd=jn((e=>{if(!1===e.geometry.hasAttribute("normal"))return Yn(0);const t=Ol.dFdx().abs().max(Ol.dFdy().abs());return t.x.max(t.y).max(t.z)})),Bd=jn((e=>{const{roughness:t}=e,s=Pd();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),Fd=jn((({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 ia(.5,r.add(n).max(Ta))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Id=jn((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(so(e.mul(s),t.mul(i),o).length()),l=o.mul(so(e.mul(r),t.mul(n),a).length());return ia(.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"}]}),Ud=jn((({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"}]}),Dd=Yn(1/Math.PI),Od=jn((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=so(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return Dd.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"}]}),Ld=jn((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||kl,l=r.pow2(),u=t.add(Pl).normalize(),c=h.dot(t).clamp(),d=h.dot(Pl).clamp(),p=h.dot(u).clamp(),m=Pl.dot(u).clamp();let g,f,y=Td({f0:s,f90:i,dotVH:m});if(Dn(o)&&(y=Bo.mix(y,n)),Dn(a)){const e=Oo.dot(t),s=Oo.dot(Pl),i=Oo.dot(u),r=Lo.dot(t),n=Lo.dot(Pl),o=Lo.dot(u);g=Id({alphaT:Uo,alphaB:l,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=Od({alphaT:Uo,alphaB:l,dotNH:p,dotTH:i,dotBH:o})}else g=Fd({alpha:l,dotNL:c,dotNV:d}),f=Ud({alpha:l,dotNH:p});return y.mul(g).mul(f)})),kd=jn((({roughness:e,dotNV:t})=>{const s=oo(-1,-.0275,-.572,.022),i=oo(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 Qn(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),zd=jn((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=kd({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),Gd=jn((({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(so(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"}]}),Vd=jn((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Yn(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Yn(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"}]}),jd=jn((({dotNV:e,dotNL:t})=>Yn(1).div(Yn(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Hd=jn((({lightDirection:e})=>{const t=e.add(Pl).normalize(),s=kl.dot(e).clamp(),i=kl.dot(Pl).clamp(),r=kl.dot(t).clamp(),n=Vd({roughness:Po,dotNH:r}),o=jd({dotNV:i,dotNL:s});return Ro.mul(n).mul(o)})),Wd=jn((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Qn(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"}]}),$d=jn((({f:e})=>{const t=e.length();return nh(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),qd=jn((({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,nh(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"}]}),Yd=jn((({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=so().toVar();return $n(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(co(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=so(0).toVar();f.addAssign(qd({v1:d,v2:p})),f.addAssign(qd({v1:p,v2:m})),f.addAssign(qd({v1:m,v2:g})),f.addAssign(qd({v1:g,v2:d})),c.assign(so($d({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"}]}),Xd=1/6,Kd=e=>sa(Xd,sa(e,sa(e,e.negate().add(3)).sub(3)).add(1)),Zd=e=>sa(Xd,sa(e,sa(e,sa(3,e).sub(6))).add(4)),Qd=e=>sa(Xd,sa(e,sa(e,sa(-3,e).add(3)).add(3)).add(1)),Jd=e=>sa(Xd,ph(e,3)),ep=e=>Kd(e).add(Zd(e)),tp=e=>Qd(e).add(Jd(e)),sp=e=>ea(-1,Zd(e).div(Kd(e).add(Zd(e)))),ip=e=>ea(1,Jd(e).div(Qd(e).add(Jd(e)))),rp=(e,t,s)=>{const i=e.uvNode,r=sa(i,t.zw).add(.5),n=Ua(r),o=La(r),a=ep(o.x),h=tp(o.x),l=sp(o.x),u=ip(o.x),c=sp(o.y),d=ip(o.y),p=Qn(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),m=Qn(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),g=Qn(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),f=Qn(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=ep(o.y).mul(ea(a.mul(e.uv(p).level(s)),h.mul(e.uv(m).level(s)))),b=tp(o.y).mul(ea(a.mul(e.uv(g).level(s)),h.mul(e.uv(f).level(s))));return y.add(b)},np=jn((([e,t=Yn(3)])=>{const s=Qn(e.size(Xn(t))),i=Qn(e.size(Xn(t.add(1)))),r=ia(1,s),n=ia(1,i),o=rp(e,oo(r,s),Ua(t)),a=rp(e,oo(n,i),Da(t));return La(t).mix(o,a)})),op=jn((([e,t,s,i,r])=>{const n=so(_h(t.negate(),Oa(e),ia(1,i))),o=so(qa(r[0].xyz),qa(r[1].xyz),qa(r[2].xyz));return Oa(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"}]}),ap=jn((([e,t])=>e.mul(xh(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),hp=kc(),lp=kc(),up=jn((([e,t,s],{material:i})=>{const r=(1==i.side?hp:lp).uv(e),n=Ba(Ic.x).mul(ap(t,s));return np(r,n)})),cp=jn((([e,t,s])=>($n(s.notEqual(0),(()=>{const i=Pa(t).negate().div(s);return Ca(i.negate().mul(e))})),so(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),dp=jn((([e,t,s,i,r,n,o,a,h,l,u,c,d,p,m])=>{let g,f;if(m){g=oo().toVar(),f=so().toVar();const r=u.sub(1).mul(m.mul(.025)),n=so(u.sub(r),u,u.add(r));xc({start:0,end:3},(({i:r})=>{const u=n.element(r),m=op(e,t,c,u,a),y=o.add(m),b=l.mul(h.mul(oo(y,1))),x=Qn(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Qn(x.x,x.y.oneMinus()));const _=up(x,s,u);g.element(r).assign(_.element(r)),g.a.addAssign(_.a),f.element(r).assign(i.element(r).mul(cp(qa(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=op(e,t,c,u,a),n=o.add(r),m=l.mul(h.mul(oo(n,1))),y=Qn(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Qn(y.x,y.y.oneMinus())),g=up(y,s,u),f=i.mul(cp(qa(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),x=so(zd({dotNV:b,specularColor:r,specularF90:n,roughness:s})),_=f.r.add(f.g,f.b).div(3);return oo(x.oneMinus().mul(y),g.a.oneMinus().mul(_).oneMinus())})),pp=co(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),mp=(e,t)=>e.sub(t).div(e.add(t)).pow2(),gp=jn((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=bh(e,t,vh(0,.03,i)),o=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();$n(o.lessThan(0),(()=>so(1)));const a=o.sqrt(),h=mp(n,e),l=Td({f0:h,f90:1,dotVH:s}),u=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Yn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return so(1).add(t).div(so(1).sub(t))})(r.clamp(0,.9999)),m=mp(p,n.toVec3()),g=Td({f0:m,f90:1,dotVH:a}),f=so(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=so(d).add(f),x=l.mul(g).clamp(1e-5,.9999),_=x.sqrt(),v=u.pow2().mul(g).div(so(1).sub(x)),T=l.add(v).toVar(),S=v.sub(u).toVar();return xc({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{S.mulAssign(_);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=so(54856e-17,44201e-17,52481e-17),r=so(1681e3,1795300,2208400),n=so(43278e5,93046e5,66121e5),o=Yn(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=so(a.x.add(o),a.y,a.z).div(1.0685e-7),pp.mul(a)})(Yn(e).mul(y),Yn(e).mul(b)).mul(2);T.addAssign(S.mul(t))})),T.max(so(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"}]}),fp=jn((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Mh(s.lessThan(.25),Yn(-339.2).mul(r).add(Yn(161.4).mul(s)).sub(25.9),Yn(-8.48).mul(r).add(Yn(14.3).mul(s)).sub(9.95)),o=Mh(s.lessThan(.25),Yn(44).mul(r).sub(Yn(23.7).mul(s)).add(3.26),Yn(1.97).mul(r).sub(Yn(3.27).mul(s)).add(.72));return Mh(s.lessThan(.25),0,Yn(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),yp=so(.04),bp=Yn(1);class xp extends bd{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=so().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=so().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=so().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=so().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=so().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=kl.dot(Pl).clamp();this.iridescenceFresnel=gp({outsideIOR:Yn(1),eta2:Fo,cosTheta1:e,thinFilmThickness:Io,baseF0:ko}),this.iridescenceF0=Gd({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=El,s=bl.sub(El).normalize(),i=zl;e.backdrop=dp(i,s,No,wo,ko,zo,t,Tl,yl,fl,Wo,qo,Xo,Yo,this.dispersion?Ko:null),e.backdropAlpha=$o,wo.a.mulAssign(bh(1,e.backdrop.a,$o))}}computeMultiscattering(e,t,s){const i=kl.dot(Pl).clamp(),r=kd({roughness:No,dotNV:i}),n=(this.iridescenceF0?Bo.mix(ko,this.iridescenceF0):ko).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=ko.add(ko.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=kl.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(Hd({lightDirection:e}))),!0===this.clearcoat){const s=Gl.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(Ld({lightDirection:e,f0:yp,f90:bp,roughness:Co,normalView:Gl})))}s.directDiffuse.addAssign(i.mul(Sd({diffuseColor:wo.rgb}))),s.directSpecular.addAssign(i.mul(Ld({lightDirection:e,f0:ko,f90:1,roughness:No,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=kl,d=Pl,p=Rl.toVar(),m=Wd({N:c,V:d,roughness:No}),g=n.uv(m).toVar(),f=o.uv(m).toVar(),y=co(so(g.x,0,g.y),so(0,1,0),so(g.z,0,g.w)).toVar(),b=ko.mul(f.x).add(ko.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(b).mul(Yd({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:l,p3:u}))),r.directDiffuse.addAssign(e.mul(wo).mul(Yd({N:c,V:d,P:p,mInv:co(1,0,0,0,1,0,0,0,1),p0:a,p1:h,p2:l,p3:u})))}indirect(e,t,s){this.indirectDiffuse(e,t,s),this.indirectSpecular(e,t,s),this.ambientOcclusion(e,t,s)}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Sd({diffuseColor:wo})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(Ro,fp({normal:kl,viewDir:Pl,roughness:Po}))),!0===this.clearcoat){const e=Gl.dot(Pl).clamp(),t=zd({dotNV:e,specularColor:yp,specularF90:bp,roughness:Co});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=so().toVar("singleScattering"),r=so().toVar("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(i,r,zo);const o=i.add(r),a=wo.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(i)),s.indirectSpecular.addAssign(r.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=kl.dot(Pl).clamp().add(e),i=No.mul(-16).oneMinus().negate().exp2(),r=e.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Gl.dot(Pl).clamp(),s=Td({dotVH:e,f0:yp,f90:bp}),i=t.mul(Eo.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Eo));t.assign(i)}if(!0===this.sheen){const e=Ro.r.max(Ro.g).max(Ro.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const _p=Yn(1),vp=Yn(-2),Tp=Yn(.8),Sp=Yn(-1),wp=Yn(.4),Mp=Yn(2),Np=Yn(.305),Ap=Yn(3),Ep=Yn(.21),Cp=Yn(4),Rp=Yn(4),Pp=Yn(16),Bp=jn((([e])=>{const t=so(Wa(e)).toVar(),s=Yn(-1).toVar();return $n(t.x.greaterThan(t.z),(()=>{$n(t.x.greaterThan(t.y),(()=>{s.assign(Mh(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Mh(e.y.greaterThan(0),1,4))}))})).Else((()=>{$n(t.z.greaterThan(t.y),(()=>{s.assign(Mh(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Mh(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Fp=jn((([e,t])=>{const s=Qn().toVar();return $n(t.equal(0),(()=>{s.assign(Qn(e.z,e.y).div(Wa(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(Qn(e.x.negate(),e.z.negate()).div(Wa(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(Qn(e.x.negate(),e.y).div(Wa(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(Qn(e.z.negate(),e.y).div(Wa(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(Qn(e.x.negate(),e.z).div(Wa(e.y)))})).Else((()=>{s.assign(Qn(e.x,e.y).div(Wa(e.z)))})),sa(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Ip=jn((([e])=>{const t=Yn(0).toVar();return $n(e.greaterThanEqual(Tp),(()=>{t.assign(_p.sub(e).mul(Sp.sub(vp)).div(_p.sub(Tp)).add(vp))})).ElseIf(e.greaterThanEqual(wp),(()=>{t.assign(Tp.sub(e).mul(Mp.sub(Sp)).div(Tp.sub(wp)).add(Sp))})).ElseIf(e.greaterThanEqual(Np),(()=>{t.assign(wp.sub(e).mul(Ap.sub(Mp)).div(wp.sub(Np)).add(Mp))})).ElseIf(e.greaterThanEqual(Ep),(()=>{t.assign(Np.sub(e).mul(Cp.sub(Ap)).div(Np.sub(Ep)).add(Ap))})).Else((()=>{t.assign(Yn(-2).mul(Ba(sa(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Up=jn((([e,t])=>{const s=e.toVar();s.assign(sa(2,s).sub(1));const i=so(s,1).toVar();return $n(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"}]}),Dp=jn((([e,t,s,i,r,n])=>{const o=Yn(s),a=so(t),h=xh(Ip(o),vp,n),l=La(h),u=Ua(h),c=so(Op(e,a,u,i,r,n)).toVar();return $n(l.notEqual(0),(()=>{const t=so(Op(e,a,u.add(1),i,r,n)).toVar();c.assign(bh(c,t,l))})),c})),Op=jn((([e,t,s,i,r,n])=>{const o=Yn(s).toVar(),a=so(t),h=Yn(Bp(a)).toVar(),l=Yn(nh(Rp.sub(o),0)).toVar();o.assign(nh(o,Rp));const u=Yn(Ra(o)).toVar(),c=Qn(Fp(a,h).mul(u.sub(2)).add(1)).toVar();return $n(h.greaterThan(2),(()=>{c.y.addAssign(u),h.subAssign(3)})),c.x.addAssign(h.mul(u)),c.x.addAssign(l.mul(sa(3,Pp))),c.y.addAssign(sa(4,Ra(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.uv(c).grad(Qn(),Qn())})),Lp=jn((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=za(i),l=s.mul(h).add(r.cross(s).mul(ka(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return Op(e,l,t,n,o,a)})),kp=jn((({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=so(Mh(t,s,dh(s,i))).toVar();$n(wa(d.equals(so(0))),(()=>{d.assign(so(i.z,0,i.x.negate()))})),d.assign(Oa(d));const p=so().toVar();return p.addAssign(r.element(Xn(0)).mul(Lp({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),xc({start:Xn(1),end:e},(({i:e})=>{$n(e.greaterThanEqual(n),(()=>{sl("break").append()}));const t=Yn(o.mul(Yn(e))).toVar();p.addAssign(r.element(e).mul(Lp({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(Lp({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))})),oo(p,1)}));let zp=null;const Gp=new WeakMap;function Vp(e){let t=Gp.get(e);if((void 0!==t?t.pmremVersion:-1)!==e.pmremVersion){const s=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}(s))return null;t=zp.fromCubemap(e,t)}else{if(!function(e){return null!=e&&e.height>0}(s))return null;t=zp.fromEquirectangular(e,t)}t.pmremVersion=e.pmremVersion,Gp.set(e,t)}return t.texture}class jp extends tn{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 dt;i.isRenderTargetTexture=!0,this._texture=dl(i),this._width=vo(0),this._height=vo(0),this._maxMip=vo(0),this.updateBeforeType=jr}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(){let e=this._pmrem;const t=e?e.pmremVersion:-1,s=this._value;t!==s.pmremVersion&&(e=!0===s.isPMREMTexture?s:Vp(s),null!==e&&(this._pmrem=e,this.updateFromTexture(e)))}setup(e){null===zp&&(zp=e.createPMREMGenerator()),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this));const s=this.value;e.renderer.coordinateSystem===Ue&&!0!==s.isPMREMTexture&&!0===s.isRenderTargetTexture&&(t=so(t.x.negate(),t.yz));let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),Dp(this._texture,t,i,this._width,this._height,this._maxMip)}}const Hp=Gn(jp),Wp=new WeakMap;class $p extends Mc{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=Wp.get(e);void 0===i&&(i=Hp(e),Wp.set(e,i)),s=i}const i=t.envMap?ru("envMapIntensity","float",e.material):ru("environmentIntensity","float",e.scene),r=!0===t.useAnisotropy||t.anisotropy>0?pu:kl,n=s.context(qp(No,r)).mul(i),o=s.context(Yp(zl)).mul(Math.PI).mul(i),a=Kh(n),h=Kh(o);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(h);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=s.context(qp(Co,Gl)).mul(i),t=Kh(e);l.addAssign(t)}}}const qp=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=Pl.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(yl)),s),getTextureLevel:()=>e}},Yp=e=>({getUV:()=>e,getTextureLevel:()=>Yn(1)}),Xp=new tr;class Kp extends td{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(Xp),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new $p(t):null}setupLightingModel(){return new xp}setupSpecular(){const e=bh(so(.04),wo.rgb,Ao);ko.assign(e),zo.assign(1)}setupVariants(){const e=this.metalnessNode?Yn(this.metalnessNode):Iu;Ao.assign(e);let t=this.roughnessNode?Yn(this.roughnessNode):Fu;t=Bd({roughness:t}),No.assign(t),this.setupSpecular(),wo.assign(oo(wo.rgb.mul(e.oneMinus()),wo.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Zp=new sr;class Qp extends Kp{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(Zp),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?Yn(this.iorNode):Yu;Wo.assign(e),ko.assign(bh(rh(mh(Wo.sub(1).div(Wo.add(1))).mul(Ru),so(1)).mul(Cu),wo.rgb,Ao)),zo.assign(bh(Cu,1,Ao))}setupLightingModel(){return new xp(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Yn(this.clearcoatNode):Du,t=this.clearcoatRoughnessNode?Yn(this.clearcoatRoughnessNode):Ou;Eo.assign(e),Co.assign(Bd({roughness:t}))}if(this.useSheen){const e=this.sheenNode?so(this.sheenNode):zu,t=this.sheenRoughnessNode?Yn(this.sheenRoughnessNode):Gu;Ro.assign(e),Po.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Yn(this.iridescenceNode):ju,t=this.iridescenceIORNode?Yn(this.iridescenceIORNode):Hu,s=this.iridescenceThicknessNode?Yn(this.iridescenceThicknessNode):Wu;Bo.assign(e),Fo.assign(t),Io.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Qn(this.anisotropyNode):Vu).toVar();Do.assign(e.length()),$n(Do.equal(0),(()=>{e.assign(Qn(1,0))})).Else((()=>{e.divAssign(Qn(Do)),Do.assign(Do.saturate())})),Uo.assign(Do.pow2().mix(No.pow2(),1)),Oo.assign(du[0].mul(e.x).add(du[1].mul(e.y))),Lo.assign(du[1].mul(e.x).sub(du[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Yn(this.transmissionNode):$u,t=this.thicknessNode?Yn(this.thicknessNode):qu,s=this.attenuationDistanceNode?Yn(this.attenuationDistanceNode):Xu,i=this.attenuationColorNode?so(this.attenuationColorNode):Ku;if($o.assign(e),qo.assign(t),Yo.assign(s),Xo.assign(i),this.useDispersion){const e=this.dispersionNode?Yn(this.dispersionNode):tc;Ko.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?so(this.clearcoatNormalNode):Lu}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 Jp=jn((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Qn(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=au("gradientMap","texture").context({getUV:()=>r});return so(e.r)}{const e=r.fwidth().mul(.5);return bh(so(.7),so(1),vh(Yn(.7).sub(e.x),Yn(.7).add(e.x),r.x))}}));class em extends bd{direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){const n=Jp({normal:Il,lightDirection:e,builder:r}).mul(t);s.directDiffuse.addAssign(n.mul(Sd({diffuseColor:wo.rgb})))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(Sd({diffuseColor:wo}))),s.indirectDiffuse.mulAssign(e)}}const tm=new rr;class sm extends td{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(tm),this.setValues(e)}setupLightingModel(){return new em}}class im extends tn{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=so(Pl.z,0,Pl.x.negate()).normalize(),t=Pl.cross(e);return Qn(e.dot(kl),t.dot(kl)).mul(.495).add(.5)}}const rm=Vn(im),nm=new ar;class om extends td{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.lights=!1,this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(nm),this.setValues(e)}setupVariants(e){const t=rm;let s;s=e.material.matcap?au("matcap","texture").context({getUV:()=>t}):so(bh(.2,.8,t.y)),wo.rgb.mulAssign(s.rgb)}}const am=new Ki;class hm extends td{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(am),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}class lm extends tn{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 uo(e,i,i.negate(),e).mul(s)}{const e=t,i=po(oo(1,0,0,0),oo(0,za(e.x),ka(e.x).negate(),0),oo(0,ka(e.x),za(e.x),0),oo(0,0,0,1)),r=po(oo(za(e.y),0,ka(e.y),0),oo(0,1,0,0),oo(ka(e.y).negate(),0,za(e.y),0),oo(0,0,0,1)),n=po(oo(za(e.z),ka(e.z).negate(),0,0),oo(ka(e.z),za(e.z),0,0),oo(0,0,1,0),oo(0,0,0,1));return i.mul(r).mul(n).mul(oo(s,1)).xyz}}}const um=Gn(lm),cm=new ki;class dm extends td{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(cm),this.setValues(e)}setupPosition({object:e,camera:t,context:s}){const i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=Nl;let h=wl.mul(so(r||0)),l=Qn(Tl[0].xyz.length(),Tl[1].xyz.length());if(null!==o&&(l=l.mul(o)),!i)if(t.isPerspectiveCamera)l=l.mul(h.z.negate());else{const e=Yn(2).div(fl.element(1).element(1));l=l.mul(e.mul(2))}let u=a.xy;if(e.center&&!0===e.center.isVector2){const e=((e,t,s)=>Ln(new kh(e,t,s)))("center","vec2");u=u.sub(e.sub(.5))}u=u.mul(l);const c=Yn(n||ku),d=um(u,c);h=oo(h.xy.add(d),h.zw);const p=fl.mul(h);return s.vertex=a,p}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)}}class pm extends bd{constructor(){super(),this.shadowNode=Yn(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){wo.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(wo.rgb)}}const mm=new er;class gm extends td{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(mm),this.setValues(e)}setupLightingModel(){return new pm}}jn((({texture:e,uv:t})=>{const s=1e-4,i=so().toVar();return $n(t.x.lessThan(s),(()=>{i.assign(so(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(so(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(so(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(so(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(so(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(so(0,0,-1))})).Else((()=>{const s=.01,r=e.uv(t.add(so(-.01,0,0))).r.sub(e.uv(t.add(so(s,0,0))).r),n=e.uv(t.add(so(0,-.01,0))).r.sub(e.uv(t.add(so(0,s,0))).r),o=e.uv(t.add(so(0,0,-.01))).r.sub(e.uv(t.add(so(0,0,s))).r);i.assign(so(r,n,o))})),i.normalize()}));class fm{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}setAnimationLoop(e){this._animationLoop=e}setContext(e){this._context=e}dispose(){this.stop()}}class ym{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s<e.length;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;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)}delete(e){let t=this.weakMap;for(let s=0;s<e.length;s++)if(t=t.get(e[s]),void 0===t)return!1;return t.delete(e[e.length-1])}}let bm=0;class xm{constructor(e,t,s,i,r,n,o,a,h,l){this._nodes=e,this._geometries=t,this.id=bm++,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.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().monitor)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}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,")}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.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",Br(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=this._nodes.getCacheKey(this.scene,this.lightsNode);return this.object.receiveShadow&&(e+=1),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const _m=[];class vm{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);_m[0]=e,_m[1]=t,_m[2]=n,_m[3]=r;let l=h.get(_m);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o,a),h.set(_m,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)),l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new ym)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,l,u){const c=this.getChainMap(u),d=new xm(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 Tm{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;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 Sm=1,wm=2,Mm=3,Nm=4,Am=16;class Em extends Tm{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===Sm?this.backend.createAttribute(e):t===wm?this.backend.createIndexAttribute(e):t===Mm?this.backend.createStorageAttribute(e):t===Nm&&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 Cm(e){return null!==e.index?e.index.version:e.attributes.position.version}function Rm(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(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(t)?Js:Qs)(t,1);return r.version=Cm(e),r}class Pm extends Tm{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,Mm):this.updateAttribute(e,Sm);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,wm);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Nm)}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=Rm(t),e.set(t,s)):s.version!==Cm(t)&&(this.attributes.delete(s),s=Rm(t),e.set(t,s)),i=s}return i}}class Bm{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,previousFrameCalls:0,timestampCalls:0},this.compute={calls:0,frameCalls:0,timestamp:0,previousFrameCalls:0,timestampCalls: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.")}updateTimestamp(e,t){0===this[e].timestampCalls&&(this[e].timestamp=0),this[e].timestamp+=t,this[e].timestampCalls++,this[e].timestampCalls>=this[e].previousFrameCalls&&(this[e].timestampCalls=0)}reset(){const e=this.render.frameCalls;this.render.previousFrameCalls=e;const t=this.compute.frameCalls;this.compute.previousFrameCalls=t,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 Fm{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Im extends Fm{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Um extends Fm{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Dm=0;class Om{constructor(e,t,s=null,i=null){this.id=Dm++,this.code=e,this.stage=t,this.transforms=s,this.attributes=i,this.usedTimes=0}}class Lm extends Tm{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 Om(n.computeShader,"compute",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();let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new Om(n.vertexShader,"vertex"),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let a=this.programs.fragment.get(n.fragmentShader);void 0===a&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),a=new Om(n.fragmentShader,"fragment"),this.programs.fragment.set(n.fragmentShader,a),s.createProgram(a));const h=this._getRenderCacheKey(e,o,a);let l=this.caches.get(h);void 0===l?(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getRenderPipeline(e,o,a,h,t)):e.pipeline=l,l.usedTimes++,o.usedTimes++,a.usedTimes++,i.pipeline=l}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new Um(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 Im(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 km extends Tm{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?Nm:Mm;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(!this.nodes.updateGroup(t))continue}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 zm(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 Gm(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 Vm(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class jm{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?(Vm(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?(Vm(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||zm),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Gm),this.transparent.length>1&&this.transparent.sort(t||Gm)}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}}}class Hm{constructor(e){this.lighting=e,this.lists=new ym}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new jm(this.lighting,e,t),s.set(i,r)),r}dispose(){this.lists=new ym}}let Wm=0;class $m{constructor(){this.id=Wm++,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 pt,this.scissor=!1,this.scissorValue=new pt,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.sampleCount=1,this.width=0,this.height=0,this.isRenderContext=!0}getCacheKey(){return qm(this)}}function qm(e){const{textures:t,activeCubeFace:s}=e,i=[s];for(const e of t)i.push(e.id);return Fr(i)}class Ym{constructor(){this.chainMaps={}}get(e,t,s=null){const i=[e,t];let r;if(null===s)r="default";else{const e=s.texture.format;r=`${s.textures.length}:${e}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this.getChainMap(r);let o=n.get(i);return void 0===o&&(o=new $m,n.set(i,o)),null!==s&&(o.sampleCount=0===s.samples?1:s.samples),o}getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new ym)}dispose(){this.chainMaps={}}}const Xm=new bt;class Km extends Tm{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 Qi,l.format=e.stencilBuffer?$:W,l.type=e.stencilBuffer?V:k,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};for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,d)}if(l&&this.updateTexture(l,d),!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=Xm){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===S||t===w||t===v||t===T}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class Zm extends zs{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Qm extends To{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class Jm extends Qr{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"}add(e){return this.nodes.push(e),this}If(e,t){const s=new On(t);return this._currentCond=Mh(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new On(t),i=Mh(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new On(e),this}build(e,...t){const s=Wn();Hn(this);for(const t of this.nodes)t.build(e,"void");return Hn(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const eg=Gn(Jm);new Wi,new bt,new bt,new bt,new Yt,new bt(0,0,-1),new pt,new bt,new bt,new pt,new Xe;const tg=new mt;Fc.flipX(),tg.depthTexture=new Qi(1,1);const sg=new Tr(-1,1,1,-1,0,1);class ig extends li{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new ti([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ti(t,2))}}const rg=new ig;class ng extends vi{constructor(e=null){super(rg,e),this.camera=sg,this.isQuadMesh=!0}renderAsync(e){return e.renderAsync(this,sg)}render(e){e.render(this,sg)}}const og=new rs,ag=new Yt;class hg extends Qr{static get type(){return"SceneNode"}constructor(e=hg.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===hg.BACKGROUND_BLURRINESS?i=ru("backgroundBlurriness","float",s):t===hg.BACKGROUND_INTENSITY?i=ru("backgroundIntensity","float",s):t===hg.BACKGROUND_ROTATION?i=vo("mat4").label("backgroundRotation").setGroup(bo).onRenderUpdate((()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(og.copy(s.backgroundRotation),og.x*=-1,og.y*=-1,og.z*=-1,ag.makeRotationFromEuler(og)):ag.identity(),ag})):console.error("THREE.SceneNode: Unknown scope:",t),i}}hg.BACKGROUND_BLURRINESS="backgroundBlurriness",hg.BACKGROUND_INTENSITY="backgroundIntensity",hg.BACKGROUND_ROTATION="backgroundRotation";const lg=Vn(hg,hg.BACKGROUND_BLURRINESS),ug=Vn(hg,hg.BACKGROUND_INTENSITY),cg=Vn(hg,hg.BACKGROUND_ROTATION),dg=new Xe;class pg extends cl{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 mg extends pg{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 gg extends tn{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 Qi;r.isRenderTargetTexture=!0,r.name="depth";const n=new mt(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:G,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.updateBeforeType=Vr,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=vo(0),this._cameraFar=vo(0),this._mrt=null,this.isPassNode=!0}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.isRenderTargetTexture=!0,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(),t.isRenderTargetTexture=!0,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=Ln(new mg(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=Ln(new mg(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=$c(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=Hc(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.depthTexture.isMultisampleRenderTargetTexture=this.renderTarget.samples>1,this.scope===gg.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(dg);this.setSize(r.width,r.height);const n=t.getRenderTarget(),o=t.getMRT();this._cameraNear.value=i.near,this._cameraFar.value=i.far;for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(n),t.setMRT(o)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}gg.COLOR="color",gg.DEPTH="depth";const fg=jn((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),yg=jn((([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"}]}),bg=jn((([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"}]}),xg=jn((([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)})),_g=jn((([e,t])=>{const s=co(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=co(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=xg(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),vg=co(so(1.6605,-.1246,-.0182),so(-.5876,1.1329,-.1006),so(-.0728,-.0083,1.1187)),Tg=co(so(.6274,.0691,.0164),so(.3293,.9195,.088),so(.0433,.0113,.8956)),Sg=jn((([e])=>{const t=so(e).toVar(),s=so(t.mul(t)).toVar(),i=so(s.mul(s)).toVar();return Yn(15.5).mul(i.mul(s)).sub(sa(40.14,i.mul(t))).add(sa(31.96,i).sub(sa(6.868,s.mul(t))).add(sa(.4298,s).add(sa(.1191,t).sub(.00232))))})),wg=jn((([e,t])=>{const s=so(e).toVar(),i=co(so(.856627153315983,.137318972929847,.11189821299995),so(.0951212405381588,.761241990602591,.0767994186031903),so(.0482516061458583,.101439036467562,.811302368396859)),r=co(so(1.1271005818144368,-.1413297634984383,-.14132976349843826),so(-.11060664309660323,1.157823702216272,-.11060664309660294),so(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Yn(-12.47393),o=Yn(4.026069);return s.mulAssign(t),s.assign(Tg.mul(s)),s.assign(i.mul(s)),s.assign(nh(s,1e-10)),s.assign(Ba(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(xh(s,0,1)),s.assign(Sg(s)),s.assign(r.mul(s)),s.assign(ph(nh(so(0),s),so(2.2))),s.assign(vg.mul(s)),s.assign(xh(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Mg=jn((([e,t])=>{const s=Yn(.76),i=Yn(.15);e=e.mul(t);const r=rh(e.r,rh(e.g,e.b)),n=Mh(r.lessThan(.08),r.sub(sa(6.25,r.mul(r))),.04);e.subAssign(n);const o=nh(e.r,nh(e.g,e.b));$n(o.lessThan(s),(()=>e));const a=ta(1,s),h=ta(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const l=ta(1,ia(1,i.mul(o.sub(h)).add(1)));return bh(e,so(h),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Ng extends Qr{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}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 Ag extends Ng{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)}}class Eg extends Qr{static get type(){return"FogNode"}constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}getViewZNode(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||Rl.z).negate()}setup(){return this.factorNode}}class Cg extends Eg{static get type(){return"FogRangeNode"}constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(e){const t=this.getViewZNode(e);return vh(this.nearNode,this.farNode,t)}}const Rg=Gn(Cg);class Pg extends Eg{static get type(){return"FogExp2Node"}constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(e){const t=this.getViewZNode(e),s=this.densityNode;return s.mul(s,t,t).negate().exp().oneMinus()}}const Bg=Gn(Pg);Gn(class extends Qr{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 Fg extends tn{static get type(){return"AtomicFunctionNode"}constructor(e,t,s,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.storeNode=i}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)}`),o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${a}`,this)}else e.addLineFlowCode(a,this)}}let Ig;function Ug(e){Ig=Ig||new WeakMap;let t=Ig.get(e);return void 0===t&&Ig.set(e,t={}),t}function Dg(e){const t=Ug(e);return t.shadowMatrix||(t.shadowMatrix=vo("mat4").setGroup(bo).onRenderUpdate((()=>(e.shadow.updateMatrices(e),e.shadow.matrix))))}function Og(e){const t=Ug(e);return t.position||(t.position=vo(new bt).setGroup(bo).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function Lg(e){const t=Ug(e);return t.viewPosition||(t.viewPosition=vo(new bt).setGroup(bo).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new bt,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}Fg.ATOMIC_LOAD="atomicLoad",Fg.ATOMIC_STORE="atomicStore",Fg.ATOMIC_ADD="atomicAdd",Fg.ATOMIC_SUB="atomicSub",Fg.ATOMIC_MAX="atomicMax",Fg.ATOMIC_MIN="atomicMin",Fg.ATOMIC_AND="atomicAnd",Fg.ATOMIC_OR="atomicOr",Fg.ATOMIC_XOR="atomicXor",Gn(Fg);const kg=e=>yl.transformDirection(Og(e).sub(function(e){const t=Ug(e);return t.targetPosition||(t.targetPosition=vo(new bt).setGroup(bo).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}(e))),zg=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Gg=new WeakMap;class Vg extends Qr{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=so().toVar("totalDiffuse"),this.totalSpecularNode=so().toVar("totalSpecular"),this.outgoingLightNode=so().toVar("outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}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(Ln(e));else{let i=null;if(null!==s&&(i=zg(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;Gg.has(e)?i=Gg.get(e):(i=Ln(new s(e)),Gg.set(e,i)),t.push(i)}}this._lightNodes=t}setupLights(e,t){for(const s of t)s.build(e)}setup(e){null===this._lightNodes&&this.setupLightsNode(e);const t=e.context,s=t.lightingModel;let i=this.outgoingLightNode;if(s){const{_lightNodes:r,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=i;const a=e.addStack();e.getDataFromNode(this).nodes=a.nodes,s.start(t,a,e),this.setupLights(e,r),s.indirect(t,a,e);const{backdrop:h,backdropAlpha:l}=t,{directDiffuse:u,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=u.add(d);null!==h&&(m=so(null!==l?l.mix(m,h):h),t.material.transparent=!0),n.assign(m),o.assign(c.add(p)),i.assign(n.add(o)),s.finish(t,a,e),i=i.bypass(e.removeStack())}return i}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}const jg=new WeakMap,Hg=so().toVar("shadowWorldPosition"),Wg=jn((([e,t,s])=>{let i=El.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i})),$g=e=>{let t=jg.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=ru("near","float",t).setGroup(bo),i=ru("far","float",t).setGroup(bo),r=_l(e);return Wg(r,s,i)})(e):null;t=new td,t.colorNode=oo(0,0,0,1),t.depthNode=s,t.isShadowNodeMaterial=!0,t.blending=0,t.name="ShadowMaterial",jg.set(e,t)}return t},qg=jn((({depthTexture:e,shadowCoord:t})=>dl(e,t.xy).compare(t.z))),Yg=jn((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>dl(e,t).compare(s),r=ru("mapSize","vec2",s).setGroup(bo),n=ru("radius","float",s).setGroup(bo),o=Qn(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 ea(i(t.xy.add(Qn(a,h)),t.z),i(t.xy.add(Qn(0,h)),t.z),i(t.xy.add(Qn(l,h)),t.z),i(t.xy.add(Qn(c,d)),t.z),i(t.xy.add(Qn(0,d)),t.z),i(t.xy.add(Qn(p,d)),t.z),i(t.xy.add(Qn(a,0)),t.z),i(t.xy.add(Qn(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(Qn(p,0)),t.z),i(t.xy.add(Qn(l,0)),t.z),i(t.xy.add(Qn(c,m)),t.z),i(t.xy.add(Qn(0,m)),t.z),i(t.xy.add(Qn(p,m)),t.z),i(t.xy.add(Qn(a,u)),t.z),i(t.xy.add(Qn(0,u)),t.z),i(t.xy.add(Qn(l,u)),t.z)).mul(1/17)})),Xg=jn((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>dl(e,t).compare(s),r=ru("mapSize","vec2",s).setGroup(bo),n=Qn(1).div(r),o=n.x,a=n.y,h=t.xy,l=La(h.mul(r).add(.5));return h.subAssign(l.mul(n)),ea(i(h,t.z),i(h.add(Qn(o,0)),t.z),i(h.add(Qn(0,a)),t.z),i(h.add(n),t.z),bh(i(h.add(Qn(o.negate(),0)),t.z),i(h.add(Qn(o.mul(2),0)),t.z),l.x),bh(i(h.add(Qn(o.negate(),a)),t.z),i(h.add(Qn(o.mul(2),a)),t.z),l.x),bh(i(h.add(Qn(0,a.negate())),t.z),i(h.add(Qn(0,a.mul(2))),t.z),l.y),bh(i(h.add(Qn(o,a.negate())),t.z),i(h.add(Qn(o,a.mul(2))),t.z),l.y),bh(bh(i(h.add(Qn(o.negate(),a.negate())),t.z),i(h.add(Qn(o.mul(2),a.negate())),t.z),l.x),bh(i(h.add(Qn(o.negate(),a.mul(2))),t.z),i(h.add(Qn(o.mul(2),a.mul(2))),t.z),l.x),l.y)).mul(1/9)})),Kg=jn((({depthTexture:e,shadowCoord:t})=>{const s=Yn(1).toVar(),i=dl(e).uv(t.xy).rg,r=ah(t.z,i.x);return $n(r.notEqual(Yn(1)),(()=>{const e=t.z.sub(i.x),n=nh(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=xh(ta(o,.3).div(.95-.3)),s.assign(xh(nh(r,o)))})),s})),Zg=jn((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Yn(0).toVar(),n=Yn(0).toVar(),o=e.lessThanEqual(Yn(1)).select(Yn(0),Yn(2).div(e.sub(1))),a=e.lessThanEqual(Yn(1)).select(Yn(0),Yn(-1));xc({start:Xn(0),end:Xn(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Yn(e).mul(o)),l=i.uv(ea(Uc.xy,Qn(0,h).mul(t)).div(s)).x;r.addAssign(l),n.addAssign(l.mul(l))})),r.divAssign(e),n.divAssign(e);const h=Fa(n.sub(r.mul(r)));return Qn(r,h)})),Qg=jn((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Yn(0).toVar(),n=Yn(0).toVar(),o=e.lessThanEqual(Yn(1)).select(Yn(0),Yn(2).div(e.sub(1))),a=e.lessThanEqual(Yn(1)).select(Yn(0),Yn(-1));xc({start:Xn(0),end:Xn(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Yn(e).mul(o)),l=i.uv(ea(Uc.xy,Qn(h,0).mul(t)).div(s));r.addAssign(l.x),n.addAssign(ea(l.y.mul(l.y),l.x.mul(l.x)))})),r.divAssign(e),n.divAssign(e);const h=Fa(n.sub(r.mul(r)));return Qn(r,h)})),Jg=[qg,Yg,Xg,Kg],ef=new ng;class tf extends Qr{static get type(){return"ShadowNode"}constructor(e,t=null){super(),this.light=e,this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this.updateBeforeType=jr,this._node=null,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,Yn(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=ru("bias","float",s).setGroup(bo);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=ru("near","float",s.camera).setGroup(bo),i=ru("far","float",s.camera).setGroup(bo);n=qc(e.negate(),t,i)}return o=so(o.x,o.y.oneMinus(),n.add(r)),o}getShadowFilterFn(e){return Jg[e]}setupShadow(e){const{renderer:t}=e,{light:s,shadow:i}=this,r=t.shadowMap.type,n=new Qi(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:X,type:G}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:X,type:G});const t=dl(n),s=dl(this.vsmShadowMapVertical.texture),r=ru("blurSamples","float",i).setGroup(bo),o=ru("radius","float",i).setGroup(bo),a=ru("mapSize","vec2",i).setGroup(bo);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new td);h.fragmentNode=Zg({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new td),h.fragmentNode=Qg({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=ru("intensity","float",i).setGroup(bo),h=ru("normalBias","float",i).setGroup(bo),l=Dg(s).mul(Hg.add(zl.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=dl(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 jn((({material:t})=>{Hg.assign(t.shadowPositionNode||El);let s=this._node;return null===s&&(this._node=s=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(s=e.material.receivedShadowNode(s)),s}))()}renderShadow(e){const{shadow:t,shadowMap:s}=this,{renderer:i,scene:r}=e;s.setSize(t.mapSize.width,t.mapSize.height),i.render(r,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;const l=n.overrideMaterial;n.overrideMaterial=$g(s),i.camera.layers.mask=o.layers.mask;const u=r.getRenderTarget(),c=r.getRenderObjectFunction(),d=r.getMRT();r.setMRT(null),r.setRenderObjectFunction(((e,...t)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&r.renderObject(e,...t)})),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(c),!0!==s.isPointLight&&3===a&&this.vsmPass(r),r.setRenderTarget(u),r.setMRT(d),n.overrideMaterial=l}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),ef.material=this.vsmMaterialVertical,ef.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),ef.material=this.vsmMaterialHorizontal,ef.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),this.updateBeforeType=Gr}updateBefore(e){const{shadow:t}=this;(t.needsUpdate||t.autoUpdate)&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}class sf extends Mc{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new zs,this.colorNode=e&&e.colorNode||vo(this.color).setGroup(bo),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vr}getCacheKey(){return Ir(super.getCacheKey(),this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}setupShadowNode(){return((e,t)=>Ln(new tf(e,t)))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const t=this.light.shadow.shadowNode;let i;i=void 0!==t?Ln(t):this.setupShadowNode(e),this.shadowNode=i,this.shadowColorNode=s=this.colorNode.mul(i),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)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const rf=jn((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return s.greaterThan(0).select(r.mul(t.div(s).pow4().oneMinus().clamp().pow2()),r)})),nf=new zs,of=jn((([e,t])=>{const s=e.toVar(),i=Wa(s),r=ia(1,nh(i.x,nh(i.y,i.z)));i.mulAssign(r),s.mulAssign(r.mul(t.mul(2).oneMinus()));const n=Qn(s.xy).toVar(),o=t.mul(1.5).oneMinus();return $n(i.z.greaterThanEqual(o),(()=>{$n(s.z.greaterThan(0),(()=>{n.x.assign(ta(4,s.x))}))})).ElseIf(i.x.greaterThanEqual(o),(()=>{const e=$a(s.x);n.x.assign(s.z.mul(e).add(e.mul(2)))})).ElseIf(i.y.greaterThanEqual(o),(()=>{const e=$a(s.y);n.x.assign(s.x.add(e.mul(2)).add(2)),n.y.assign(s.z.mul(e).sub(2))})),Qn(.125,.25).mul(n).add(Qn(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),af=jn((({depthTexture:e,bd3D:t,dp:s,texelSize:i})=>dl(e,of(t,i.y)).compare(s))),hf=jn((({depthTexture:e,bd3D:t,dp:s,texelSize:i,shadow:r})=>{const n=ru("radius","float",r).setGroup(bo),o=Qn(-1,1).mul(n).mul(i.y);return dl(e,of(t.add(o.xyy),i.y)).compare(s).add(dl(e,of(t.add(o.yyy),i.y)).compare(s)).add(dl(e,of(t.add(o.xyx),i.y)).compare(s)).add(dl(e,of(t.add(o.yyx),i.y)).compare(s)).add(dl(e,of(t,i.y)).compare(s)).add(dl(e,of(t.add(o.xxy),i.y)).compare(s)).add(dl(e,of(t.add(o.yxy),i.y)).compare(s)).add(dl(e,of(t.add(o.xxx),i.y)).compare(s)).add(dl(e,of(t.add(o.yxx),i.y)).compare(s)).mul(1/9)})),lf=jn((({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),o=vo("float").setGroup(bo).onRenderUpdate((()=>i.camera.near)),a=vo("float").setGroup(bo).onRenderUpdate((()=>i.camera.far)),h=ru("bias","float",i).setGroup(bo),l=vo(i.mapSize).setGroup(bo),u=Yn(1).toVar();return $n(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=Qn(1).div(l.mul(Qn(4,2)));u.assign(e({depthTexture:t,bd3D:c,dp:s,texelSize:d,shadow:i}))})),u})),uf=new pt,cf=new Xe,df=new Xe;class pf extends tf{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?af:hf}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:r,shadow:n}){return lf({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();df.copy(t.mapSize),df.multiply(o),s.setSize(df.width,df.height),cf.copy(t.mapSize);const a=r.autoClear,h=r.getClearColor(nf),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=cf.x*o.x,h=df.y-cf.y-cf.y*o.y;uf.set(a,h,cf.x*o.z,cf.y*o.w),s.viewport.copy(uf),t.updateMatrices(i,e),r.render(n,t.camera)}r.autoClear=a,r.setClearColor(h,l)}}const mf=jn((({color:e,lightViewPosition:t,cutoffDistance:s,decayExponent:i},r)=>{const n=r.context.lightingModel,o=t.sub(Rl),a=o.normalize(),h=o.length(),l=rf({lightDistance:h,cutoffDistance:s,decayExponent:i}),u=e.mul(l),c=r.context.reflectedLight;n.direct({lightDirection:a,lightColor:u,reflectedLight:c},r.stack,r)}));class gf extends sf{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=vo(0).setGroup(bo),this.decayExponentNode=vo(0).setGroup(bo)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>Ln(new pf(e,t)))(this.light)}setup(e){super.setup(e),mf({color:this.colorNode,lightViewPosition:Lg(this.light),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode}).append()}}const ff=jn((([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(sa(s,s).sub(sa(i,i)))),n})),yf=new Zm;class bf extends Tm{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(yf,ve),yf.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(yf,ve),yf.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;yf.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Ah(oo(n).mul(ug),{getUV:()=>cg.mul(Ll),getTextureLevel:()=>lg});let t=oc();t=t.setZ(t.w);const i=new td;i.name="Background.material",i.side=1,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new vi(new Ji(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=oo(n).mul(ug),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);if(!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=yf.r,e.g=yf.g,e.b=yf.b,e.a=yf.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 xf=0;class _f{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=xf++}}class vf{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.monitor=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new _f(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 Tf{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class Sf{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 wf{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class Mf extends wf{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class Nf{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let Af=0;class Ef{constructor(e=null){this.id=Af++,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 Cf{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 Rf extends Cf{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class Pf extends Cf{constructor(e,t=new Xe){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Bf extends Cf{constructor(e,t=new bt){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Ff extends Cf{constructor(e,t=new pt){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class If extends Cf{constructor(e,t=new zs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Uf extends Cf{constructor(e,t=new Ke){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Df extends Cf{constructor(e,t=new Yt){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Of extends Rf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Lf extends Pf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kf extends Bf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zf extends Ff{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Gf extends If{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Vf extends Uf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class jf extends Df{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Hf=[.125,.215,.35,.446,.526,.582],Wf=20,$f=new Tr(-1,1,1,-1,0,1),qf=new Ri(90,1),Yf=new zs;let Xf=null,Kf=0,Zf=0;const Qf=(1+Math.sqrt(5))/2,Jf=1/Qf,ey=[new bt(-Qf,Jf,0),new bt(Qf,Jf,0),new bt(-Jf,0,Qf),new bt(Jf,0,Qf),new bt(0,Qf,-Jf),new bt(0,Qf,Jf),new bt(-1,1,-1),new bt(1,1,-1),new bt(-1,1,1),new bt(1,1,1)],ty=[3,1,5,0,4,2],sy=Up(ol(),nl("faceIndex")).normalize(),iy=so(sy.x,sy.y.negate(),sy.z);class ry{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=null){if(this._setSize(256),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=r||this._allocateTargets();return this.fromSceneAsync(e,t,s,i,n),n}Xf=this._renderer.getRenderTarget(),Kf=this._renderer.getActiveCubeFace(),Zf=this._renderer.getActiveMipmapLevel();const n=r||this._allocateTargets();return n.depthBuffer=!0,this._sceneToCubeUV(e,s,i,n),t>0&&this._blur(n,0,0,t),this._applyPMREM(n),this._cleanup(n),n}async fromSceneAsync(e,t=0,s=.1,i=100,r=null){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=hy(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=ly(),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(Xf,Kf,Zf),e.scissorTest=!1,oy(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Xf=this._renderer.getRenderTarget(),Kf=this._renderer.getActiveCubeFace(),Zf=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:G,format:H,colorSpace:ve},i=ny(e,t,s);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=ny(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+Hf.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=Hf[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=ty[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 li;v.setAttribute("position",new Zs(b,g)),v.setAttribute("uv",new Zs(x,f)),v.setAttribute("faceIndex",new Zs(_,y)),t.push(v),r.push(new vi(v,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=tu(new Array(Wf).fill(0)),r=vo(new bt(0,1,0)),n=vo(0),o=Yn(Wf),a=vo(0),h=vo(1),l=dl(null),u=vo(0),c=Yn(1/t),d=Yn(1/s),p=Yn(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:iy,dTheta:n,samples:h,envMap:l,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=ay("blur");return g.uniforms=m,g.fragmentNode=kp({...m,latitudinal:a.equal(1)}),g}(i,e,t)}return i}async _compileMaterial(e){const t=new vi(this._lodPlanes[0],e);await this._renderer.compile(t,$f)}_sceneToCubeUV(e,t,s,i){const r=qf;r.near=t,r.far=s;const n=[-1,1,-1,-1,-1,-1],o=[1,1,1,-1,-1,-1],a=this._renderer,h=a.autoClear;a.getClearColor(Yf),a.autoClear=!1;let l=this._backgroundBox;if(null===l){const e=new Hs({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});l=new vi(new Si,e)}let u=!1;const c=e.background;c?c.isColor&&(l.material.color.copy(c),e.background=null,u=!0):(l.material.color.copy(Yf),u=!0),a.setRenderTarget(i),a.clear(),u&&a.render(l,r);for(let t=0;t<6;t++){const s=t%3;0===s?(r.up.set(0,n[t],0),r.lookAt(o[t],0,0)):1===s?(r.up.set(0,0,n[t]),r.lookAt(0,o[t],0)):(r.up.set(0,n[t],0),r.lookAt(0,0,o[t]));const h=this._cubeSize;oy(i,s*h,t>2?h:0,h,h),a.render(e,r)}a.autoClear=h,e.background=c}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===v||e.mapping===T;i?null===this._cubemapMaterial&&(this._cubemapMaterial=hy(e)):null===this._equirectMaterial&&(this._equirectMaterial=ly(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;oy(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,$f)}_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=ey[(i-t-1)%ey.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=h.uniforms,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):Wf;m>Wf&&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<Wf;++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];oy(t,3*b*(i>y-4?i-y+4:0),4*(this._cubeSize-b),3*b,2*b),a.setRenderTarget(t),a.render(l,$f)}}function ny(e,t,s){const i=new mt(e,t,s);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function oy(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function ay(e){const t=new td;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function hy(e){const t=ay("cubemap");return t.fragmentNode=Kl(e,iy),t}function ly(e){const t=ay("equirect");return t.fragmentNode=dl(e,ld(iy),0),t}const uy=new WeakMap,cy=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),dy=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class py{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.monitor=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.flow={code:""},this.chaining=[],this.stack=eg(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Ef,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=uy.get(this.renderer);return void 0===e&&(e=new ym,uy.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new mt(e,t,s)}createCubeRenderTarget(e,t){return new ud(e,t)}createPMREMGenerator(){return new ry(this.renderer)}includes(e){return this.nodes.includes(e)}_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 _f(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new _f(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 Xr)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()!==Gr&&this.updateNodes.push(e.getSelf())}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==Gr&&this.updateBeforeNodes.push(e.getSelf()),s!==Gr&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===P||e.magFilter===B||e.magFilter===R||e.magFilter===F||e.minFilter===P||e.minFilter===B||e.minFilter===R||e.minFilter===F}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 Ef(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.")}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new zs:"vec2"===e?t=new Xe:"vec3"===e?t=new bt:"vec4"===e&&(t=new pt)),"float"===e)return dy(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")}( ${dy(t.r)}, ${dy(t.g)}, ${dy(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)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>4&&t&&(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 Tf(e,t);return 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||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===L)return"int";if(t===k)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;const s=function(e){return Or.get(e)}(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return cy.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof ei||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){return this.stack=eg(this.stack),this.stacks.push(Wn()||this.stack),Hn(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Hn(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 Tf("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),s.structType=e}return e}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 Sf(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let n=r.variable;if(void 0===n){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),n=new wf(t,s),e.push(n),r.variable=n}return n}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 Mf(t,s),e.push(r),i.varying=r}return r}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 Nf("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}buildFunctionNode(e){const t=new Ag,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 Qm(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.cache,n=this.buildStage,o=this.stack,a={code:""};this.flow=a,this.vars={},this.cache=new Ef,this.stack=eg();for(const s of Yr)this.setBuildStage(s),a.result=e.build(this,t);return a.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.cache=r,this.stack=o,this.setBuildStage(n),a}getFunctionOperator(){return null}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){return`${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 td),e.build(this)}else this.addFlow("compute",e);for(const e of Yr){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Xr){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 Of(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Lf(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new kf(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new zf(e);if("color"===t)return new Gf(e);if("mat3"===t)return new Vf(e);if("mat4"===t)return new jf(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}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`}}class my{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,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===Vr){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===jr){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===Hr&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Vr){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===jr){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===Hr&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Vr){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===jr){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===Hr&&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 gy{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}gy.isNodeFunctionInput=!0;class fy extends sf{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,i=kg(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:s,reflectedLight:r},e.stack,e)}}const yy=new Yt,by=new Yt;let xy=null;class _y extends sf{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=vo(new bt).setGroup(bo),this.halfWidth=vo(new bt).setGroup(bo),this.updateType=jr}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;by.identity(),yy.copy(t.matrixWorld),yy.premultiply(s),by.extractRotation(yy),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(by),this.halfHeight.value.applyMatrix4(by)}setup(e){let t,s;super.setup(e),e.isAvailable("float32Filterable")?(t=dl(xy.LTC_FLOAT_1),s=dl(xy.LTC_FLOAT_2)):(t=dl(xy.LTC_HALF_1),s=dl(xy.LTC_HALF_2));const{colorNode:i,light:r}=this,n=e.context.lightingModel,o=Lg(r),a=e.context.reflectedLight;n.directRectArea({lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,reflectedLight:a,ltc_1:t,ltc_2:s},e.stack,e)}static setLTC(e){xy=e}}class vy extends sf{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=vo(0).setGroup(bo),this.penumbraCosNode=vo(0).setGroup(bo),this.cutoffDistanceNode=vo(0).setGroup(bo),this.decayExponentNode=vo(0).setGroup(bo)}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 vh(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,o=Lg(n).sub(Rl),a=o.normalize(),h=a.dot(kg(n)),l=this.getSpotAttenuation(h),u=o.length(),c=rf({lightDistance:u,cutoffDistance:i,decayExponent:r});let d=s.mul(l).mul(c);if(n.map){const e=function(e){const t=Ug(e);if(void 0===t.projectionUV){const s=Dg(e).mul(El);t.projectionUV=s.xyz.div(s.w)}return t.projectionUV}(n),t=dl(n.map,e.xy).onRenderUpdate((()=>n.map));d=e.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(t),d)}const p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:d,reflectedLight:p},e.stack,e)}}class Ty extends vy{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=dl(t,Qn(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class Sy extends sf{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class wy extends sf{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Og(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=vo(new zs).setGroup(bo)}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=Ol.dot(i).mul(.5).add(.5),n=bh(s,t,r);e.context.irradiance.addAssign(n)}}class My extends sf{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new bt);this.lightProbe=tu(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=ff(Ll,this.lightProbe);e.context.irradiance.addAssign(t)}}class Ny{parseFunction(){console.warn("Abstract function.")}}class Ay{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}Ay.isNodeFunction=!0;const Ey=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Cy=/[a-z_0-9]+/gi,Ry="#pragma main";class Py extends Ay{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(Ry),s=-1!==t?e.slice(t+12):e,i=s.match(Ey);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=Cy.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 gy(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 By extends Ny{parseFunction(e){return new Py(e)}}const Fy=new WeakMap;class Iy extends Tm{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new my,this.nodeBuilderCache=new Map,this.callHashCache=new ym,this.groupsData=new ym}updateGroup(e){const t=e.groupNode,s=t.name;if(s===xo.name)return!0;if(s===bo.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===yo.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}const i=[t,e];let r=this.groupsData.get(i);return void 0===r&&this.groupsData.set(i,r={}),r.version!==t.version&&(r.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 vf(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.monitor,e.transforms)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){const s=[e,t],i=this.renderer.info.calls;let r=this.callHashCache.get(s);if(void 0===r||r.callId!==i){const n=this.getEnvironmentNode(e),o=this.getFogNode(e),a=[];t&&a.push(t.getCacheKey(!0)),n&&a.push(n.getCacheKey()),o&&a.push(o.getCacheKey()),a.push(this.renderer.shadowMap.enabled?1:0),r={callId:i,cacheKey:Fr(a)},this.callHashCache.set(s,r)}return r.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e)}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){let i=null;if(!0===s.isCubeTexture||s.mapping===S||s.mapping===w||306===s.mapping)if(e.backgroundBlurriness>0||306===s.mapping)i=Hp(s);else{let e;e=!0===s.isCubeTexture?Kl(s):dl(s),i=gd(e)}else!0===s.isTexture?i=dl(s,Fc.flipY()).setUpdateMatrix(!0):!0!==s.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",s);t.backgroundNode=i,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;if(s.isFogExp2){const t=ru("color","color",s).setGroup(bo),i=ru("density","float",s).setGroup(bo);e=Bg(t,i)}else if(s.isFog){const t=ru("color","color",s).setGroup(bo),i=ru("near","float",s).setGroup(bo),r=ru("far","float",s).setGroup(bo);e=Rg(t,i,r)}else console.error("WebGPUNodes: 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){let e=null;!0===s.isCubeTexture?e=Kl(s):!0===s.isTexture?e=dl(s):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 Fy.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=dl(e,Fc).renderOutput(t.toneMapping,t.currentColorSpace);return Fy.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 my,this.nodeBuilderCache=new Map}}const Uy=new Wi;class Dy{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",null===e?(this.intersectionPlanes=[],this.unionPlanes=[],this.viewNormalMatrix=new Ke,this.clippingGroupContexts=new WeakMap,this.shadowPass=!1):(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix),this.parentVersion=null}projectPlanes(e,t,s){const i=e.length;for(let r=0;r<i;r++){Uy.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=Uy.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=Uy.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowNodeMaterial,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 pt;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 Dy(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class Oy{constructor(e,t){this.scene=e,this.camera=t}clone(){return Object.assign(new this.constructor,this)}}class Ly{constructor(){this.lists=new ym}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new Oy(e,t),s.set(i,r)),r}dispose(){this.lists=new ym}}class ky{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 zy=new Vg;class Gy extends ym{constructor(){super()}createNode(e=[]){return(new Vg).setLights(e)}getNode(e,t){if(e.isQuadMesh)return zy;const s=[e,t];let i=this.get(s);return void 0===i&&(i=this.createNode(),this.set(s,i)),i}}const Vy=new Ui,jy=new Xe,Hy=new pt,Wy=new Yi,$y=new Yt,qy=new pt;class Yy{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}=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 Bm,this.nodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new ky,this.lighting=new Gy,this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new pt(0,0,this._width,this._height),this._scissor=new pt(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 ng(new td),this._quad.material.type="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const l=!0===this.alpha?0:1;this._clearColor=new Zm(0,0,0,l),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr={enabled:!1},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 Iy(this,s),this._animation=new fm(this._nodes,this.info),this._attributes=new Em(s),this._background=new bf(this,this._nodes),this._geometries=new Pm(this._attributes,this.info),this._textures=new Km(this,s,this.info),this._pipelines=new Lm(s,this._nodes),this._bindings=new km(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new vm(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Hm(this.lighting),this._bundles=new Ly,this._renderContexts=new Ym,this._animation.start(),this._initialized=!0,e()}))),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:Vy;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 Dy),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._nodes.updateScene(h),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();const s=this._renderScene(e,t);await this.backend.resolveTimestampAsync(s,"render")}async waitForGPU(){await this.backend.waitForGPU()}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}_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 e=n.opaque;!0===this.opaque&&e.length>0&&this._renderObjects(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(jy),{depth:r,stencil:n}=this;let o=this._frameBufferTarget;return null===o&&(o=new mt(s,i,{depthBuffer:r,stencilBuffer:n,type:G,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:Vy,l=this._renderTarget,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;t.coordinateSystem!==m&&(t.coordinateSystem=m,t.updateProjectionMatrix()),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld();let g=this._viewport,f=this._scissor,y=this._pixelRatio;null!==d&&(g=d.viewport,f=d.scissor,y=1),this.getDrawingBufferSize(jy),Hy.set(0,0,jy.width,jy.height);const b=void 0===g.minDepth?0:g.minDepth,x=void 0===g.maxDepth?1:g.maxDepth;p.viewportValue.copy(g).multiplyScalar(y).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=b,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(Hy),p.scissorValue.copy(f).multiplyScalar(y).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Hy),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new Dy),p.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,d),$y.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),Wy.setFromProjectionMatrix($y,m);const _=this._renderLists.get(e,t);if(_.begin(),this._projectObject(e,t,0,_,p.clippingContext),_.finish(),!0===this.sortObjects&&_.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=_.occlusionQueryCount,this._nodes.updateScene(h),this._background.update(h,_,p),this.backend.beginRender(p);const{bundles:v,lightsNode:T,transparentDoublePass:S,transparent:w,opaque:M}=_;if(v.length>0&&this._renderBundles(v,h,T),!0===this.opaque&&M.length>0&&this._renderObjects(M,t,h,T),!0===this.transparent&&w.length>0&&this._renderTransparents(w,S,t,h,T),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i){this.setRenderTarget(l,u,c);const e=this._quad;this._nodes.hasOutputChange(d.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(d.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}return h.onAfterRender(this,e,t,d),p}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._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._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),r=this._textures.get(i)),this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget){const e=this._quad;this._nodes.hasOutputChange(i.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(i.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}}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)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentToneMapping(){return null!==this._renderTarget?0:this.toneMapping}get currentColorSpace(){return null!==this._renderTarget?ve:this.outputColorSpace}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(),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}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),await this.backend.resolveTimestampAsync(e,"compute")}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(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){if(!1===this._initialized)return console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),!1;this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=qy.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=qy.copy(t).floor()}else t=qy.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){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r)}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||Wy.intersectsSprite(e)){!0===this.sortObjects&&qy.setFromMatrixPosition(e.matrixWorld).applyMatrix4($y);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,qy.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||Wy.intersectsObject(e))){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),qy.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4($y)),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,qy.z,h,r)}}else n.visible&&i.push(e,t,n,s,qy.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 o=e[n],{object:a,geometry:h,material:l,group:u,clippingContext:c}=o;if(t.isArrayCamera){const e=t.cameras;for(let t=0,n=e.length;t<n;t++){const n=e[t];if(a.layers.test(n.layers)){const e=n.viewport,t=void 0===e.minDepth?0:e.minDepth,o=void 0===e.maxDepth?1:e.maxDepth,d=this._currentRenderContext.viewportValue;d.copy(e).multiplyScalar(this._pixelRatio).floor(),d.minDepth=t,d.maxDepth=o,this.backend.updateViewport(this._currentRenderContext),this._currentRenderObjectFunction(a,s,n,h,l,u,i,c,r)}}}else this._currentRenderObjectFunction(a,s,t,h,l,u,i,c,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),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.isShadowNodeMaterial&&(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.scene}this.backend.draw(h,this.info),l&&this._nodes.updateAfter(h)}_createObjectPipeline(e,t,s,i,r,n,o){const a=this._objects.get(e,t,s,i,r,this._currentRenderContext,n,o);this._nodes.updateBefore(a),this._geometries.updateForRender(a),this._nodes.updateForRender(a),this._bindings.updateForRender(a),this._pipelines.getForRender(a,this._compilationPromises),this._nodes.updateAfter(a)}get compile(){return this.compileAsync}}class Xy{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class Ky extends Xy{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)+(Am-e%Am)%Am;var e}get buffer(){return this._buffer}update(){return!0}}class Zy extends Ky{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Qy=0;class Jy extends Zy{constructor(e,t){super("UniformBuffer_"+Qy++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class eb extends Zy{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%Am;0!==n&&Am-n-i<0?e+=Am-n:n%i!=0&&(e+=n%i),s.offset=e/this.bytesPerElement,e+=r*this.bytesPerElement}return Math.ceil(e/Am)*Am}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 tb=0;class sb extends eb{constructor(e,t){super(e),this.id=tb++,this.groupNode=t,this.isNodeUniformsGroup=!0}getNodes(){const e=[];for(const t of this.uniforms){const s=t.nodeUniform.node;if(!s)throw new Error("NodeUniformsGroup: Uniform has no node.");e.push(s)}return e}}let ib=0;class rb extends Xy{constructor(e,t){super(e),this.id=ib++,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 nb extends rb{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 ob extends nb{constructor(e,t,s,i){super(e,t,s,i),this.isSampledCubeTexture=!0}}class ab extends nb{constructor(e,t,s,i){super(e,t,s,i),this.isSampledTexture3D=!0}}const hb={atan2:"atan",textureDimensions:"textureSize",equals:"equal"},lb={low:"lowp",medium:"mediump",high:"highp"},ub={swizzleAssign:!0,storageBuffer:!1},cb="\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 db extends py{constructor(e,t){super(e,t,new By),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]},this.useComparisonMethod=!0}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==xe}getMethod(e){return hb[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?Y:q;2===i?n=r?K:X:3===i?n=r?1032:j:4===i&&(n=r?Z:H);const o={Float32Array:z,Uint8Array:I,Uint16Array:O,Uint32Array:k,Int8Array:U,Int16Array:D,Int32Array:L,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 zi(t.array,a,h,n,o[t.array.constructor.name]||z);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new cl(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="."+Kr.join("").slice(0,u),d=`ivec2(${o} % ${l}, ${o} / ${l})`,p=this.generateTextureLoad(null,n,d,null,"0");let m="vec4";i.pbo.type===k?m="uvec4":i.pbo.type===L&&(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)};`);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){const e=r.node.value;let s="";!0===e.isDataTexture&&(e.type===k?s="u":e.type===L&&(s="i")),t=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("texture3D"===r.type)t=`sampler3D ${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=lb[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!==L){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=[],s=e.getMemberTypes();for(let e=0;e<s.length;e++){const i=s[e];t.push(`layout( location = ${e} ) out ${i} m${e};`)}return t.join("\n")}getStructs(e){const t=[],s=this.structs[e];if(0===s.length)return"layout( location = 0 ) out vec4 fragColor;\n";for(let e=0,i=s.length;e<i;e++){const i=s[e];let r="\n";r+=this.getStructMembers(i),r+="\n",t.push(r)}return t.join("\n\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);t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}${i.needsInterpolation?"out":"/*out*/"} ${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=ub[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)}ub[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);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${cb}\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${cb}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\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 nb(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new ob(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new ab(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 Jy(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 sb(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let pb=null,mb=null,gb=null;class fb{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(){}finish(){}draw(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}createRenderPipeline(){}createComputePipeline(){}destroyPipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}createDefaultTexture(){}createTexture(){}copyTextureToBuffer(){}createAttribute(){}createIndexAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}resolveTimestampAsync(){}hasFeatureAsync(){}hasFeature(){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.count>1?t.count:1}getDrawingBufferSize(){return pb=pb||new Xe,this.renderer.getDrawingBufferSize(pb)}getScissor(){return mb=mb||new pt,this.renderer.getScissor(mb)}setScissorTest(){}getClearColor(){const e=this.renderer;return gb=gb||new Zm,e.getClearColor(gb),gb.getRGB(gb,this.renderer.currentColorSpace),gb}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Qe("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 yb=0;class bb{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 xb{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===L,id:yb++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new bb(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}}let _b,vb,Tb=!1;class Sb{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.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},!1===Tb&&(this._init(this.gl),Tb=!0)}_init(e){_b={[a]:e.FUNC_ADD,[h]:e.FUNC_SUBTRACT,[l]:e.FUNC_REVERSE_SUBTRACT},vb={[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}}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(_b[t],_b[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(vb[s],vb[i],vb[n],vb[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}}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)}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 wb{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===U)return s.BYTE;if(e===D)return s.SHORT;if(e===O)return s.UNSIGNED_SHORT;if(e===L)return s.INT;if(e===k)return s.UNSIGNED_INT;if(e===z)return s.FLOAT;if(e===G)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===Y)return s.RED_INTEGER;if(e===X)return s.RG;if(e===K)return s.RG_INTEGER;if(e===Z)return s.RGBA_INTEGER;if(e===Q||e===J||e===ee||e===te)if(t===_e){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===Q)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===Q)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===V?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 Mb,Nb,Ab,Eb=!1;class Cb{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===Eb&&(this._init(this.gl),Eb=!0)}_init(e){Mb={[M]:e.REPEAT,[N]:e.CLAMP_TO_EDGE,[A]:e.MIRRORED_REPEAT},Nb={[E]:e.NEAREST,[C]:e.NEAREST_MIPMAP_NEAREST,[R]:e.NEAREST_MIPMAP_LINEAR,[P]:e.LINEAR,[B]:e.LINEAR_MIPMAP_NEAREST,[F]:e.LINEAR_MIPMAP_LINEAR},Ab={[Me]:e.NEVER,[Be]:e.ALWAYS,[Ne]:e.LESS,[Ee]:e.LEQUAL,[Ae]:e.EQUAL,[Pe]:e.GEQUAL,[Ce]:e.GREATER,[Re]:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===E||e===C||e===R?t.NEAREST:t.LINEAR}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_INT&&(a=n.DEPTH24_STENCIL8),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,Mb[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,Mb[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,Mb[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Nb[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===P&&n?F:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Nb[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,Ab[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===E)return;if(t.minFilter!==R&&t.minFilter!==F)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){const{gl:n,backend:o}=this,{state:a}=this.backend,{textureGPU:h,glTextureType:l,glType:u,glFormat:c}=o.get(t);let d,p,m,g,f,y;null!==s?(d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=s.min.x,g=s.min.y):(d=e.image.width,p=e.image.height,m=0,g=0),null!==i?(f=i.x,y=i.y):(f=0,y=0),a.bindTexture(l,h),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment);const b=n.getParameter(n.UNPACK_ROW_LENGTH),x=n.getParameter(n.UNPACK_IMAGE_HEIGHT),_=n.getParameter(n.UNPACK_SKIP_PIXELS),v=n.getParameter(n.UNPACK_SKIP_ROWS),T=n.getParameter(n.UNPACK_SKIP_IMAGES),S=e.isCompressedTexture?e.mipmaps[r]:e.image;if(n.pixelStorei(n.UNPACK_ROW_LENGTH,S.width),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,S.height),n.pixelStorei(n.UNPACK_SKIP_PIXELS,m),n.pixelStorei(n.UNPACK_SKIP_ROWS,g),e.isRenderTargetTexture||e.isDepthTexture){const s=o.get(e),i=o.get(t),r=o.get(s.renderTarget),h=o.get(i.renderTarget),l=r.framebuffers[s.cacheKey],u=h.framebuffers[i.cacheKey];a.bindFramebuffer(n.READ_FRAMEBUFFER,l),a.bindFramebuffer(n.DRAW_FRAMEBUFFER,u);let c=n.COLOR_BUFFER_BIT;e.isDepthTexture&&(c=n.DEPTH_BUFFER_BIT),n.blitFramebuffer(m,g,d,p,f,y,d,p,c,n.NEAREST),a.bindFramebuffer(n.READ_FRAMEBUFFER,null),a.bindFramebuffer(n.DRAW_FRAMEBUFFER,null)}else e.isDataTexture?n.texSubImage2D(n.TEXTURE_2D,r,f,y,d,p,c,u,S.data):e.isCompressedTexture?n.compressedTexSubImage2D(n.TEXTURE_2D,r,f,y,S.width,S.height,c,S.data):n.texSubImage2D(n.TEXTURE_2D,r,f,y,d,p,c,u,S);n.pixelStorei(n.UNPACK_ROW_LENGTH,b),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,x),n.pixelStorei(n.UNPACK_SKIP_PIXELS,_),n.pixelStorei(n.UNPACK_SKIP_ROWS,v),n.pixelStorei(n.UNPACK_SKIP_IMAGES,T),0===r&&t.generateMipmaps&&n.generateMipmap(n.TEXTURE_2D),a.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.gerDrawingBufferSize().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){const{gl:s}=this,i=t.renderTarget,{samples:r,depthTexture:n,depthBuffer:o,stencilBuffer:a,width:h,height:l}=i;if(s.bindRenderbuffer(s.RENDERBUFFER,e),o&&!a){let t=s.DEPTH_COMPONENT24;r>0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,r,t,h,l)):s.renderbufferStorage(s.RENDERBUFFER,t,h,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(r>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,h,l):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,h,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.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 Rb{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 Pb{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 Bb={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 Fb{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,i,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,r,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,r,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,n,1)}}}class Ib extends fb{constructor(e={}){super(e),this.isWebGLBackend=!0}init(e){super.init(e);const t=this.parameters,s=void 0!==t.context?t.context:e.domElement.getContext("webgl2");function i(t){t.preventDefault();const s={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(s)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new Rb(this),this.capabilities=new Pb(this),this.attributeUtils=new xb(this),this.textureUtils=new Cb(this),this.bufferRenderer=new Fb(this),this.state=new Sb(this),this.utils=new wb(this),this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.trackTimestamp=!0===t.trackTimestamp,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"),this._knownBindings=new WeakSet,this._currentContext=null}get coordinateSystem(){return Ue}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=this.get(e);if(this.queryRunning)return t.queryQueue||(t.queryQueue=[]),void t.queryQueue.push(e);t.activeQuery&&(this.gl.endQuery(this.disjoint.TIME_ELAPSED_EXT),t.activeQuery=null),t.activeQuery=this.gl.createQuery(),null!==t.activeQuery&&(this.gl.beginQuery(this.disjoint.TIME_ELAPSED_EXT,t.activeQuery),this.queryRunning=!0)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=this.get(e);if(t.activeQuery&&(this.gl.endQuery(this.disjoint.TIME_ELAPSED_EXT),t.gpuQueries||(t.gpuQueries=[]),t.gpuQueries.push({query:t.activeQuery}),t.activeQuery=null,this.queryRunning=!1,t.queryQueue&&t.queryQueue.length>0)){const e=t.queryQueue.shift();this.initTimestampQuery(e)}}async resolveTimestampAsync(e,t="render"){if(!this.disjoint||!this.trackTimestamp)return;const s=this.get(e);s.gpuQueries||(s.gpuQueries=[]);for(let e=0;e<s.gpuQueries.length;e++){const i=s.gpuQueries[e],r=this.gl.getQueryParameter(i.query,this.gl.QUERY_RESULT_AVAILABLE),n=this.gl.getParameter(this.disjoint.GPU_DISJOINT_EXT);if(r&&!n){const r=this.gl.getQueryParameter(i.query,this.gl.QUERY_RESULT),n=Number(r)/1e6;this.gl.deleteQuery(i.query),s.gpuQueries.splice(e,1),e--,this.renderer.info.updateTimestamp(t,n)}}}getContext(){return this.gl}beginRender(e){const{gl:t}=this,s=this.get(e);if(this.initTimestampQuery(e),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1),e.viewport?this.updateViewport(e):t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight),e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext,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){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),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),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray)}}null!==r&&(this._setFramebuffer(r),r.viewport?this.updateViewport(r):t.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)&&(r.getQueryParameter(n,r.QUERY_RESULT)>0&&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 t=this.gl,{x:s,y:i,width:r,height:n}=e.viewportValue;t.viewport(s,e.height-n-i,r,n)}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST)}clear(e,t,s,i=null,r=!0){const{gl:n}=this;if(null===i){const e=this.getClearColor();e.r*=e.a,e.g*=e.a,e.b*=e.a,i={textures:null,clearColorValue:e}}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 a;if(i.clearColorValue?a=i.clearColorValue:(a=this.getClearColor(),a.r*=a.a,a.g*=a.a,a.b*=a.a),t&&this.state.setDepthMask(!0),null===i.textures)n.clearColor(a.r,a.g,a.b,a.a),n.clear(o);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)n.clearBufferfv(n.COLOR,e,[a.r,a.g,a.b,a.a]);t&&s?n.clearBufferfi(n.DEPTH_STENCIL,0,1,0):t?n.clearBufferfv(n.DEPTH,0,[1]):s&&n.clearBufferiv(n.STENCIL,0,[0])}}}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;this.discard||(n.enable(n.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:a,attributes:h}=this.get(i),l=this._getVaoKey(null,h),u=this.vaoCache[l];void 0===u?this._createVao(null,h):n.bindVertexArray(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.getIndex(),e.getAttributes());if(p=this.vaoCache[t],void 0===p){let t;({vaoGPU:p,staticVao:t}=this._createVao(e.getIndex(),e.getAttributes())),t&&(d.staticVao=p,d.geometryId=e.geometry.id)}}a.bindVertexArray(p);const m=e.getIndex(),g=l.lastOcclusionObject;if(g!==t&&void 0!==g){if(null!==g&&!0===g.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 f=this.bufferRenderer;t.isPoints?f.mode=a.POINTS:t.isLineSegments?f.mode=a.LINES:t.isLine?f.mode=a.LINE_STRIP:t.isLineLoop?f.mode=a.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),f.mode=a.LINES):f.mode=a.TRIANGLES;const{vertexCount:y,instanceCount:b}=u;let{firstVertex:x}=u;if(f.object=t,null!==m){x*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);f.index=m.count,f.type=e.type}else f.index=0;var _;t.isBatchedMesh?null!==t._multiDrawInstances?f.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances):this.hasFeature("WEBGL_multi_draw")?f.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):(_="THREE.WebGLRenderer: WEBGL_multi_draw not supported.")in Je||(Je[_]=!0,console.warn(_)):b>1?f.renderInstances(x,y,b):f.render(x,y),a.bindVertexArray(null)}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)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new db(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(){console.warn("Abstract class.")}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)}updateSize(){}hasFeature(e){const t=Object.keys(Bb).filter((t=>Bb[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,i,r){this.textureUtils.copyTextureToTexture(e,t,s,i,r)}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;let u=n.msaaFrameBuffer,c=n.depthRenderbuffer;const d=qm(e);let p;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),p=n.cubeFramebuffers[d]):(n.framebuffers||(n.framebuffers={}),p=n.framebuffers[d]),void 0===p){p=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,p);const i=e.textures;if(l){n.cubeFramebuffers[d]=p;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[d]=p;for(let s=0;s<i.length;s++){const r=i[s],n=this.get(r);n.renderTarget=e.renderTarget,n.cacheKey=d;const o=t.COLOR_ATTACHMENT0+s;t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0)}s.drawBuffers(e,p)}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=d,t.framebufferTexture2D(t.FRAMEBUFFER,i,t.TEXTURE_2D,s.textureGPU,0)}}if(o>0){if(void 0===u){const i=[];u=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,u);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=u,n.msaaRenderbuffers=r,void 0===c){c=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(c,e),n.depthRenderbuffer=c;const s=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=p}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e,t){let s=[];if(null!==e){s+=":"+this.get(e).id}for(let e=0;e<t.length;e++){s+=":"+this.get(t[e]).id}return s}_createVao(e,t){const{gl:s}=this,i=s.createVertexArray();let r="",n=!0;if(s.bindVertexArray(i),null!==e){const t=this.get(e);s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t.bufferGPU),r+=":"+t.id}for(let e=0;e<t.length;e++){const i=t[e],o=this.get(i);let a,h;r+=":"+o.id,s.bindBuffer(s.ARRAY_BUFFER,o.bufferGPU),s.enableVertexAttribArray(e),(i.isStorageBufferAttribute||i.isStorageInstancedBufferAttribute)&&(n=!1),!0===i.isInterleavedBufferAttribute?(a=i.data.stride*o.bytesPerElement,h=i.offset*o.bytesPerElement):(a=0,h=0),o.isInteger?s.vertexAttribIPointer(e,i.itemSize,o.type,a,h):s.vertexAttribPointer(e,i.itemSize,o.type,i.normalized,a,h),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?s.vertexAttribDivisor(e,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&s.vertexAttribDivisor(e,i.data.meshPerAttribute)}return s.bindBuffer(s.ARRAY_BUFFER,null),this.vaoCache[r]=i,{vaoGPU:i,staticVao:n}}_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)}}dispose(){this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Ub="point-list",Db="line-list",Ob="line-strip",Lb="triangle-list",kb="triangle-strip",zb="never",Gb="less",Vb="equal",jb="less-equal",Hb="greater",Wb="not-equal",$b="greater-equal",qb="always",Yb="store",Xb="load",Kb="clear",Zb="ccw",Qb="none",Jb="front",ex="back",tx="uint16",sx="uint32",ix={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10uFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Stencil8:"stencil8",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},rx="clamp-to-edge",nx="repeat",ox="mirror-repeat",ax="linear",hx="nearest",lx="zero",ux="one",cx="src",dx="one-minus-src",px="src-alpha",mx="one-minus-src-alpha",gx="dst",fx="one-minus-dst",yx="dst-alpha",bx="one-minus-dst-alpha",xx="src-alpha-saturated",_x="constant",vx="one-minus-constant",Tx="add",Sx="subtract",wx="reverse-subtract",Mx="min",Nx="max",Ax=0,Ex=15,Cx="keep",Rx="zero",Px="replace",Bx="invert",Fx="increment-clamp",Ix="decrement-clamp",Ux="increment-wrap",Dx="decrement-wrap",Ox="storage",Lx="read-only-storage",kx="write-only",zx="read-only",Gx="read-write",Vx="float",jx="unfilterable-float",Hx="depth",Wx="sint",$x="uint",qx="2d",Yx="3d",Xx="2d",Kx="2d-array",Zx="cube",Qx="3d",Jx="all",e_="vertex",t_="instance",s_={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 i_ extends Xy{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class r_ extends i_{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class n_ extends Ky{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let o_=0;class a_ extends n_{constructor(e,t){super("StorageBuffer_"+o_++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:qr,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class h_ extends Tm{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:ax}),this.flipYSampler=e.createSampler({minFilter:hx}),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:kb,stripIndexFormat:sx},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:kb,stripIndexFormat:sx},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:Xx,baseArrayLayer:s}),u=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:Xx,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:Kb,storeOp:Yb,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:Xx,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:Xx,baseArrayLayer:s}),u={colorAttachments:[{view:l,loadOp:Kb,storeOp:Yb,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 l_={[Me]:"never",[Ne]:"less",[Ae]:"equal",[Ee]:"less-equal",[Ce]:"greater",[Pe]:"greater-equal",[Be]:"always",[Re]:"not-equal"},u_=[0,1,3,2,4,5];class c_{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new Qi,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===ax&&r.minFilter===ax&&r.mipmapFilter===ax&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=l_[e.compareFunction]),i.sampler=s.createSampler(r)}createDefaultTexture(e){let t;const s=d_(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||d_(e,s.device);i.format=l;let u=void 0!==t.sampleCount?t.sampleCount:1;u=s.utils.getSampleCount(u);const c=e.isRenderTargetTexture&&!e.isMultisampleRenderTargetTexture?1:u;let d=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(d|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&(d|=GPUTextureUsage.RENDER_ATTACHMENT);const p={label:e.name,size:{width:r,height:n,depthOrArrayLayers:o},mipLevelCount:a,sampleCount:c,dimension:h,format:l,usage:d};if(e.isVideoTexture){const t=e.source.data,s=new VideoFrame(t);p.size.width=s.displayWidth,p.size.height=s.displayHeight,s.close(),i.externalTexture=t}else{if(void 0===l)return console.warn("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);i.texture=s.device.createTexture(p)}if(e.isRenderTargetTexture&&u>1&&!e.isMultisampleRenderTargetTexture){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=u,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}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=V):e&&(a=W,h=k),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,{sampleCount:s.utils.getSampleCount(s.renderer.samples),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===S||t===w||t===v||t===T}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new dt;s.minFilter=E,s.magFilter=E,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 Fi;s.minFilter=E,s.magFilter=E,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?u_[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},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,s,i)}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new h_(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===ix.BC1RGBAUnorm||e===ix.BC1RGBAUnormSRGB?{byteLength:8,width:4,height:4}:e===ix.BC2RGBAUnorm||e===ix.BC2RGBAUnormSRGB||e===ix.BC3RGBAUnorm||e===ix.BC3RGBAUnormSRGB?{byteLength:16,width:4,height:4}:e===ix.BC4RUnorm||e===ix.BC4RSNorm?{byteLength:8,width:4,height:4}:e===ix.BC5RGUnorm||e===ix.BC5RGSnorm||e===ix.BC6HRGBUFloat||e===ix.BC6HRGBFloat||e===ix.BC7RGBAUnorm||e===ix.BC7RGBAUnormSRGB?{byteLength:16,width:4,height:4}:e===ix.ETC2RGB8Unorm||e===ix.ETC2RGB8UnormSRGB||e===ix.ETC2RGB8A1Unorm||e===ix.ETC2RGB8A1UnormSRGB?{byteLength:8,width:4,height:4}:e===ix.ETC2RGBA8Unorm||e===ix.ETC2RGBA8UnormSRGB?{byteLength:16,width:4,height:4}:e===ix.EACR11Unorm||e===ix.EACR11Snorm?{byteLength:8,width:4,height:4}:e===ix.EACRG11Unorm||e===ix.EACRG11Snorm||e===ix.ASTC4x4Unorm||e===ix.ASTC4x4UnormSRGB?{byteLength:16,width:4,height:4}:e===ix.ASTC5x4Unorm||e===ix.ASTC5x4UnormSRGB?{byteLength:16,width:5,height:4}:e===ix.ASTC5x5Unorm||e===ix.ASTC5x5UnormSRGB?{byteLength:16,width:5,height:5}:e===ix.ASTC6x5Unorm||e===ix.ASTC6x5UnormSRGB?{byteLength:16,width:6,height:5}:e===ix.ASTC6x6Unorm||e===ix.ASTC6x6UnormSRGB?{byteLength:16,width:6,height:6}:e===ix.ASTC8x5Unorm||e===ix.ASTC8x5UnormSRGB?{byteLength:16,width:8,height:5}:e===ix.ASTC8x6Unorm||e===ix.ASTC8x6UnormSRGB?{byteLength:16,width:8,height:6}:e===ix.ASTC8x8Unorm||e===ix.ASTC8x8UnormSRGB?{byteLength:16,width:8,height:8}:e===ix.ASTC10x5Unorm||e===ix.ASTC10x5UnormSRGB?{byteLength:16,width:10,height:5}:e===ix.ASTC10x6Unorm||e===ix.ASTC10x6UnormSRGB?{byteLength:16,width:10,height:6}:e===ix.ASTC10x8Unorm||e===ix.ASTC10x8UnormSRGB?{byteLength:16,width:10,height:8}:e===ix.ASTC10x10Unorm||e===ix.ASTC10x10UnormSRGB?{byteLength:16,width:10,height:10}:e===ix.ASTC12x10Unorm||e===ix.ASTC12x10UnormSRGB?{byteLength:16,width:12,height:10}:e===ix.ASTC12x12Unorm||e===ix.ASTC12x12UnormSRGB?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=rx;return e===M?t=nx:e===A&&(t=ox),t}_convertFilterMode(e){let t=ax;return e!==E&&e!==C&&e!==R||(t=hx),t}_getBytesPerTexel(e){return e===ix.R8Unorm||e===ix.R8Snorm||e===ix.R8Uint||e===ix.R8Sint?1:e===ix.R16Uint||e===ix.R16Sint||e===ix.R16Float||e===ix.RG8Unorm||e===ix.RG8Snorm||e===ix.RG8Uint||e===ix.RG8Sint?2:e===ix.R32Uint||e===ix.R32Sint||e===ix.R32Float||e===ix.RG16Uint||e===ix.RG16Sint||e===ix.RG16Float||e===ix.RGBA8Unorm||e===ix.RGBA8UnormSRGB||e===ix.RGBA8Snorm||e===ix.RGBA8Uint||e===ix.RGBA8Sint||e===ix.BGRA8Unorm||e===ix.BGRA8UnormSRGB||e===ix.RGB9E5UFloat||e===ix.RGB10A2Unorm||e===ix.RG11B10UFloat||e===ix.Depth32Float||e===ix.Depth24Plus||e===ix.Depth24PlusStencil8||e===ix.Depth32FloatStencil8?4:e===ix.RG32Uint||e===ix.RG32Sint||e===ix.RG32Float||e===ix.RGBA16Uint||e===ix.RGBA16Sint||e===ix.RGBA16Float?8:e===ix.RGBA32Uint||e===ix.RGBA32Sint||e===ix.RGBA32Float?16:void 0}_getTypedArrayType(e){return e===ix.R8Uint?Uint8Array:e===ix.R8Sint?Int8Array:e===ix.R8Unorm?Uint8Array:e===ix.R8Snorm?Int8Array:e===ix.RG8Uint?Uint8Array:e===ix.RG8Sint?Int8Array:e===ix.RG8Unorm?Uint8Array:e===ix.RG8Snorm?Int8Array:e===ix.RGBA8Uint?Uint8Array:e===ix.RGBA8Sint?Int8Array:e===ix.RGBA8Unorm?Uint8Array:e===ix.RGBA8Snorm?Int8Array:e===ix.R16Uint?Uint16Array:e===ix.R16Sint?Int16Array:e===ix.RG16Uint?Uint16Array:e===ix.RG16Sint?Int16Array:e===ix.RGBA16Uint?Uint16Array:e===ix.RGBA16Sint?Int16Array:e===ix.R16Float||e===ix.RG16Float||e===ix.RGBA16Float?Uint16Array:e===ix.R32Uint?Uint32Array:e===ix.R32Sint?Int32Array:e===ix.R32Float?Float32Array:e===ix.RG32Uint?Uint32Array:e===ix.RG32Sint?Int32Array:e===ix.RG32Float?Float32Array:e===ix.RGBA32Uint?Uint32Array:e===ix.RGBA32Sint?Int32Array:e===ix.RGBA32Float?Float32Array:e===ix.BGRA8Unorm||e===ix.BGRA8UnormSRGB?Uint8Array:e===ix.RGB10A2Unorm||e===ix.RGB9E5UFloat||e===ix.RG11B10UFloat?Uint32Array:e===ix.Depth32Float?Float32Array:e===ix.Depth24Plus||e===ix.Depth24PlusStencil8?Uint32Array:e===ix.Depth32FloatStencil8?Float32Array:void 0}_getDimension(e){let t;return t=e.isData3DTexture?Yx:qx,t}}function d_(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?ix.BC1RGBAUnormSRGB:ix.BC1RGBAUnorm;break;case ee:n=r===_e?ix.BC2RGBAUnormSRGB:ix.BC2RGBAUnorm;break;case te:n=r===_e?ix.BC3RGBAUnormSRGB:ix.BC3RGBAUnorm;break;case se:n=r===_e?ix.ETC2RGB8UnormSRGB:ix.ETC2RGB8Unorm;break;case ie:n=r===_e?ix.ETC2RGBA8UnormSRGB:ix.ETC2RGBA8Unorm;break;case re:n=r===_e?ix.ASTC4x4UnormSRGB:ix.ASTC4x4Unorm;break;case ne:n=r===_e?ix.ASTC5x4UnormSRGB:ix.ASTC5x4Unorm;break;case oe:n=r===_e?ix.ASTC5x5UnormSRGB:ix.ASTC5x5Unorm;break;case ae:n=r===_e?ix.ASTC6x5UnormSRGB:ix.ASTC6x5Unorm;break;case he:n=r===_e?ix.ASTC6x6UnormSRGB:ix.ASTC6x6Unorm;break;case le:n=r===_e?ix.ASTC8x5UnormSRGB:ix.ASTC8x5Unorm;break;case ue:n=r===_e?ix.ASTC8x6UnormSRGB:ix.ASTC8x6Unorm;break;case ce:n=r===_e?ix.ASTC8x8UnormSRGB:ix.ASTC8x8Unorm;break;case de:n=r===_e?ix.ASTC10x5UnormSRGB:ix.ASTC10x5Unorm;break;case pe:n=r===_e?ix.ASTC10x6UnormSRGB:ix.ASTC10x6Unorm;break;case me:n=r===_e?ix.ASTC10x8UnormSRGB:ix.ASTC10x8Unorm;break;case ge:n=r===_e?ix.ASTC10x10UnormSRGB:ix.ASTC10x10Unorm;break;case fe:n=r===_e?ix.ASTC12x10UnormSRGB:ix.ASTC12x10Unorm;break;case ye:n=r===_e?ix.ASTC12x12UnormSRGB:ix.ASTC12x12Unorm;break;case H:n=r===_e?ix.RGBA8UnormSRGB:ix.RGBA8Unorm;break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case H:switch(i){case U:n=ix.RGBA8Snorm;break;case D:n=ix.RGBA16Sint;break;case O:n=ix.RGBA16Uint;break;case k:n=ix.RGBA32Uint;break;case L:n=ix.RGBA32Sint;break;case I:n=r===_e?ix.RGBA8UnormSRGB:ix.RGBA8Unorm;break;case G:n=ix.RGBA16Float;break;case z:n=ix.RGBA32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case j:if(35902===i)n=ix.RGB9E5UFloat;else console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",i);break;case q:switch(i){case U:n=ix.R8Snorm;break;case D:n=ix.R16Sint;break;case O:n=ix.R16Uint;break;case k:n=ix.R32Uint;break;case L:n=ix.R32Sint;break;case I:n=ix.R8Unorm;break;case G:n=ix.R16Float;break;case z:n=ix.R32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case X:switch(i){case U:n=ix.RG8Snorm;break;case D:n=ix.RG16Sint;break;case O:n=ix.RG16Uint;break;case k:n=ix.RG32Uint;break;case L:n=ix.RG32Sint;break;case I:n=ix.RG8Unorm;break;case G:n=ix.RG16Float;break;case z:n=ix.RG32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case W:switch(i){case O:n=ix.Depth16Unorm;break;case k:n=ix.Depth24Plus;break;case z:n=ix.Depth32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case $:switch(i){case V:n=ix.Depth24PlusStencil8;break;case z:t&&!1===t.features.has(s_.Depth32FloatStencil8)&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),n=ix.Depth32FloatStencil8;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case Y:switch(i){case L:n=ix.R32Sint;break;case k:n=ix.R32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case K:switch(i){case L:n=ix.RG32Sint;break;case k:n=ix.RG32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Z:switch(i){case L:n=ix.RGBA32Sint;break;case k:n=ix.RGBA32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}return n}const p_=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,m_=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,g_={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_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 f_ extends Ay{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(p_);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=m_.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=g_[r]),n.push(new gy(r,t))}const o=e.substring(t[0].length),a=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:g_[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 y_ extends Ny{parseFunction(e){return new f_(e)}}const b_="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},x_={[Wr]:"read",[$r]:"write",[qr]:"read_write"},__={[M]:"repeat",[N]:"clamp",[A]:"mirror"},v_={vertex:b_?b_.VERTEX:1,fragment:b_?b_.FRAGMENT:2,compute:b_?b_.COMPUTE:4},T_={instance:!0,swizzleAssign:!1,storageBuffer:!0},S_={"^^":"tsl_xor"},w_={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>"},M_={},N_={tsl_xor:new Ng("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Ng("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Ng("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Ng("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Ng("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Ng("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Ng("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Ng("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 Ng("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 Ng("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Ng("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 Ng("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Ng("\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")},A_={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)&&(N_.pow_float=new Ng("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),N_.pow_vec2=new Ng("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 ) ); }",[N_.pow_float]),N_.pow_vec3=new Ng("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 ) ); }",[N_.pow_float]),N_.pow_vec4=new Ng("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 ) ); }",[N_.pow_float]),A_.pow_float="tsl_pow_float",A_.pow_vec2="tsl_pow_vec2",A_.pow_vec3="tsl_pow_vec3",A_.pow_vec4="tsl_pow_vec4");let E_="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(E_+="diagnostic( off, derivative_uniformity );\n");class C_ extends py{constructor(e,t){super(e,t,new y_),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&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,r,i)}generateWrapFunction(e){const t=`tsl_coord_${__[e.wrapS]}S_${__[e.wrapT]}T`;let s=M_[t];if(void 0===s){const i=[];let r=`fn ${t}( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;const n=(e,t)=>{e===M?(i.push(N_.repeatWrapping_float),r+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===N?(i.push(N_.clampWrapping_float),r+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===A?(i.push(N_.mirrorWrapping_float),r+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(r+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};n(e.wrapS,"x"),r+=",\n",n(e.wrapT,"y"),r+="\n\t);\n\n}\n",M_[t]=s=new Ng(r,i)}return s.build(this),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;n=!0===e.isMultisampleRenderTargetTexture?t:`${t}, u32( ${s} )`,r=new Eh(new tl(`textureDimensions( ${n} )`,"uvec2")),i.dimensionsSnippet[s]=r}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=`vec2u( ${this.generateWrapFunction(e)}( ${s} ) * vec2f( ${this.generateTextureDimension(e,t,r)} ) )`;return this.generateTextureLoad(e,t,n,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===E&&e.magFilter===E||!0===e.isMultisampleRenderTargetTexture}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?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=S_[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Wr:e.access}getStorageAccess(e,t){return x_[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 i;const o=e.groupNode,a=o.name,h=this.getBindGroupArray(a,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let n=null;const a=this.getNodeAccess(e,s);if("texture"===t||"storageTexture"===t?n=new nb(r.name,r.node,o,a):"cubeTexture"===t?n=new ob(r.name,r.node,o,a):"texture3D"===t&&(n=new ab(r.name,r.node,o,a)),n.store=!0===e.isStorageTextureNode,n.setVisibility(v_[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new r_(`${r.name}_sampler`,r.node,o);e.setVisibility(v_[s]),h.push(e,n),i=[e,n]}else h.push(n),i=[n]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?Jy:a_)(e,o);r.setVisibility(v_[s]),h.push(r),i=r}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new sb(a,o),n.setVisibility(v_[s]),e[a]=n,h.push(n)),i=this.getNodeUniform(r,t),n.addUniform(i)}n.uniformGPU=i}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","id","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=[],s=e.getMemberTypes();for(let e=0;e<s.length;e++){const i=s[e];t.push(`\t@location( ${e} ) m${e} : ${i}<f32>`)}const i=this.getBuiltins("output");return i&&t.push("\t"+i),t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,i=s.length;e<i;e++){const i=s[e],r=i.name;let n=`struct ${r} {\n`;n+=this.getStructMembers(i),n+="\n}",t.push(n),t.push(`\nvar<private> output : ${r};\n\n`)}return t.join("\n\n")}getVar(e,t){return`var ${t} : ${this.getType(e)}`}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)};`);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}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&&!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="";if(!0===t.isMultisampleRenderTargetTexture&&(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<${d_(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.bufferType),n=t.bufferCount,a=n>0&&"buffer"===r.type?", "+n:"",h=t.isAtomic?`atomic<${s}>`:`${s}`,l=`\t${r.name} : array< ${h}${a} >\n`,u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+t.id,l,u,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){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\t`),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.nodeType,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;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}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 w_[e]||e}isAvailable(e){let t=T_[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),T_[e]=t),t}_getWGSLMethod(e){return void 0!==N_[e]&&this._include(e),A_[e]}_include(e){const t=N_[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// 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${E_}\n\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\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// 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 = id.x + id.y * numWorkgroups.x * u32(${t}) + id.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 R_{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=ix.Depth24PlusStencil8:e.depth&&(t=ix.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}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?Ub:e.isLineSegments||e.isMesh&&!0===t.wireframe?Db:e.isLine?Ob:e.isMesh?Lb: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(){return navigator.userAgent.includes("Quest")?ix.BGRA8Unorm:navigator.gpu.getPreferredCanvasFormat()}}const P_=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),B_=new Map([[ei,["float16"]]]),F_=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class I_{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&&(a.constructor===Int16Array||a.constructor===Uint16Array)){const e=new Uint32Array(a.length);for(let t=0;t<a.length;t++)e[t]=a[t];a=e}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}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).buffer,n=t.array,o=this._isTypedArray(n),a=t.updateRanges;if(0===a.length)i.queue.writeBuffer(r,0,n,0);else{const e=o?1:n.BYTES_PER_ELEMENT;for(let t=0,s=a.length;t<s;t++){const s=a[t],o=s.start*e,h=s.count*e;i.queue.writeBuffer(r,0,n,o,h)}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?t_:e_):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?t_:e_),!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,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),o=s.createCommandEncoder({});o.copyBufferToBuffer(i,0,n,0,r),n.unmap();const a=o.finish();s.queue.submit([a]),await n.mapAsync(GPUMapMode.READ);return n.getMappedRange()}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1==t)n=F_.get(i);else{const e=(B_.get(r)||P_.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 U_{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend.device,s=[];let i=0;for(const t of e.bindings){const e={binding:i++,visibility:t.visibility};if(t.isUniformBuffer||t.isStorageBuffer){const s={};t.isStorageBuffer&&(4&t.visibility&&(t.access===qr||t.access===$r)?s.type=Ox:s.type=Lx),e.buffer=s}else if(t.isSampler){const s={};t.texture.isDepthTexture&&null!==t.texture.compareFunction&&(s.type="comparison"),e.sampler=s}else if(t.isSampledTexture&&t.texture.isVideoTexture)e.externalTexture={};else if(t.isSampledTexture&&t.store){const s={};s.format=this.backend.get(t.texture).texture.format;const i=t.access;s.access=i===qr?Gx:i===$r?kx:zx,e.storageTexture=s}else if(t.isSampledTexture){const s={};if(!0===t.texture.isMultisampleRenderTargetTexture&&(s.multisampled=!0),t.texture.isDepthTexture)s.sampleType=Hx;else if(t.texture.isDataTexture||t.texture.isDataArrayTexture||t.texture.isData3DTexture){const e=t.texture.type;e===L?s.sampleType=Wx:e===k?s.sampleType=$x:e===z&&(this.backend.hasFeature("float32-filterable")?s.sampleType=Vx:s.sampleType=jx)}t.isSampledCubeTexture?s.viewDimension=Zx:t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?s.viewDimension=Kx:t.isSampledTexture3D&&(s.viewDimension=Qx),e.texture=s}else console.error(`WebGPUBindingUtils: Unsupported binding "${t}".`);s.push(e)}return t.createBindGroupLayout({entries:s})}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)}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=Jx;let n;n=t.isSampledCubeTexture?Zx:t.isSampledTexture3D?Qx:t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Kx:Xx,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 D_{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),S=this._getSampleCount(e.context),w={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},x,{targets:y}),primitive:_,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:l.createPipelineLayout({bindGroupLayouts:d})},M={},N=e.context.depth,A=e.context.stencil;if(!0!==N&&!0!==A||(!0===N&&(M.format=T,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),!0===A&&(M.stencilFront=g,M.stencilBack={},M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),w.depthStencil=M),null===t)c.pipeline=l.createRenderPipeline(w);else{const e=new Promise((e=>{l.createRenderPipelineAsync(w).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:Tx},s={srcFactor:r,dstFactor:n,operation:Tx}};if(e.premultipliedAlpha)switch(i){case 1:r(ux,mx,ux,mx);break;case 2:r(ux,ux,ux,ux);break;case 3:r(lx,dx,lx,ux);break;case 4:r(lx,cx,lx,px)}else switch(i){case 1:r(px,mx,ux,mx);break;case 2:r(px,ux,px,ux);break;case 3:r(lx,dx,lx,ux);break;case 4:r(lx,cx,lx,cx)}}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 200:t=lx;break;case 201:t=ux;break;case 202:t=cx;break;case 203:t=dx;break;case m:t=px;break;case g:t=mx;break;case 208:t=gx;break;case 209:t=fx;break;case 206:t=yx;break;case 207:t=bx;break;case 210:t=xx;break;case 211:t=_x;break;case 212:t=vx;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=zb;break;case 519:t=qb;break;case 513:t=Gb;break;case 515:t=jb;break;case 514:t=Vb;break;case 518:t=$b;break;case 516:t=Hb;break;case 517:t=Wb;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case we:t=Cx;break;case 0:t=Rx;break;case 7681:t=Px;break;case 5386:t=Bx;break;case 7682:t=Fx;break;case 7683:t=Ix;break;case 34055:t=Ux;break;case 34056:t=Dx;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case a:t=Tx;break;case 101:t=Sx;break;case 102:t=wx;break;case 103:t=Mx;break;case 104:t=Nx;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?tx:sx),s.side){case 0:i.frontFace=Zb,i.cullMode=ex;break;case 1:i.frontFace=Zb,i.cullMode=Jb;break;case 2:i.frontFace=Zb,i.cullMode=Qb;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?Ex:Ax}_getDepthCompare(e){let t;if(!1===e.depthTest)t=qb;else{const s=e.depthFunc;switch(s){case 0:t=zb;break;case 1:t=qb;break;case 2:t=Gb;break;case 3:t=jb;break;case 4:t=Vb;break;case 5:t=$b;break;case 6:t=Hb;break;case 7:t=Wb;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class O_ extends fb{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.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new R_(this),this.attributeUtils=new I_(this),this.bindingUtils=new U_(this),this.pipelineUtils=new D_(this),this.textureUtils=new c_(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(s_),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(s_.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){const t=e.renderTarget,s=this.get(t);let i=s.descriptors;if(void 0===i||s.width!==t.width||s.height!==t.height||s.activeMipmapLevel!==t.activeMipmapLevel||s.samples!==t.samples){i={},s.descriptors=i;const e=()=>{t.removeEventListener("dispose",e),this.delete(t)};t.addEventListener("dispose",e)}const r=e.getCacheKey();let n=i[r];if(void 0===n){const o=e.textures,a=[];for(let t=0;t<o.length;t++){const s=this.get(o[t]),i=s.texture.createView({baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,dimension:Xx});let r,n;void 0!==s.msaaTexture?(r=s.msaaTexture.createView(),n=i):(r=i,n=void 0),a.push({view:r,resolveTarget:n,loadOp:Xb,storeOp:Yb})}if(n={colorAttachments:a},e.depth){const t={view:this.get(e.depthTexture).texture.createView()};n.depthStencilAttachment=t}i[r]=n,s.width=t.width,s.height=t.height,s.samples=t.samples,s.activeMipmapLevel=t.activeMipmapLevel}return n}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),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=Kb,i.storeOp=Yb):(i.loadOp=Xb,i.storeOp=Yb)}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=Kb,t.storeOp=Yb):(t.loadOp=Xb,t.storeOp=Yb)}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=Kb,o.depthStoreOp=Yb):(o.depthLoadOp=Xb,o.depthStoreOp=Yb)),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=Kb,o.stencilStoreOp=Yb):(o.stencilLoadOp=Xb,o.stencilStoreOp=Yb));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.prepareTimestampBuffer(e,t.encoder),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)}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();if(!0===this.renderer.alpha){const t=e.a;a={r:e.r*t,g:e.g*t,b:e.b*t,a:t}}else 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=Kb,e.storeOp=Yb}(h||l)&&(o=t.depthStencilAttachment)}else{if(h=i.depth,l=i.stencil,e)for(const e of i.textures){const t=this.get(e),s=t.texture.createView();let i,r;void 0!==t.msaaTexture?(i=t.msaaTexture.createView(),r=s):(i=s,r=void 0),u.push({view:i,resolveTarget:r,clearValue:a,loadOp:Kb,storeOp:Yb})}if(h||l){o={view:this.get(i.depthTexture).texture.createView()}}}h&&(t?(o.depthLoadOp=Kb,o.depthClearValue=n.getClearDepth(),o.depthStoreOp=Yb):(o.depthLoadOp=Xb,o.depthStoreOp=Yb)),l&&(s?(o.stencilLoadOp=Kb,o.stencilClearValue=n.getClearStencil(),o.stencilStoreOp=Yb):(o.stencilLoadOp=Xb,o.stencilStoreOp=Yb));const c=r.createCommandEncoder({});c.beginRenderPass({colorAttachments:u,depthStencilAttachment:o}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={};this.initTimestampQuery(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder(),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.prepareTimestampBuffer(e,t.cmdEncoderGPU),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=e.getBindings(),o=this.get(i),a=this.get(r).pipeline,h=o.currentSets,l=o.currentPass,u=e.getDrawParameters();if(null===u)return;h.pipeline!==a&&(l.setPipeline(a),h.pipeline=a);const c=h.bindingGroups;for(let e=0,t=n.length;e<t;e++){const t=n[e],s=this.get(t);c[t.index]!==t.id&&(l.setBindGroup(t.index,s.group),c[t.index]=t.id)}const d=e.getIndex(),p=null!==d;if(!0===p&&h.index!==d){const e=this.get(d).buffer,t=d.array instanceof Uint16Array?tx:sx;l.setIndexBuffer(e,t),h.index=d}const m=e.getVertexBuffers();for(let e=0,t=m.length;e<t;e++){const t=m[e];if(h.attributes[e]!==t){const s=this.get(t).buffer;l.setVertexBuffer(e,s),h.attributes[e]=t}}if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(l.endOcclusionQuery(),o.occlusionQueryIndex++),!0===s.occlusionTest&&(l.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=s),o.lastOcclusionObject=s)}if(!0===s.isBatchedMesh){const e=s._multiDrawStarts,t=s._multiDrawCounts,i=s._multiDrawCount,r=s._multiDrawInstances,n=p?d.array.BYTES_PER_ELEMENT:1;for(let s=0;s<i;s++){const i=r?r[s]:1,o=i>1?0:s;l.drawIndexed(t[s],i,e[s]/n,0,o)}}else if(!0===p){const{vertexCount:i,instanceCount:r,firstVertex:n}=u,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;l.drawIndexedIndirect(e,0)}else l.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=u,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;l.drawIndirect(e,0)}else l.draw(i,r,n,0);t.update(s,i,r)}}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)}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=this.get(e);if(!s.timeStampQuerySet){const i=e.isComputeNode?"compute":"render",r=this.device.createQuerySet({type:"timestamp",count:2,label:`timestamp_${i}_${e.id}`}),n={querySet:r,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1};Object.assign(t,{timestampWrites:n}),s.timeStampQuerySet=r}}prepareTimestampBuffer(e,t){if(!this.trackTimestamp)return;const s=this.get(e),i=2*BigInt64Array.BYTES_PER_ELEMENT;void 0===s.currentTimestampQueryBuffers&&(s.currentTimestampQueryBuffers={resolveBuffer:this.device.createBuffer({label:"timestamp resolve buffer",size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),resultBuffer:this.device.createBuffer({label:"timestamp result buffer",size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})});const{resolveBuffer:r,resultBuffer:n}=s.currentTimestampQueryBuffers;t.resolveQuerySet(s.timeStampQuerySet,0,2,r,0),"unmapped"===n.mapState&&t.copyBufferToBuffer(r,0,n,0,i)}async resolveTimestampAsync(e,t="render"){if(!this.trackTimestamp)return;const s=this.get(e);if(void 0===s.currentTimestampQueryBuffers)return;const{resultBuffer:i}=s.currentTimestampQueryBuffers;await this.device.queue.onSubmittedWorkDone(),"unmapped"===i.mapState&&i.mapAsync(GPUMapMode.READ).then((()=>{const e=new BigUint64Array(i.getMappedRange()),s=Number(e[1]-e[0])/1e6;this.renderer.info.updateTimestamp(t,s),i.unmap()}))}createNodeBuilder(e,t){return new C_(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage}),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){let n=0,o=0,a=0,h=0,l=0,u=0,c=e.image.width,d=e.image.height;null!==s&&(h=s.x,l=s.y,u=s.z||0,c=s.width,d=s.height),null!==i&&(n=i.x,o=i.y,a=i.z||0);const p=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),m=this.get(e).texture,g=this.get(t).texture;p.copyTextureToTexture({texture:m,mipLevel:r,origin:{x:h,y:l,z:u}},{texture:g,mipLevel:r,origin:{x:n,y:o,z:a}},[c,d,1]),this.device.queue.submit([p.finish()])}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=Xb;if(t.depth&&(e.depthStencilAttachment.depthLoadOp=Xb),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=Xb),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 L_ extends fr{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 k_ extends ky{constructor(){super(),this.addMaterial(Rd,"MeshPhongMaterial"),this.addMaterial(Kp,"MeshStandardMaterial"),this.addMaterial(Qp,"MeshPhysicalMaterial"),this.addMaterial(sm,"MeshToonMaterial"),this.addMaterial(vd,"MeshBasicMaterial"),this.addMaterial(Ed,"MeshLambertMaterial"),this.addMaterial(ad,"MeshNormalMaterial"),this.addMaterial(om,"MeshMatcapMaterial"),this.addMaterial(id,"LineBasicMaterial"),this.addMaterial(nd,"LineDashedMaterial"),this.addMaterial(hm,"PointsMaterial"),this.addMaterial(dm,"SpriteMaterial"),this.addMaterial(gm,"ShadowMaterial"),this.addLight(gf,vr),this.addLight(fy,wr),this.addLight(_y,Nr),this.addLight(vy,fr),this.addLight(Sy,Mr),this.addLight(wy,ur),this.addLight(My,Er),this.addLight(Ty,L_),this.addToneMapping(fg,1),this.addToneMapping(yg,2),this.addToneMapping(bg,3),this.addToneMapping(_g,4),this.addToneMapping(wg,6),this.addToneMapping(Mg,7)}}class z_ extends Yy{constructor(e={}){let t;e.forceWebGL?t=Ib:(t=O_,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Ib(e)));super(new t(e),e),this.library=new k_,this.isWebGPURenderer=!0}}const G_={type:"change"},V_={type:"start"},j_={type:"end"},H_=1e-6,W_=-1,$_=0,q_=1,Y_=2,X_=3,K_=4,Z_=new e.Vector2,Q_=new e.Vector2,J_=new e.Vector3,ev=new e.Vector3,tv=new e.Vector3,sv=new e.Quaternion,iv=new e.Vector3,rv=new e.Vector3,nv=new e.Vector3,ov=new e.Vector3;class av extends e.Controls{constructor(t,s=null){super(t,s),this.enabled=!0,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.state=W_,this.keyState=W_,this.target=new e.Vector3,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=lv.bind(this),this._onPointerDown=hv.bind(this),this._onPointerUp=uv.bind(this),this._onPointerCancel=cv.bind(this),this._onContextMenu=bv.bind(this),this._onMouseWheel=yv.bind(this),this._onKeyDown=pv.bind(this),this._onKeyUp=dv.bind(this),this._onTouchStart=xv.bind(this),this._onTouchMove=_v.bind(this),this._onTouchEnd=vv.bind(this),this._onMouseDown=mv.bind(this),this._onMouseMove=gv.bind(this),this._onMouseUp=fv.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(),this.handleResize()),this.update()}connect(){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)>H_&&(this.dispatchEvent(G_),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>H_||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(G_),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(G_),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(Q_.copy(this._panEnd).sub(this._panStart),Q_.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;Q_.x*=e,Q_.y*=t}Q_.multiplyScalar(this._eye.length()*this.panSpeed),ev.copy(this._eye).cross(this.object.up).setLength(Q_.x),ev.add(J_.copy(this.object.up).setLength(Q_.y)),this.object.position.add(ev),this.target.add(ev),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(Q_.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){ov.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=ov.length();e?(this._eye.copy(this.object.position).sub(this.target),iv.copy(this._eye).normalize(),rv.copy(this.object.up).normalize(),nv.crossVectors(rv,iv).normalize(),rv.setLength(this._moveCurr.y-this._movePrev.y),nv.setLength(this._moveCurr.x-this._movePrev.x),ov.copy(rv.add(nv)),tv.crossVectors(ov,this._eye).normalize(),e*=this.rotateSpeed,sv.setFromAxisAngle(tv,e),this._eye.applyQuaternion(sv),this.object.up.applyQuaternion(sv),this._lastAxis.copy(tv),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),sv.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(sv),this.object.up.applyQuaternion(sv)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===K_?(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 Z_.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),Z_}_getMouseOnCircle(e,t){return Z_.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),Z_}_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 hv(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 lv(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function uv(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 cv(e){this._removePointer(e)}function dv(){!1!==this.enabled&&(this.keyState=W_,window.addEventListener("keydown",this._onKeyDown))}function pv(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===W_&&(e.code!==this.keys[$_]||this.noRotate?e.code!==this.keys[q_]||this.noZoom?e.code!==this.keys[Y_]||this.noPan||(this.keyState=Y_):this.keyState=q_:this.keyState=$_))}function mv(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=q_;break;case e.MOUSE.ROTATE:this.state=$_;break;case e.MOUSE.PAN:this.state=Y_;break;default:this.state=W_}const i=this.keyState!==W_?this.keyState:this.state;i!==$_||this.noRotate?i!==q_||this.noZoom?i!==Y_||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(V_)}function gv(e){const t=this.keyState!==W_?this.keyState:this.state;t!==$_||this.noRotate?t!==q_||this.noZoom?t!==Y_||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 fv(){this.state=W_,this.dispatchEvent(j_)}function yv(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(V_),this.dispatchEvent(j_)}}function bv(e){!1!==this.enabled&&e.preventDefault()}function xv(e){if(this._trackPointer(e),1===this._pointers.length)this.state=X_,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=K_;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(V_)}function _v(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 vv(e){switch(this._pointers.length){case 0:this.state=W_;break;case 1:this.state=X_,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=K_;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(j_)}const Tv={type:"change"},Sv={type:"start"},wv={type:"end"},Mv=new e.Ray,Nv=new e.Plane,Av=Math.cos(70*e.MathUtils.DEG2RAD),Ev=new e.Vector3,Cv=2*Math.PI,Rv=-1,Pv=0,Bv=1,Fv=2,Iv=3,Uv=4,Dv=5,Ov=6,Lv=1e-6;class kv extends e.Controls{constructor(t,s=null){super(t,s),this.state=Rv,this.enabled=!0,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.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=Gv.bind(this),this._onPointerDown=zv.bind(this),this._onPointerUp=Vv.bind(this),this._onContextMenu=Xv.bind(this),this._onMouseWheel=Wv.bind(this),this._onKeyDown=$v.bind(this),this._onTouchStart=qv.bind(this),this._onTouchMove=Yv.bind(this),this._onMouseDown=jv.bind(this),this._onMouseMove=Hv.bind(this),this._interceptControlDown=Kv.bind(this),this._interceptControlUp=Zv.bind(this),null!==this.domElement&&this.connect(),this.update()}connect(){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(Tv),this.update(),this.state=Rv}update(t=null){const s=this.object.position;Ev.copy(s).sub(this.target),Ev.applyQuaternion(this._quat),this._spherical.setFromVector3(Ev),this.autoRotate&&this.state===Rv&&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+=Cv:i>Math.PI&&(i-=Cv),r<-Math.PI?r+=Cv:r>Math.PI&&(r-=Cv),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(Ev.setFromSpherical(this._spherical),Ev.applyQuaternion(this._quatInverse),s.copy(this.target).add(Ev),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=Ev.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=Ev.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):(Mv.origin.copy(this.object.position),Mv.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Mv.direction))<Av?this.object.lookAt(this.target):(Nv.setFromNormalAndCoplanarPoint(this.object.up,this.target),Mv.intersectPlane(Nv,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)>Lv||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Lv||this._lastTargetPosition.distanceToSquared(this.target)>Lv)&&(this.dispatchEvent(Tv),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?Cv/60*this.autoRotateSpeed*e:Cv/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){Ev.setFromMatrixColumn(t,0),Ev.multiplyScalar(-e),this._panOffset.add(Ev)}_panUp(e,t){!0===this.screenSpacePanning?Ev.setFromMatrixColumn(t,1):(Ev.setFromMatrixColumn(t,0),Ev.crossVectors(this.object.up,Ev)),Ev.multiplyScalar(e),this._panOffset.add(Ev)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Ev.copy(i).sub(this.target);let r=Ev.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(Cv*this._rotateDelta.x/t.clientHeight),this._rotateUp(Cv*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(Cv*this.rotateSpeed/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(-Cv*this.rotateSpeed/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(Cv*this.rotateSpeed/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(-Cv*this.rotateSpeed/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(Cv*this._rotateDelta.x/t.clientHeight),this._rotateUp(Cv*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 zv(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 Gv(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function Vv(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(wv),this.state=Rv;break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function jv(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=Bv;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=Fv}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=Pv}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=Pv}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=Fv}break;default:this.state=Rv}this.state!==Rv&&this.dispatchEvent(Sv)}function Hv(e){switch(this.state){case Pv:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case Bv:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case Fv:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function Wv(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===Rv&&(e.preventDefault(),this.dispatchEvent(Sv),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(wv))}function $v(e){!1!==this.enabled&&this._handleKeyDown(e)}function qv(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=Iv;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=Uv;break;default:this.state=Rv}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=Dv;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=Ov;break;default:this.state=Rv}break;default:this.state=Rv}this.state!==Rv&&this.dispatchEvent(Sv)}function Yv(e){switch(this._trackPointer(e),this.state){case Iv:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case Uv:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case Dv:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case Ov:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Rv}}function Xv(e){!1!==this.enabled&&e.preventDefault()}function Kv(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function Zv(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const Qv={type:"change"},Jv=1e-6,eT=new e.Quaternion;class tT 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=sT.bind(this),this._onKeyUp=iT.bind(this),this._onPointerMove=nT.bind(this),this._onPointerDown=rT.bind(this),this._onPointerUp=oT.bind(this),this._onPointerCancel=aT.bind(this),this._onContextMenu=hT.bind(this),null!==s&&this.connect()}connect(){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),eT.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(eT),(this._lastPosition.distanceToSquared(t.position)>Jv||8*(1-this._lastQuaternion.dot(t.quaternion))>Jv)&&(this.dispatchEvent(Qv),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 sT(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 iT(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 rT(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 nT(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 oT(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 aT(){!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 hT(e){!1!==this.enabled&&e.preventDefault()}const lT={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 uT{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 cT=new e.OrthographicCamera(-1,1,1,-1,0,1);class dT 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 pT=new dT;class mT{constructor(t){this._mesh=new e.Mesh(pT,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,cT)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class gT extends uT{constructor(t,s){super(),this.textureID=void 0!==s?s:"tDiffuse",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 mT(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 fT extends uT{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 yT extends uT{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class bT{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 gT(lT),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!==fT&&(i instanceof fT?s=!0:i instanceof yT&&(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 xT extends uT{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 _T(){return _T=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},_T.apply(null,arguments)}function vT(e,t){return vT=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},vT(e,t)}function TT(e){return TT=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},TT(e)}function ST(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ST=function(){return!!e})()}function wT(e){var t="function"==typeof Map?new Map:void 0;return wT=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(ST())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&vT(r,s.prototype),r}(e,arguments,TT(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),vT(s,e)},wT(e)}var MT={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 NT(){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 AT=function(e){var t,s;function i(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,NT.apply(void 0,[MT[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 s=e,(t=i).prototype=Object.create(s.prototype),t.prototype.constructor=t,vT(t,s),i}(wT(Error));function ET(e){return Math.round(255*e)}function CT(e,t,s){return ET(e)+","+ET(t)+","+ET(s)}function RT(e,t,s,i){if(void 0===i&&(i=CT),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 PT={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 BT=/^#[a-fA-F0-9]{6}$/,FT=/^#[a-fA-F0-9]{8}$/,IT=/^#[a-fA-F0-9]{3}$/,UT=/^#[a-fA-F0-9]{4}$/,DT=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,OT=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,LT=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,kT=/^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 zT(e){if("string"!=typeof e)throw new AT(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return PT[t]?"#"+PT[t]:e}(e);if(t.match(BT))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(FT)){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(IT))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(UT)){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=DT.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=OT.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=LT.exec(t);if(o){var a="rgb("+RT(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",h=DT.exec(a);if(!h)throw new AT(4,t,a);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var l=kT.exec(t.substring(0,50));if(l){var u="rgb("+RT(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",c=DT.exec(u);if(!c)throw new AT(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 AT(5)}function GT(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}}(zT(e))}var VT=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 jT(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function HT(e){return jT(Math.round(255*e))}function WT(e,t,s){return VT("#"+HT(e)+HT(t)+HT(s))}function $T(e,t,s){return RT(e,t,s,WT)}function qT(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return VT("#"+jT(e)+jT(t)+jT(s));if("object"==typeof e&&void 0===t&&void 0===s)return VT("#"+jT(e.red)+jT(e.green)+jT(e.blue));throw new AT(6)}function YT(e,t,s,i){if("string"==typeof e&&"number"==typeof t){var r=zT(e);return"rgba("+r.red+","+r.green+","+r.blue+","+t+")"}if("number"==typeof e&&"number"==typeof t&&"number"==typeof s&&"number"==typeof i)return i>=1?qT(e,t,s):"rgba("+e+","+t+","+s+","+i+")";if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?qT(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new AT(7)}function XT(e){if("object"!=typeof e)throw new AT(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return YT(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 qT(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("number"==typeof e&&"number"==typeof t&&"number"==typeof s&&"number"==typeof i)return i>=1?$T(e,t,s):"rgba("+RT(e,t,s)+","+i+")";if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?$T(e.hue,e.saturation,e.lightness):"rgba("+RT(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new AT(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("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return $T(e,t,s);if("object"==typeof e&&void 0===t&&void 0===s)return $T(e.hue,e.saturation,e.lightness);throw new AT(1)}(e);throw new AT(8)}function KT(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):KT(e,t,i)}}function ZT(e){return KT(e,e.length,[])}function QT(e,t,s){return Math.max(e,Math.min(t,s))}ZT((function(e,t){if("transparent"===t)return t;var s=GT(t);return XT(_T({},s,{hue:s.hue+parseFloat(e)}))})),ZT((function(e,t){if("transparent"===t)return t;var s=GT(t);return XT(_T({},s,{lightness:QT(0,1,s.lightness-parseFloat(e))}))})),ZT((function(e,t){if("transparent"===t)return t;var s=GT(t);return XT(_T({},s,{saturation:QT(0,1,s.saturation-parseFloat(e))}))})),ZT((function(e,t){if("transparent"===t)return t;var s=GT(t);return XT(_T({},s,{lightness:QT(0,1,s.lightness+parseFloat(e))}))}));var JT=ZT((function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=zT(t),r=_T({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=zT(s),o=_T({},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 YT({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))})})),eS=JT;var tS=ZT((function(e,t){if("transparent"===t)return t;var s=zT(t);return YT(_T({},s,{alpha:QT(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))})),sS=tS;ZT((function(e,t){if("transparent"===t)return t;var s=GT(t);return XT(_T({},s,{saturation:QT(0,1,s.saturation+parseFloat(e))}))})),ZT((function(e,t){return"transparent"===t?t:XT(_T({},GT(t),{hue:parseFloat(e)}))})),ZT((function(e,t){return"transparent"===t?t:XT(_T({},GT(t),{lightness:parseFloat(e)}))})),ZT((function(e,t){return"transparent"===t?t:XT(_T({},GT(t),{saturation:parseFloat(e)}))})),ZT((function(e,t){return"transparent"===t?t:eS(parseFloat(e),"rgb(0, 0, 0)",t)})),ZT((function(e,t){return"transparent"===t?t:eS(parseFloat(e),"rgb(255, 255, 255)",t)})),ZT((function(e,t){if("transparent"===t)return t;var s=zT(t);return YT(_T({},s,{alpha:QT(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}));var iS,rS=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-rS.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*rS.Bounce.In(2*e):.5*rS.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}}}}),nS=function(){return performance.now()},oS=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=nS()),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}(),aS={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=aS.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)},Bezier:function(e,t){for(var s=0,i=e.length-1,r=Math.pow,n=aS.Utils.Bernstein,o=0;o<=i;o++)s+=r(1-t,i-o)*r(t,o)*e[o]*n(i,o);return s},CatmullRom:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=aS.Utils.CatmullRom;return e[0]===e[s]?(t<0&&(r=Math.floor(i=s*(1+t))),n(e[(r-1+s)%s],e[r],e[(r+1)%s],e[(r+2)%s],i-r)):t<0?e[0]-(n(e[0],e[0],e[1],e[1],-i)-e[0]):t>1?e[s]-(n(e[s],e[s],e[s-1],e[s-1],i-s)-e[s]):n(e[r?r-1:0],e[r],e[s<r+1?s:r+1],e[s<r+2?s:r+2],i-r)},Utils:{Linear:function(e,t,s){return(t-e)*s+e},Bernstein:function(e,t){var s=aS.Utils.Factorial;return s(e)/s(t)/s(e-t)},Factorial:(iS=[1],function(e){var t=1;if(iS[e])return iS[e];for(var s=e;s>1;s--)t*=s;return iS[e]=t,t}),CatmullRom:function(e,t,s,i,r){var n=.5*(s-e),o=.5*(i-t),a=r*r;return(2*t-2*s+n+o)*(r*a)+(-3*t+3*s-2*n-o)*a+n*r+t}}},hS=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),lS=new oS,uS=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=rS.Linear.None,this._interpolationFunction=aS.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=hS.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=lS,lS.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=nS()),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=nS()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=nS()),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=rS.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=aS.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=nS()),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}(),cS=lS;cS.getAll.bind(cS),cS.removeAll.bind(cS),cS.add.bind(cS),cS.remove.bind(cS),cS.update.bind(cS);function dS(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var pS="object"==typeof global&&global&&global.Object===Object&&global,mS="object"==typeof self&&self&&self.Object===Object&&self,gS=pS||mS||Function("return this")(),fS=function(){return gS.Date.now()},yS=/\s/;var bS=/^\s+/;function xS(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&yS.test(e.charAt(t)););return t}(e)+1).replace(bS,""):e}var _S=gS.Symbol,vS=Object.prototype,TS=vS.hasOwnProperty,SS=vS.toString,wS=_S?_S.toStringTag:void 0;var MS=Object.prototype.toString;var NS=_S?_S.toStringTag:void 0;function AS(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":NS&&NS in Object(e)?function(e){var t=TS.call(e,wS),s=e[wS];try{e[wS]=void 0;var i=!0}catch(e){}var r=SS.call(e);return i&&(t?e[wS]=s:delete e[wS]),r}(e):function(e){return MS.call(e)}(e)}var ES=/^[-+]0x[0-9a-f]+$/i,CS=/^0b[01]+$/i,RS=/^0o[0-7]+$/i,PS=parseInt;function BS(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]"==AS(e)}(e))return NaN;if(dS(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=dS(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=xS(e);var s=CS.test(e);return s||RS.test(e)?PS(e.slice(2),s?2:8):ES.test(e)?NaN:+e}var FS=Math.max,IS=Math.min;function US(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=fS();if(m(e))return f(e);a=setTimeout(g,function(e){var s=t-(e-h);return c?IS(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=fS(),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=BS(t)||0,dS(s)&&(u=!!s.leading,n=(c="maxWait"in s)?FS(BS(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(fS())},y}function DS(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 OS(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function LS(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 DS(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)?DS(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 kS=OS((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}));var zS,GS,VS,jS,HS,WS,$S,qS,YS,XS,KS,ZS,QS,JS,ew=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,EventDispatcher:e.EventDispatcher,MOUSE:e.MOUSE,Quaternion:e.Quaternion,Spherical:e.Spherical,Clock:e.Clock},tw=(zS={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)}},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.toolTipElem&&(t.toolTipElem.innerHTML="")},triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{default:function(){return-1},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){if(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)})),e.enablePointerInteraction){var t=null;if(e.hoverDuringDrag||!e.isPointerDragging){var s=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y).filter((function(t){return e.hoverFilter(t.object)})).sort((function(t,s){return e.hoverOrderComparator(t.object,s.object)})),i=s.length?s[0]:null;t=i?i.object:null,e.intersectionPoint=i?i.point:null}t!==e.hoverObj&&(e.onHover(t,e.hoverObj),e.toolTipElem.innerHTML=t&&("function"==typeof(r=e.tooltipContent)?r:"string"==typeof r?function(e){return e[r]}:function(e){return r})(t)||"",e.hoverObj=t)}e.tweenGroup.update()}var r;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 uS(a).to(n,i).easing(rS.Quadratic.Out).onUpdate(l).start()),e.tweenGroup.add(new uS(h).to(o,i/3).easing(rS.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 ew.Vector3(t.x,t.y,t.z);e.controls.target?e.controls.target=s:r.lookAt(s)}function c(){return Object.assign(new ew.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 ew.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 ew.Box3(new ew.Vector3(0,0,0),new ew.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 ew.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 ew.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new ew.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new ew.Vector3))},intersectingObjects:function(e,t,s){var i=new ew.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new ew.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,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 ew.Scene,camera:new ew.PerspectiveCamera,clock:new ew.Clock,tweenGroup:new oS}},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.toolTipElem=document.createElement("div"),t.toolTipElem.classList.add("scene-tooltip"),t.container.appendChild(t.toolTipElem),t.pointerPos=new ew.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,t.toolTipElem.style.top="".concat(t.pointerPos.y,"px"),t.toolTipElem.style.left="".concat(t.pointerPos.x,"px"),t.toolTipElem.style.transform="translate(-".concat(t.pointerPos.x/t.width*100,"%, ").concat(t.height-t.pointerPos.y<100?"calc(-100% - 8px)":"21px",")")}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.intersectionPoint),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersectionPoint)}))}),{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",(function(e){t.onRightClick&&e.preventDefault()})),t.renderer=new(a?z_:ew.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 bT(t.renderer),t.postProcessingComposer.addPass(new xT(t.scene,t.camera)),t.controls=new{trackball:av,orbit:kv,fly:tT}[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 ew.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"))&&(e.container.style.width="".concat(e.width,"px"),e.container.style.height="".concat(e.height,"px"),[e.renderer,e.postProcessingComposer].concat(r(e.extraRenderers)).forEach((function(t){return t.setSize(e.width,e.height)})),e.camera.aspect=e.width/e.height,e.camera.updateProjectionMatrix()),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 ew.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var s=zT(e.backgroundColor).alpha;void 0===s&&(s=1),e.renderer.setClearColor(new ew.Color(sS(1,e.backgroundColor)),s)}function i(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new ew.TextureLoader).load(e.backgroundImageUrl,(function(t){t.colorSpace=ew.SRGBColorSpace,e.skysphere.material=new ew.MeshBasicMaterial({map:t,side:ew.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&i()})):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&i())),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)})))}},GS=zS.stateInit,VS=void 0===GS?function(){return{}}:GS,jS=zS.props,HS=void 0===jS?{}:jS,WS=zS.methods,$S=void 0===WS?{}:WS,qS=zS.aliases,YS=void 0===qS?{}:qS,XS=zS.init,KS=void 0===XS?function(){}:XS,ZS=zS.update,QS=void 0===ZS?function(){}:ZS,JS=Object.keys(HS).map((function(e){return new kS(e,HS[e])})),function e(){for(var t=arguments.length,s=new Array(t),i=0;i<t;i++)s[i]=arguments[i];var r=!!(this instanceof e?this.constructor:void 0),n=r?s.shift():void 0,o=s[0],a=void 0===o?{}:o,h=Object.assign({},VS instanceof Function?VS(a):VS,{initialised:!1}),l={};function u(e){return c(e,a),d(),u}var c=function(e,t){KS.call(u,e,h,t),h.initialised=!0},d=US((function(){h.initialised&&(QS.call(u,h,l),l={})}),1);return JS.forEach((function(e){u[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=h[t];if(!arguments.length)return s;var r=void 0===e?a:e;return h[t]=r,n.call(u,r,h,s),!l.hasOwnProperty(t)&&(l[t]=s),i&&d(),u}}(e)})),Object.keys($S).forEach((function(e){u[e]=function(){for(var t,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];return(t=$S[e]).call.apply(t,[u,h].concat(i))}})),Object.entries(YS).forEach((function(e){var t=LS(e,2),s=t[0],i=t[1];return u[s]=u[i]})),u.resetProps=function(){return JS.forEach((function(e){u[e.name](e.defaultVal)})),u},u.resetProps(),h._rerender=d,r&&n&&u(n),u});return tw}));
1
+ // Version 1.33.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||"default");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 bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n}\n\n.scene-tooltip {\n top: 0;\n color: lavender;\n font-size: 15px;\n background: rgba(0,0,0,0.5);\n padding: 2px 5px;\n border-radius: 3px;\n}\n\n.scene-nav-info, .scene-tooltip {\n position: absolute;\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="172",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,S=303,w=304,M=1e3,N=1001,A=1002,E=1003,C=1004,R=1005,P=1006,B=1007,F=1008,I=1009,U=1010,D=1011,O=1012,L=1013,k=1014,z=1015,G=1016,V=1020,j=1022,H=1023,W=1026,$=1027,q=1028,Y=1029,X=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",Se="srgb",we=7680,Me=512,Ne=513,Ae=514,Ee=515,Ce=516,Re=517,Pe=518,Be=519,Fe=35044,Ie=35048,Ue=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){if(void 0===this._listeners)return!1;const s=this._listeners;return void 0!==s[e]&&-1!==s[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const s=this._listeners[e];if(void 0!==s){const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const s=t.slice(0);for(let t=0,i=s.length;t<i;t++)s[t].call(this,e);e.target=null}}}const Le=["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 ke=1234567;const ze=Math.PI/180,Ge=180/Math.PI;function Ve(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Le[255&e]+Le[e>>8&255]+Le[e>>16&255]+Le[e>>24&255]+"-"+Le[255&t]+Le[t>>8&255]+"-"+Le[t>>16&15|64]+Le[t>>24&255]+"-"+Le[63&s|128]+Le[s>>8&255]+"-"+Le[s>>16&255]+Le[s>>24&255]+Le[255&i]+Le[i>>8&255]+Le[i>>16&255]+Le[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 Ye={DEG2RAD:ze,RAD2DEG:Ge,generateUUID:Ve,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&&(ke=e);let t=ke+=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*Ge},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 Xe{constructor(e=0,t=0){Xe.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){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const Je={};const et=(new Ke).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),tt=(new Ke).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function st(){const e={enabled:!0,workingColorSpace:ve,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Se&&(e.r=rt(e.r),e.g=rt(e.g),e.b=rt(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===Se&&(e.r=nt(e.r),e.g=nt(e.g),e.b=nt(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:et,fromXYZ:tt,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:_e},outputColorSpaceConfig:{drawingBufferColorSpace:_e}},[_e]:{primaries:t,whitePoint:i,transfer:Se,toXYZ:et,fromXYZ:tt,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:_e}}}),e}const it=st();function rt(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function nt(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let ot;class at{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===ot&&(ot=Ze("canvas")),ot.width=e.width,ot.height=e.height;const s=ot.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=ot}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Ze("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*rt(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*rt(t[e]/255)):t[e]=rt(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 ht=0;class lt{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ht++}),this.uuid=Ve(),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(ut(i[t].image)):e.push(ut(i[t]))}else e=ut(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function ut(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?at.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 ct=0;class dt extends Oe{constructor(e=dt.DEFAULT_IMAGE,t=dt.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,o=1023,a=1009,h=dt.DEFAULT_ANISOTROPY,l=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:ct++}),this.uuid=Ve(),this.name="",this.source=new lt(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 Xe(0,0),this.repeat=new Xe(1,1),this.center=new Xe(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 A: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 A: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++}}dt.DEFAULT_IMAGE=null,dt.DEFAULT_MAPPING=300,dt.DEFAULT_ANISOTROPY=1;class pt{constructor(e=0,t=0,s=0,i=1){pt.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 mt extends Oe{constructor(e=1,t=1,s={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new pt(0,0,e,t),this.scissorTest=!1,this.viewport=new pt(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 dt(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}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 t=Object.assign({},e.texture.image);return this.texture.source=new lt(t),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 gt extends mt{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class ft extends dt{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=E,this.minFilter=E,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 yt{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 bt{constructor(e=0,t=0,s=0){bt.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(_t.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_t.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 xt.copy(this).projectOnVector(e),this.sub(xt)}reflect(e){return this.sub(xt.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 xt=new bt,_t=new yt;class vt{constructor(e=new bt(1/0,1/0,1/0),t=new bt(-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(St.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(St.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=St.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,St):St.fromBufferAttribute(i,t),St.applyMatrix4(e.matrixWorld),this.expandByPoint(St);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),wt.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),wt.copy(s.boundingBox)),wt.applyMatrix4(e.matrixWorld),this.union(wt)}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,St),St.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(Pt),Bt.subVectors(this.max,Pt),Mt.subVectors(e.a,Pt),Nt.subVectors(e.b,Pt),At.subVectors(e.c,Pt),Et.subVectors(Nt,Mt),Ct.subVectors(At,Nt),Rt.subVectors(Mt,At);let t=[0,-Et.z,Et.y,0,-Ct.z,Ct.y,0,-Rt.z,Rt.y,Et.z,0,-Et.x,Ct.z,0,-Ct.x,Rt.z,0,-Rt.x,-Et.y,Et.x,0,-Ct.y,Ct.x,0,-Rt.y,Rt.x,0];return!!Ut(t,Mt,Nt,At,Bt)&&(t=[1,0,0,0,1,0,0,0,1],!!Ut(t,Mt,Nt,At,Bt)&&(Ft.crossVectors(Et,Ct),t=[Ft.x,Ft.y,Ft.z],Ut(t,Mt,Nt,At,Bt)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,St).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(St).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()||(Tt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Tt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Tt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Tt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Tt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Tt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Tt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Tt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Tt)),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 Tt=[new bt,new bt,new bt,new bt,new bt,new bt,new bt,new bt],St=new bt,wt=new vt,Mt=new bt,Nt=new bt,At=new bt,Et=new bt,Ct=new bt,Rt=new bt,Pt=new bt,Bt=new bt,Ft=new bt,It=new bt;function Ut(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){It.fromArray(e,n);const o=r.x*Math.abs(It.x)+r.y*Math.abs(It.y)+r.z*Math.abs(It.z),a=t.dot(It),h=s.dot(It),l=i.dot(It);if(Math.max(-Math.max(a,h,l),Math.min(a,h,l))>o)return!1}return!0}const Dt=new vt,Ot=new bt,Lt=new bt;class kt{constructor(e=new bt,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):Dt.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;Ot.subVectors(e,this.center);const t=Ot.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Ot,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):(Lt.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ot.copy(e.center).add(Lt)),this.expandByPoint(Ot.copy(e.center).sub(Lt))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const zt=new bt,Gt=new bt,Vt=new bt,jt=new bt,Ht=new bt,Wt=new bt,$t=new bt;class qt{constructor(e=new bt,t=new bt(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,zt)),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=zt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(zt.copy(this.origin).addScaledVector(this.direction,t),zt.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Gt.copy(e).add(t).multiplyScalar(.5),Vt.copy(t).sub(e).normalize(),jt.copy(this.origin).sub(Gt);const r=.5*e.distanceTo(t),n=-this.direction.dot(Vt),o=jt.dot(this.direction),a=-jt.dot(Vt),h=jt.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(Gt).addScaledVector(Vt,c),d}intersectSphere(e,t){zt.subVectors(e.center,this.origin);const s=zt.dot(this.direction),i=zt.dot(zt)-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,zt)}intersectTriangle(e,t,s,i,r){Ht.subVectors(t,e),Wt.subVectors(s,e),$t.crossVectors(Ht,Wt);let n,o=this.direction.dot($t);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}jt.subVectors(this.origin,e);const a=n*this.direction.dot(Wt.crossVectors(jt,Wt));if(a<0)return null;const h=n*this.direction.dot(Ht.cross(jt));if(h<0)return null;if(a+h>o)return null;const l=-n*jt.dot($t);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 Yt{constructor(e,t,s,i,r,n,o,a,h,l,u,c,d,p,m,g){Yt.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 Yt).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/Xt.setFromMatrixColumn(e,0).length(),r=1/Xt.setFromMatrixColumn(e,1).length(),n=1/Xt.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(Qt,e,Zt)}lookAt(e,t,s){const i=this.elements;return ts.subVectors(e,t),0===ts.lengthSq()&&(ts.z=1),ts.normalize(),Jt.crossVectors(s,ts),0===Jt.lengthSq()&&(1===Math.abs(s.z)?ts.x+=1e-4:ts.z+=1e-4,ts.normalize(),Jt.crossVectors(s,ts)),Jt.normalize(),es.crossVectors(ts,Jt),i[0]=Jt.x,i[4]=es.x,i[8]=ts.x,i[1]=Jt.y,i[5]=es.y,i[9]=ts.y,i[2]=Jt.z,i[6]=es.z,i[10]=ts.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],S=i[8],w=i[12],M=i[1],N=i[5],A=i[9],E=i[13],C=i[2],R=i[6],P=i[10],B=i[14],F=i[3],I=i[7],U=i[11],D=i[15];return r[0]=n*v+o*M+a*C+h*F,r[4]=n*T+o*N+a*R+h*I,r[8]=n*S+o*A+a*P+h*U,r[12]=n*w+o*E+a*B+h*D,r[1]=l*v+u*M+c*C+d*F,r[5]=l*T+u*N+c*R+d*I,r[9]=l*S+u*A+c*P+d*U,r[13]=l*w+u*E+c*B+d*D,r[2]=p*v+m*M+g*C+f*F,r[6]=p*T+m*N+g*R+f*I,r[10]=p*S+m*A+g*P+f*U,r[14]=p*w+m*E+g*B+f*D,r[3]=y*v+b*M+x*C+_*F,r[7]=y*T+b*N+x*R+_*I,r[11]=y*S+b*A+x*P+_*U,r[15]=y*w+b*E+x*B+_*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=Xt.set(i[0],i[1],i[2]).length();const n=Xt.set(i[4],i[5],i[6]).length(),o=Xt.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],Kt.copy(this);const a=1/r,h=1/n,l=1/o;return Kt.elements[0]*=a,Kt.elements[1]*=a,Kt.elements[2]*=a,Kt.elements[4]*=h,Kt.elements[5]*=h,Kt.elements[6]*=h,Kt.elements[8]*=l,Kt.elements[9]*=l,Kt.elements[10]*=l,t.setFromRotationMatrix(Kt),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===Ue)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===Ue)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 Xt=new bt,Kt=new Yt,Qt=new bt(0,0,0),Zt=new bt(1,1,1),Jt=new bt,es=new bt,ts=new bt,ss=new Yt,is=new yt;class rs{constructor(e=0,t=0,s=0,i=rs.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 ss.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ss,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return is.setFromEuler(this),this.setFromQuaternion(is,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}}rs.DEFAULT_ORDER="XYZ";class ns{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 os=0;const as=new bt,hs=new yt,ls=new Yt,us=new bt,cs=new bt,ds=new bt,ps=new yt,ms=new bt(1,0,0),gs=new bt(0,1,0),fs=new bt(0,0,1),ys={type:"added"},bs={type:"removed"},xs={type:"childadded",child:null},_s={type:"childremoved",child:null};class vs extends Oe{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:os++}),this.uuid=Ve(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=vs.DEFAULT_UP.clone();const e=new bt,t=new rs,s=new yt,i=new bt(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 Yt},normalMatrix:{value:new Ke}}),this.matrix=new Yt,this.matrixWorld=new Yt,this.matrixAutoUpdate=vs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=vs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ns,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],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 hs.setFromAxisAngle(e,t),this.quaternion.multiply(hs),this}rotateOnWorldAxis(e,t){return hs.setFromAxisAngle(e,t),this.quaternion.premultiply(hs),this}rotateX(e){return this.rotateOnAxis(ms,e)}rotateY(e){return this.rotateOnAxis(gs,e)}rotateZ(e){return this.rotateOnAxis(fs,e)}translateOnAxis(e,t){return as.copy(e).applyQuaternion(this.quaternion),this.position.add(as.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ms,e)}translateY(e){return this.translateOnAxis(gs,e)}translateZ(e){return this.translateOnAxis(fs,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ls.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?us.copy(e):us.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),cs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ls.lookAt(cs,us,this.up):ls.lookAt(us,cs,this.up),this.quaternion.setFromRotationMatrix(ls),i&&(ls.extractRotation(i.matrixWorld),hs.setFromRotationMatrix(ls),this.quaternion.premultiply(hs.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(ys),xs.child=e,this.dispatchEvent(xs),xs.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(bs),_s.child=e,this.dispatchEvent(_s),_s.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),ls.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),ls.multiply(e.parent.matrixWorld)),e.applyMatrix4(ls),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(ys),xs.child=e,this.dispatchEvent(xs),xs.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(cs,e,ds),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(cs,ps,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}}vs.DEFAULT_UP=new bt(0,1,0),vs.DEFAULT_MATRIX_AUTO_UPDATE=!0,vs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Ts=new bt,Ss=new bt,ws=new bt,Ms=new bt,Ns=new bt,As=new bt,Es=new bt,Cs=new bt,Rs=new bt,Ps=new bt,Bs=new pt,Fs=new pt,Is=new pt;class Us{constructor(e=new bt,t=new bt,s=new bt){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Ts.subVectors(e,t),i.cross(Ts);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){Ts.subVectors(i,t),Ss.subVectors(s,t),ws.subVectors(e,t);const n=Ts.dot(Ts),o=Ts.dot(Ss),a=Ts.dot(ws),h=Ss.dot(Ss),l=Ss.dot(ws),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,Ms)&&(Ms.x>=0&&Ms.y>=0&&Ms.x+Ms.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Ms)?(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,Ms.x),a.addScaledVector(n,Ms.y),a.addScaledVector(o,Ms.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Bs.setScalar(0),Fs.setScalar(0),Is.setScalar(0),Bs.fromBufferAttribute(e,t),Fs.fromBufferAttribute(e,s),Is.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Bs,r.x),n.addScaledVector(Fs,r.y),n.addScaledVector(Is,r.z),n}static isFrontFacing(e,t,s,i){return Ts.subVectors(s,t),Ss.subVectors(e,t),Ts.cross(Ss).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 Ts.subVectors(this.c,this.b),Ss.subVectors(this.a,this.b),.5*Ts.cross(Ss).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Us.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Us.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Us.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Us.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Us.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;Ns.subVectors(i,s),As.subVectors(r,s),Cs.subVectors(e,s);const a=Ns.dot(Cs),h=As.dot(Cs);if(a<=0&&h<=0)return t.copy(s);Rs.subVectors(e,i);const l=Ns.dot(Rs),u=As.dot(Rs);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(Ns,n);Ps.subVectors(e,r);const d=Ns.dot(Ps),p=As.dot(Ps);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(As,o);const g=l*p-d*u;if(g<=0&&u-l>=0&&d-p>=0)return Es.subVectors(r,i),o=(u-l)/(u-l+(d-p)),t.copy(i).addScaledVector(Es,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(Ns,n).addScaledVector(As,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Ds={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Os={h:0,s:0,l:0},Ls={h:0,s:0,l:0};function ks(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class zs{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=_e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,it.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=it.workingColorSpace){return this.r=e,this.g=t,this.b=s,it.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=it.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=ks(r,i,e+1/3),this.g=ks(r,i,e),this.b=ks(r,i,e-1/3)}return it.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=Ds[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=rt(e.r),this.g=rt(e.g),this.b=rt(e.b),this}copyLinearToSRGB(e){return this.r=nt(e.r),this.g=nt(e.g),this.b=nt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=_e){return it.fromWorkingColorSpace(Gs.copy(this),e),65536*Math.round(je(255*Gs.r,0,255))+256*Math.round(je(255*Gs.g,0,255))+Math.round(je(255*Gs.b,0,255))}getHexString(e=_e){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=it.workingColorSpace){it.fromWorkingColorSpace(Gs.copy(this),t);const s=Gs.r,i=Gs.g,r=Gs.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=it.workingColorSpace){return it.fromWorkingColorSpace(Gs.copy(this),t),e.r=Gs.r,e.g=Gs.g,e.b=Gs.b,e}getStyle(e=_e){it.fromWorkingColorSpace(Gs.copy(this),e);const t=Gs.r,s=Gs.g,i=Gs.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(Os),this.setHSL(Os.h+e,Os.s+t,Os.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(Os),e.getHSL(Ls);const s=We(Os.h,Ls.h,t),i=We(Os.s,Ls.s,t),r=We(Os.l,Ls.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Gs=new zs;zs.NAMES=Ds;let Vs=0;class js extends Oe{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Vs++}),this.uuid=Ve(),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 zs(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=we,this.stencilZFail=we,this.stencilZPass=we,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.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!==we&&(s.stencilFail=this.stencilFail),this.stencilZFail!==we&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==we&&(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 Hs extends js{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new zs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rs,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 Ws=$s();function $s(){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 qs(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=je(e,-65504,65504),Ws.floatView[0]=e;const t=Ws.uint32View[0],s=t>>23&511;return Ws.baseTable[s]+((8388607&t)>>Ws.shiftTable[s])}function Ys(e){const t=e>>10;return Ws.uint32View[0]=Ws.mantissaTable[Ws.offsetTable[t]+(1023&e)]+Ws.exponentTable[t],Ws.floatView[0]}const Xs=new bt,Ks=new Xe;class Qs{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Fe,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++)Ks.fromBufferAttribute(this,t),Ks.applyMatrix3(e),this.setXY(t,Ks.x,Ks.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.applyMatrix3(e),this.setXYZ(t,Xs.x,Xs.y,Xs.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.applyMatrix4(e),this.setXYZ(t,Xs.x,Xs.y,Xs.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.applyNormalMatrix(e),this.setXYZ(t,Xs.x,Xs.y,Xs.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Xs.fromBufferAttribute(this,t),Xs.transformDirection(e),this.setXYZ(t,Xs.x,Xs.y,Xs.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!==Fe&&(e.usage=this.usage),e}}class Zs extends Qs{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Js extends Qs{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class ei extends Qs{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Ys(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]=qs(t),this}getY(e){let t=Ys(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]=qs(t),this}getZ(e){let t=Ys(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]=qs(t),this}getW(e){let t=Ys(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]=qs(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]=qs(t),this.array[e+1]=qs(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]=qs(t),this.array[e+1]=qs(s),this.array[e+2]=qs(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]=qs(t),this.array[e+1]=qs(s),this.array[e+2]=qs(i),this.array[e+3]=qs(r),this}}class ti extends Qs{constructor(e,t,s){super(new Float32Array(e),t,s)}}let si=0;const ii=new Yt,ri=new vs,ni=new bt,oi=new vt,ai=new vt,hi=new bt;class li extends Oe{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:si++}),this.uuid=Ve(),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(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?Js:Zs)(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 ii.makeRotationFromQuaternion(e),this.applyMatrix4(ii),this}rotateX(e){return ii.makeRotationX(e),this.applyMatrix4(ii),this}rotateY(e){return ii.makeRotationY(e),this.applyMatrix4(ii),this}rotateZ(e){return ii.makeRotationZ(e),this.applyMatrix4(ii),this}translate(e,t,s){return ii.makeTranslation(e,t,s),this.applyMatrix4(ii),this}scale(e,t,s){return ii.makeScale(e,t,s),this.applyMatrix4(ii),this}lookAt(e){return ri.lookAt(e),ri.updateMatrix(),this.applyMatrix4(ri.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ni).negate(),this.translate(ni.x,ni.y,ni.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 ti(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 vt);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 bt(-1/0,-1/0,-1/0),new bt(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];oi.setFromBufferAttribute(s),this.morphTargetsRelative?(hi.addVectors(this.boundingBox.min,oi.min),this.boundingBox.expandByPoint(hi),hi.addVectors(this.boundingBox.max,oi.max),this.boundingBox.expandByPoint(hi)):(this.boundingBox.expandByPoint(oi.min),this.boundingBox.expandByPoint(oi.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 kt);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 bt,1/0);if(e){const s=this.boundingSphere.center;if(oi.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];ai.setFromBufferAttribute(s),this.morphTargetsRelative?(hi.addVectors(oi.min,ai.min),oi.expandByPoint(hi),hi.addVectors(oi.max,ai.max),oi.expandByPoint(hi)):(oi.expandByPoint(ai.min),oi.expandByPoint(ai.max))}oi.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)hi.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(hi));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++)hi.fromBufferAttribute(n,t),o&&(ni.fromBufferAttribute(e,t),hi.add(ni)),i=Math.max(i,s.distanceToSquared(hi))}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 Qs(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),o=[],a=[];for(let e=0;e<s.count;e++)o[e]=new bt,a[e]=new bt;const h=new bt,l=new bt,u=new bt,c=new Xe,d=new Xe,p=new Xe,m=new bt,g=new bt;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 bt,x=new bt,_=new bt,v=new bt;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 Qs(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 bt,r=new bt,n=new bt,o=new bt,a=new bt,h=new bt,l=new bt,u=new bt;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++)hi.fromBufferAttribute(e,t),hi.normalize(),e.setXYZ(t,hi.x,hi.y,hi.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 Qs(n,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new li,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(t));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 ui=new Yt,ci=new qt,di=new kt,pi=new bt,mi=new bt,gi=new bt,fi=new bt,yi=new bt,bi=new bt,xi=new bt,_i=new bt;class vi extends vs{constructor(e=new li,t=new Hs){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,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){bi.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=o[s],a=r[s];0!==i&&(yi.fromBufferAttribute(a,e),n?bi.addScaledVector(yi,i):bi.addScaledVector(yi.sub(t),i))}t.add(bi)}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(),di.copy(s.boundingSphere),di.applyMatrix4(r),ci.copy(e.ray).recast(e.near),!1===di.containsPoint(ci.origin)){if(null===ci.intersectSphere(di,pi))return;if(ci.origin.distanceToSquared(pi)>(e.far-e.near)**2)return}ui.copy(r).invert(),ci.copy(e.ray).applyMatrix4(ui),null!==s.boundingBox&&!1===ci.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,ci)}}_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=Ti(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=Ti(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=Ti(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=Ti(this,n,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Ti(e,t,s,i,r,n,o,a,h,l){e.getVertexPosition(a,mi),e.getVertexPosition(h,gi),e.getVertexPosition(l,fi);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;_i.copy(a),_i.applyMatrix4(e.matrixWorld);const l=s.ray.origin.distanceTo(_i);return l<s.near||l>s.far?null:{distance:l,point:_i.clone(),object:e}}(e,t,s,i,mi,gi,fi,xi);if(u){const e=new bt;Us.getBarycoord(xi,mi,gi,fi,e),r&&(u.uv=Us.getInterpolatedAttribute(r,a,h,l,e,new Xe)),n&&(u.uv1=Us.getInterpolatedAttribute(n,a,h,l,e,new Xe)),o&&(u.normal=Us.getInterpolatedAttribute(o,a,h,l,e,new bt),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:a,b:h,c:l,normal:new bt,materialIndex:0};Us.getNormal(mi,gi,fi,t.normal),u.face=t,u.barycoord=e}return u}class Si extends li{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,S=g+1,w=f+1;let M=0,N=0;const A=new bt;for(let n=0;n<w;n++){const o=n*x-v;for(let a=0;a<S;a++){const c=a*b-_;A[e]=c*i,A[t]=o*r,A[s]=T,h.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[s]=m>0?1:-1,l.push(A.x,A.y,A.z),u.push(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+S*e,i=c+t+S*(e+1),r=c+(t+1)+S*(e+1),n=c+(t+1)+S*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 ti(h,3)),this.setAttribute("normal",new ti(l,3)),this.setAttribute("uv",new ti(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Si(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function wi(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 Mi extends js{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=wi(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 Ni extends vs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Yt,this.projectionMatrix=new Yt,this.projectionMatrixInverse=new Yt,this.coordinateSystem=Ue}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 Ai=new bt,Ei=new Xe,Ci=new Xe;class Ri extends Ni{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*Ge*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*ze*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Ge*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){Ai.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ai.x,Ai.y).multiplyScalar(-e/Ai.z),Ai.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Ai.x,Ai.y).multiplyScalar(-e/Ai.z)}getViewSize(e,t){return this.getViewBounds(e,Ei,Ci),t.subVectors(Ci,Ei)}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 Pi=-90;class Bi extends vs{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ri(Pi,1,e,t);i.layers=this.layers,this.add(i);const r=new Ri(Pi,1,e,t);r.layers=this.layers,this.add(r);const n=new Ri(Pi,1,e,t);n.layers=this.layers,this.add(n);const o=new Ri(Pi,1,e,t);o.layers=this.layers,this.add(o);const a=new Ri(Pi,1,e,t);a.layers=this.layers,this.add(a);const h=new Ri(Pi,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===Ue)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 Fi extends dt{constructor(e,t,s,i,r,n,o,a,h,l){super(e=void 0!==e?e:[],t=void 0!==t?t:v,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 Ii extends gt{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 Fi(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 Si(5,5,5),r=new Mi({name:"CubemapFromEquirect",uniforms:wi(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new vi(i,r),o=t.minFilter;t.minFilter===F&&(t.minFilter=P);return new Bi(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t,s,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Ui extends vs{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 rs,this.environmentIntensity=1,this.environmentRotation=new rs,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 Di{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Fe,this.updateRanges=[],this.version=0,this.uuid=Ve()}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=Ve()),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=Ve()),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 Oi=new bt;class Li{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++)Oi.fromBufferAttribute(this,t),Oi.applyMatrix4(e),this.setXYZ(t,Oi.x,Oi.y,Oi.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Oi.fromBufferAttribute(this,t),Oi.applyNormalMatrix(e),this.setXYZ(t,Oi.x,Oi.y,Oi.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Oi.fromBufferAttribute(this,t),Oi.transformDirection(e),this.setXYZ(t,Oi.x,Oi.y,Oi.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 Qs(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 Li(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 ki extends js{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new zs(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class zi extends dt{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 Gi extends Qs{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 Vi=new bt,ji=new bt,Hi=new Ke;class Wi{constructor(e=new bt(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=Vi.subVectors(s,t).cross(ji.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(Vi),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||Hi.getNormalMatrix(e),i=this.coplanarPoint(Vi).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 $i=new kt,qi=new bt;class Yi{constructor(e=new Wi,t=new Wi,s=new Wi,i=new Wi,r=new Wi,n=new Wi){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===Ue)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(),$i.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),$i.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere($i)}intersectsSprite(e){return $i.center.set(0,0,0),$i.radius=.7071067811865476,$i.applyMatrix4(e.matrixWorld),this.intersectsSphere($i)}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(qi.x=i.normal.x>0?e.max.x:e.min.x,qi.y=i.normal.y>0?e.max.y:e.min.y,qi.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(qi)<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 Xi extends js{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new zs(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class Ki extends js{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new zs(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class Qi extends dt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=E,this.minFilter=E,this.generateMipmaps=!1,this.needsUpdate=!0}}class Zi extends dt{constructor(e,t,s,i,r,n,o,a,h,l=1026){if(l!==W&&l!==$)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===s&&l===W&&(s=k),void 0===s&&l===$&&(s=V),super(null,i,r,n,o,a,l,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==o?o:E,this.minFilter=void 0!==a?a:E,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Ji extends li{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 bt,c=new bt,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 ti(p,3)),this.setAttribute("normal",new ti(m,3)),this.setAttribute("uv",new ti(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ji(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class er extends js{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new zs(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class tr extends js{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new zs(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 rs,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 sr extends tr{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 Xe(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 zs(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new zs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new zs(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class ir extends js{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new zs(16777215),this.specular=new zs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rs,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 rr extends js{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new zs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 nr extends js{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 or extends js{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new zs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rs,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 ar extends js{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new zs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Xe(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 hr extends Xi{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 lr extends vs{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new zs(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 ur extends lr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(vs.DEFAULT_UP),this.updateMatrix(),this.groundColor=new zs(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const cr=new Yt,dr=new bt,pr=new bt;class mr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Xe(512,512),this.map=null,this.mapPass=null,this.matrix=new Yt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Yi,this._frameExtents=new Xe(1,1),this._viewportCount=1,this._viewports=[new pt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;dr.setFromMatrixPosition(e.matrixWorld),t.position.copy(dr),pr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(pr),t.updateMatrixWorld(),cr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(cr),s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(cr)}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 gr extends mr{constructor(){super(new Ri(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,s=2*Ge*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 fr extends lr{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(vs.DEFAULT_UP),this.updateMatrix(),this.target=new vs,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new gr}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 yr=new Yt,br=new bt,xr=new bt;class _r extends mr{constructor(){super(new Ri(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Xe(4,2),this._viewportCount=6,this._viewports=[new pt(2,1,1,1),new pt(0,1,1,1),new pt(3,1,1,1),new pt(1,1,1,1),new pt(3,0,1,1),new pt(1,0,1,1)],this._cubeDirections=[new bt(1,0,0),new bt(-1,0,0),new bt(0,0,1),new bt(0,0,-1),new bt(0,1,0),new bt(0,-1,0)],this._cubeUps=[new bt(0,1,0),new bt(0,1,0),new bt(0,1,0),new bt(0,1,0),new bt(0,0,1),new bt(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()),br.setFromMatrixPosition(e.matrixWorld),s.position.copy(br),xr.copy(s.position),xr.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(xr),s.updateMatrixWorld(),i.makeTranslation(-br.x,-br.y,-br.z),yr.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(yr)}}class vr extends lr{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 _r}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 Tr extends Ni{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 Sr extends mr{constructor(){super(new Tr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class wr extends lr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(vs.DEFAULT_UP),this.updateMatrix(),this.target=new vs,this.shadow=new Sr}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Mr extends lr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Nr extends lr{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 Ar{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new bt)}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 Er extends lr{constructor(e=new Ar,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 Cr extends Di{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}}"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 Rr=["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 Pr{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Rr,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:{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(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 Br(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 Fr=e=>Br(e),Ir=(...e)=>Br(e);function Ur(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of Dr(e))s.push(s,Br(i.slice(0,-4)),r.getCacheKey(t));return Br(s)}function*Dr(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 Or=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Lr=new WeakMap;function kr(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.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function zr(e,...t){const s=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===s?t=[t[0],t[0]]:"vec3"===s?t=[t[0],t[0],t[0]]:"vec4"===s&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new zs(...t):"vec2"===s?new Xe(...t):"vec3"===s?new bt(...t):"vec4"===s?new pt(...t):"mat3"===s?new Ke(...t):"mat4"===s?new Yt(...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 Gr(e){let t=Lr.get(e);return void 0===t&&(t={},Lr.set(e,t)),t}const Vr="vertex",jr="none",Hr="frame",Wr="render",$r="object",qr="readOnly",Yr="writeOnly",Xr="readWrite",Kr=["setup","analyze","generate"],Qr=["fragment","vertex","compute"],Zr=["x","y","z","w"];let Jr=0;class en 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=Ye.generateUUID(),this.version=0,this.global=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Jr++})}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,Hr)}onRenderUpdate(e){return this.onUpdate(e,Wr)}onObjectUpdate(e){return this.onUpdate(e,$r)}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 Dr(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=Ir(Ur(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)}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?(i=this.generate(e)||"",r.snippet=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 Dr(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 tn extends en{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){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class sn extends en{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 rn extends en{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 nn extends rn{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=this.nodes,r=e.getComponentType(s),n=[];for(const t of i){let s=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(s=e.format(s,i,r)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}const on=Zr.join("");class an extends en{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(Zr.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===on.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 hn extends rn{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=Zr[e];t===s[0]?(u.push(a),e+=s.length-1):u.push(h+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class ln extends rn{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=Zr[e];s===t[l]?(h.push("1.0 - "+o+"."+s),l++):h.push(o+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class un extends en{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?kr(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=kr(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)?zr(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.")}}class cn extends un{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 e.format(this.generateConst(e),s,t)}}let dn=null;const pn=new Map;function mn(e,t){if(pn.has(e))console.warn(`Redefinition of method chaining ${e}`);else{if("function"!=typeof t)throw new Error(`Node element ${e} is not a function`);pn.set(e,t)}}const gn=e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),fn=e=>gn(e).split("").sort().join(""),yn={setup(e,t){const s=t.shift();return e(Gn(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(dn.assign(s,...e),s);if(pn.has(t)){const i=pn.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&pn.has(t.slice(0,t.length-6))){const i=pn.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=gn(t),zn(new an(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=fn(t.slice(3).toLowerCase()),s=>zn(new hn(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=fn(t.slice(4).toLowerCase()),()=>zn(new ln(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 an(e,t));if(!0===/^\d+$/.test(t))return zn(new tn(s,new cn(Number(t),"uint")))}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)},bn=new WeakMap,xn=new WeakMap,_n=function(e,t=null){for(const s in e)e[s]=zn(e[s],t);return e},vn=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=zn(e[i],t);return e},Tn=function(e,t=null,s=null,i=null){const r=e=>zn(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Vn(t))):null!==s?(s=zn(s),(...i)=>r(new e(t,...Vn(i),s))):(...s)=>r(new e(t,...Vn(s)))},Sn=function(e,...t){return zn(new e(...Vn(t)))};class wn extends en{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}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=xn.get(e.constructor);void 0===i&&(i=new WeakMap,xn.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=zn(e.buildFunctionNode(t)),i.set(t,n)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(n),r=zn(n.call(s))}else{const i=t.jsFunc,n=null!==s?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 Mn extends en{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 Gn(e),zn(new wn(this,e))}setup(){return this.call()}}const Nn=[!1,!0],An=[0,1,2,3],En=[-1,-2],Cn=[.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],Rn=new Map;for(const e of Nn)Rn.set(e,new cn(e));const Pn=new Map;for(const e of An)Pn.set(e,new cn(e,"uint"));const Bn=new Map([...Pn].map((e=>new cn(e.value,"int"))));for(const e of En)Bn.set(e,new cn(e,"int"));const Fn=new Map([...Bn].map((e=>new cn(e.value))));for(const e of Cn)Fn.set(e,new cn(e));for(const e of Cn)Fn.set(-e,new cn(-e));const In={bool:Rn,uint:Pn,ints:Bn,float:Fn},Un=new Map([...Rn,...Fn]),Dn=(e,t)=>Un.has(e)?Un.get(e):!0===e.isNode?e:new cn(e,t),On=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[zr(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return zn(t.get(s[0]));if(1===s.length){const t=Dn(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?zn(t):zn(new sn(t,e))}const i=s.map((e=>Dn(e)));return zn(new nn(i,e))}},Ln=e=>"object"==typeof e&&null!==e?e.value:e;function kn(e,t){return new Proxy(new Mn(e,t),yn)}const zn=(e,t=null)=>function(e,t=null){const s=kr(e);if("node"===s){let t=bn.get(e);return void 0===t&&(t=new Proxy(e,yn),bn.set(e,t),bn.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?zn(Dn(e,t)):"shader"===s?Wn(e):e}(e,t),Gn=(e,t=null)=>new _n(e,t),Vn=(e,t=null)=>new vn(e,t),jn=(...e)=>new Tn(...e),Hn=(...e)=>new Sn(...e),Wn=(e,t)=>{const s=new kn(e,t),i=(...e)=>{let t;return Gn(e),t=e[0]&&e[0].isNode?[...e]:e[0],s.call(t)};return i.shaderNode=s,i.setLayout=e=>(s.setLayout(e),i),i.once=()=>(s.once=!0,i),i};mn("toGlobal",(e=>(e.global=!0,e)));const $n=e=>{dn=e},qn=()=>dn,Yn=(...e)=>dn.If(...e);mn("append",(function(e){return dn&&dn.add(e),e}));const Xn=new On("color"),Kn=new On("float",In.float),Qn=new On("int",In.ints),Zn=new On("uint",In.uint),Jn=new On("bool",In.bool),eo=new On("vec2"),to=new On("ivec2"),so=new On("uvec2"),io=new On("bvec2"),ro=new On("vec3"),no=new On("ivec3"),oo=new On("uvec3"),ao=new On("bvec3"),ho=new On("vec4"),lo=new On("ivec4"),uo=new On("uvec4"),co=new On("bvec4"),po=new On("mat2"),mo=new On("mat3"),go=new On("mat4");mn("toColor",Xn),mn("toFloat",Kn),mn("toInt",Qn),mn("toUint",Zn),mn("toBool",Jn),mn("toVec2",eo),mn("toIVec2",to),mn("toUVec2",so),mn("toBVec2",io),mn("toVec3",ro),mn("toIVec3",no),mn("toUVec3",oo),mn("toBVec3",ao),mn("toVec4",ho),mn("toIVec4",lo),mn("toUVec4",uo),mn("toBVec4",co),mn("toMat2",po),mn("toMat3",mo),mn("toMat4",go);mn("element",jn(tn)),mn("convert",((e,t)=>zn(new sn(zn(e),t))));class fo extends en{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 yo=e=>new fo(e),bo=(e,t=0)=>new fo(e,!0,t),xo=bo("frame"),_o=bo("render"),vo=yo("object");class To extends un{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=vo}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 So=(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 To(i,s))};class wo extends en{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 Mo=(e,t)=>zn(new wo(e,t,!0)),No=Hn(wo,"vec4","DiffuseColor"),Ao=Hn(wo,"vec3","EmissiveColor"),Eo=Hn(wo,"float","Roughness"),Co=Hn(wo,"float","Metalness"),Ro=Hn(wo,"float","Clearcoat"),Po=Hn(wo,"float","ClearcoatRoughness"),Bo=Hn(wo,"vec3","Sheen"),Fo=Hn(wo,"float","SheenRoughness"),Io=Hn(wo,"float","Iridescence"),Uo=Hn(wo,"float","IridescenceIOR"),Do=Hn(wo,"float","IridescenceThickness"),Oo=Hn(wo,"float","AlphaT"),Lo=Hn(wo,"float","Anisotropy"),ko=Hn(wo,"vec3","AnisotropyT"),zo=Hn(wo,"vec3","AnisotropyB"),Go=Hn(wo,"color","SpecularColor"),Vo=Hn(wo,"float","SpecularF90"),jo=Hn(wo,"float","Shininess"),Ho=Hn(wo,"vec4","Output"),Wo=Hn(wo,"float","dashSize"),$o=Hn(wo,"float","gapSize"),qo=Hn(wo,"float","IOR"),Yo=Hn(wo,"float","Transmission"),Xo=Hn(wo,"float","Thickness"),Ko=Hn(wo,"float","AttenuationDistance"),Qo=Hn(wo,"color","AttenuationColor"),Zo=Hn(wo,"float","Dispersion");class Jo extends rn{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 Zr.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)}}mn("assign",jn(Jo));class ea extends rn{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))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];if(void 0===s)throw new Error(`FunctionCallNode: Input '${e.name}' not found in FunctionNode.`);t.push(n(s,e))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}mn("call",((e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Vn(t):Gn(t[0]),zn(new ea(zn(e),t)))));class ta extends rn{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new ta(e,t,s);for(let t=0;t<i.length-1;t++)r=new ta(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s}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)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"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):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?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):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);return"void"!==t?"<"===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} < ${l} )`,n,t):"<="===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} <= ${l} )`,n,t):">"===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} > ${l} )`,n,t):">="===s&&u>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} >= ${l} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${h})`,o,t):c?e.format(`${c}( ${h}, ${l} )`,n,t):e.format(`( ${h} ${s} ${l} )`,n,t):"void"!==o?c?e.format(`${c}( ${h}, ${l} )`,n,t):e.format(`${h} ${s} ${l}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const sa=jn(ta,"+"),ia=jn(ta,"-"),ra=jn(ta,"*"),na=jn(ta,"/"),oa=jn(ta,"%"),aa=jn(ta,"=="),ha=jn(ta,"!="),la=jn(ta,"<"),ua=jn(ta,">"),ca=jn(ta,"<="),da=jn(ta,">="),pa=jn(ta,"&&"),ma=jn(ta,"||"),ga=jn(ta,"!"),fa=jn(ta,"^^"),ya=jn(ta,"&"),ba=jn(ta,"~"),xa=jn(ta,"|"),_a=jn(ta,"^"),va=jn(ta,"<<"),Ta=jn(ta,">>");mn("add",sa),mn("sub",ia),mn("mul",ra),mn("div",na),mn("modInt",oa),mn("equal",aa),mn("notEqual",ha),mn("lessThan",la),mn("greaterThan",ua),mn("lessThanEqual",ca),mn("greaterThanEqual",da),mn("and",pa),mn("or",ma),mn("not",ga),mn("xor",fa),mn("bitAnd",ya),mn("bitNot",ba),mn("bitOr",xa),mn("bitXor",_a),mn("shiftLeft",va),mn("shiftRight",Ta);mn("remainder",((...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),oa(...e))));class Sa extends rn{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=i}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===Sa.LENGTH||t===Sa.DISTANCE||t===Sa.DOT?"float":t===Sa.CROSS?"vec3":t===Sa.ALL?"bool":t===Sa.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===Sa.MOD?this.aNode.getNodeType(e):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===Sa.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=ho(ro(i),0):s=ho(ro(s),0);const r=ra(s,i).xyz;return La(r).build(e,t)}if(s===Sa.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===Sa.ONE_MINUS)return ia(1,n).build(e,t);if(s===Sa.RECIPROCAL)return na(1,n).build(e,t);if(s===Sa.DIFFERENCE)return $a(ia(n,o)).build(e,t);{const l=[];return s===Sa.CROSS||s===Sa.MOD?l.push(n.build(e,i),o.build(e,i)):h===Ue&&s===Sa.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h===Ue&&(s===Sa.MIN||s===Sa.MAX)||s===Sa.MOD?l.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):s===Sa.REFRACT?l.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===Sa.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===Sa.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))),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}}Sa.ALL="all",Sa.ANY="any",Sa.RADIANS="radians",Sa.DEGREES="degrees",Sa.EXP="exp",Sa.EXP2="exp2",Sa.LOG="log",Sa.LOG2="log2",Sa.SQRT="sqrt",Sa.INVERSE_SQRT="inversesqrt",Sa.FLOOR="floor",Sa.CEIL="ceil",Sa.NORMALIZE="normalize",Sa.FRACT="fract",Sa.SIN="sin",Sa.COS="cos",Sa.TAN="tan",Sa.ASIN="asin",Sa.ACOS="acos",Sa.ATAN="atan",Sa.ABS="abs",Sa.SIGN="sign",Sa.LENGTH="length",Sa.NEGATE="negate",Sa.ONE_MINUS="oneMinus",Sa.DFDX="dFdx",Sa.DFDY="dFdy",Sa.ROUND="round",Sa.RECIPROCAL="reciprocal",Sa.TRUNC="trunc",Sa.FWIDTH="fwidth",Sa.TRANSPOSE="transpose",Sa.BITCAST="bitcast",Sa.EQUALS="equals",Sa.MIN="min",Sa.MAX="max",Sa.MOD="mod",Sa.STEP="step",Sa.REFLECT="reflect",Sa.DISTANCE="distance",Sa.DIFFERENCE="difference",Sa.DOT="dot",Sa.CROSS="cross",Sa.POW="pow",Sa.TRANSFORM_DIRECTION="transformDirection",Sa.MIX="mix",Sa.CLAMP="clamp",Sa.REFRACT="refract",Sa.SMOOTHSTEP="smoothstep",Sa.FACEFORWARD="faceforward";const wa=Kn(1e-6),Ma=Kn(Math.PI),Na=jn(Sa,Sa.ALL),Aa=jn(Sa,Sa.ANY),Ea=jn(Sa,Sa.RADIANS),Ca=jn(Sa,Sa.DEGREES),Ra=jn(Sa,Sa.EXP),Pa=jn(Sa,Sa.EXP2),Ba=jn(Sa,Sa.LOG),Fa=jn(Sa,Sa.LOG2),Ia=jn(Sa,Sa.SQRT),Ua=jn(Sa,Sa.INVERSE_SQRT),Da=jn(Sa,Sa.FLOOR),Oa=jn(Sa,Sa.CEIL),La=jn(Sa,Sa.NORMALIZE),ka=jn(Sa,Sa.FRACT),za=jn(Sa,Sa.SIN),Ga=jn(Sa,Sa.COS),Va=jn(Sa,Sa.TAN),ja=jn(Sa,Sa.ASIN),Ha=jn(Sa,Sa.ACOS),Wa=jn(Sa,Sa.ATAN),$a=jn(Sa,Sa.ABS),qa=jn(Sa,Sa.SIGN),Ya=jn(Sa,Sa.LENGTH),Xa=jn(Sa,Sa.NEGATE),Ka=jn(Sa,Sa.ONE_MINUS),Qa=jn(Sa,Sa.DFDX),Za=jn(Sa,Sa.DFDY),Ja=jn(Sa,Sa.ROUND),eh=jn(Sa,Sa.RECIPROCAL),th=jn(Sa,Sa.TRUNC),sh=jn(Sa,Sa.FWIDTH),ih=jn(Sa,Sa.TRANSPOSE);Sa.BITCAST;const rh=jn(Sa,Sa.EQUALS),nh=jn(Sa,Sa.MIN),oh=jn(Sa,Sa.MAX),ah=jn(Sa,Sa.MOD),hh=jn(Sa,Sa.STEP),lh=jn(Sa,Sa.REFLECT),uh=jn(Sa,Sa.DISTANCE),ch=jn(Sa,Sa.DIFFERENCE),dh=jn(Sa,Sa.DOT),ph=jn(Sa,Sa.CROSS),mh=jn(Sa,Sa.POW),gh=jn(Sa,Sa.POW,2),fh=jn(Sa,Sa.POW,3),yh=jn(Sa,Sa.POW,4),bh=jn(Sa,Sa.TRANSFORM_DIRECTION),xh=jn(Sa,Sa.MIX),_h=(e,t=0,s=1)=>zn(new Sa(Sa.CLAMP,zn(e),zn(t),zn(s))),vh=jn(Sa,Sa.REFRACT),Th=jn(Sa,Sa.SMOOTHSTEP),Sh=jn(Sa,Sa.FACEFORWARD),wh=Wn((([e])=>{const t=dh(e.xy,eo(12.9898,78.233)),s=ah(t,Ma);return ka(za(s).mul(43758.5453))}));mn("all",Na),mn("any",Aa),mn("equals",rh),mn("radians",Ea),mn("degrees",Ca),mn("exp",Ra),mn("exp2",Pa),mn("log",Ba),mn("log2",Fa),mn("sqrt",Ia),mn("inverseSqrt",Ua),mn("floor",Da),mn("ceil",Oa),mn("normalize",La),mn("fract",ka),mn("sin",za),mn("cos",Ga),mn("tan",Va),mn("asin",ja),mn("acos",Ha),mn("atan",Wa),mn("abs",$a),mn("sign",qa),mn("length",Ya),mn("lengthSq",(e=>dh(e,e))),mn("negate",Xa),mn("oneMinus",Ka),mn("dFdx",Qa),mn("dFdy",Za),mn("round",Ja),mn("reciprocal",eh),mn("trunc",th),mn("fwidth",sh),mn("atan2",((e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),Wa(e,t)))),mn("min",nh),mn("max",oh),mn("mod",ah),mn("step",hh),mn("reflect",lh),mn("distance",uh),mn("dot",dh),mn("cross",ph),mn("pow",mh),mn("pow2",gh),mn("pow3",fh),mn("pow4",yh),mn("transformDirection",bh),mn("mix",((e,t,s)=>xh(t,s,e))),mn("clamp",_h),mn("refract",vh),mn("smoothstep",((e,t,s)=>Th(t,s,e))),mn("faceForward",Sh),mn("difference",ch),mn("saturate",(e=>_h(e))),mn("cbrt",(e=>ra(qa(e),mh($a(e),1/3)))),mn("transpose",ih),mn("rand",wh);class Mh extends en{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="void"!==t,h=a?((e,t)=>zn(new wo(e,t)))(s).build(e):"";i.nodeProperty=h;const l=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${l} ) {\n\n`).addFlowTab();let u=n.build(e,s);if(u&&(u=a?h+" = "+u+";":"return "+u+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+u+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(t=a?h+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const Nh=jn(Mh);mn("select",Nh);mn("cond",((...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),Nh(...e))));class Ah extends en{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 Eh=jn(Ah);mn("context",Eh),mn("label",((e,t)=>Eh(e,{label:t})));class Ch extends en{static get type(){return"VarNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,i=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),n=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${n}`,this),r}}const Rh=jn(Ch);mn("toVar",((...e)=>Rh(...e).append()));mn("temp",(e=>(console.warn('TSL: "temp" is deprecated. Use ".toVar()" instead.'),Rh(e))));class Ph extends en{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,Vr);e.flowNodeFromShaderStage(Vr,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 Bh=jn(Ph);mn("varying",Bh),mn("vertexStage",(e=>Bh(e)));const Fh=Wn((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return xh(t,s,i)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Ih=Wn((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return xh(t,s,i)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Uh="WorkingColorSpace",Dh="OutputColorSpace";class Oh extends rn{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===Uh?it.workingColorSpace:t===Dh?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!==it.enabled&&s!==i&&s&&i?(it.getTransfer(s)===Se&&(r=ho(Fh(r.rgb),r.a)),it.getPrimaries(s)!==it.getPrimaries(i)&&(r=ho(mo(it._getMatrix(new Ke,s,i)).mul(r.rgb),r.a)),it.getTransfer(i)===Se&&(r=ho(Ih(r.rgb),r.a)),r):r}}const Lh=(e,t)=>zn(new Oh(zn(e),t,Uh));mn("toOutputColorSpace",(e=>zn(new Oh(zn(e),Uh,Dh)))),mn("toWorkingColorSpace",(e=>zn(new Oh(zn(e),Dh,Uh)))),mn("workingToColorSpace",((e,t)=>zn(new Oh(zn(e),Uh,t)))),mn("colorSpaceToWorking",Lh);let kh=class extends tn{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 zh extends en{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=$r}setGroup(e){return this.group=e,this}element(e){return zn(new kh(this,zn(e)))}setNodeType(e){const t=So(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 Gh extends zh{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(_o)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const Vh=(e,t,s=null)=>zn(new Gh(e,t,s));class jh extends rn{static get type(){return"ToneMappingNode"}constructor(e,t=Hh,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Ir(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=ho(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const Hh=Vh("toneMappingExposure","float");mn("toneMapping",((e,t,s)=>((e,t,s)=>zn(new jh(e,zn(t),zn(s))))(t,s,e)));class Wh extends un{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=Fe,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 Di(s,r),a=new Li(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=Bh(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 $h=(e,t=null,s=0,i=0)=>zn(new Wh(e,t,s,i)),qh=(e,t=null,s=0,i=0)=>$h(e,t,s,i).setInstanced(!0),Yh=(e,t=null,s=0,i=0)=>((e,t=null,s=0,i=0)=>$h(e,t,s,i).setUsage(Ie))(e,t,s,i).setInstanced(!0);mn("toAttribute",(e=>$h(e.value)));class Xh extends en{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=$r,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)}generate(e){const{shaderStage:t}=e;if("compute"===t){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}}}mn("compute",((e,t,s)=>zn(new Xh(zn(e),t,s))));class Kh extends en{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 Qh=(e,t)=>zn(new Kh(zn(e),t));mn("cache",Qh);class Zh extends en{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)}}mn("bypass",jn(Zh));class Jh extends en{static get type(){return"RemapNode"}constructor(e,t,s,i=Kn(0),r=Kn(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 el=jn(Jh,null,null,{doClamp:!1}),tl=jn(Jh);mn("remap",el),mn("remapClamp",tl);class sl extends en{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 il=jn(sl);mn("discard",(e=>(e?Nh(e,il("discard")):il("discard")).append()));class rl extends rn{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!==it.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}mn("renderOutput",((e,t=null,s=null)=>zn(new rl(zn(e),t,s))));class nl extends en{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 Bh(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 ol=(e,t)=>zn(new nl(e,t)),al=(e=0)=>ol("uv"+(e>0?e:""),"vec2");class hl extends en{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=jn(hl);class ul extends To{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Hr}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 cl=jn(ul);class dl extends To{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===k?"uvec4":this.value.type===L?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return al(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=So(this.value.matrix)),this._matrixUniform.mul(ro(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Wr: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(Qn(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)),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"===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=Lh(il(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();return t.biasNode=zn(e).mul(cl(t)),t.referenceNode=this.getSelf(),zn(t)}level(e){const t=this.clone();return t.levelNode=zn(e),t.referenceNode=this.getSelf(),zn(t)}size(e){return ll(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 pl=jn(dl),ml=(...e)=>pl(...e).setSampler(!1),gl=So("float").label("cameraNear").setGroup(_o).onRenderUpdate((({camera:e})=>e.near)),fl=So("float").label("cameraFar").setGroup(_o).onRenderUpdate((({camera:e})=>e.far)),yl=So("mat4").label("cameraProjectionMatrix").setGroup(_o).onRenderUpdate((({camera:e})=>e.projectionMatrix)),bl=So("mat4").label("cameraViewMatrix").setGroup(_o).onRenderUpdate((({camera:e})=>e.matrixWorldInverse)),xl=So(new bt).label("cameraPosition").setGroup(_o).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));class _l extends en{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=$r,this._uniformNode=new To(null)}getNodeType(){const e=this.scope;return e===_l.WORLD_MATRIX?"mat4":e===_l.POSITION||e===_l.VIEW_POSITION||e===_l.DIRECTION||e===_l.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===_l.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===_l.POSITION)s.value=s.value||new bt,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===_l.SCALE)s.value=s.value||new bt,s.value.setFromMatrixScale(t.matrixWorld);else if(i===_l.DIRECTION)s.value=s.value||new bt,t.getWorldDirection(s.value);else if(i===_l.VIEW_POSITION){const i=e.camera;s.value=s.value||new bt,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===_l.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t!==_l.POSITION&&t!==_l.VIEW_POSITION&&t!==_l.DIRECTION&&t!==_l.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}_l.WORLD_MATRIX="worldMatrix",_l.POSITION="position",_l.SCALE="scale",_l.VIEW_POSITION="viewPosition",_l.DIRECTION="direction",_l.DIRECTION,_l.WORLD_MATRIX;const vl=jn(_l,_l.POSITION);_l.SCALE,_l.VIEW_POSITION;class Tl extends _l{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Sl=Hn(Tl,Tl.WORLD_MATRIX),wl=So(new Ke).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),Ml=Wn((e=>e.renderer.nodes.modelViewMatrix||Nl)).once()().toVar("modelViewMatrix"),Nl=bl.mul(Sl),Al=ol("position","vec3"),El=Al.varying("positionLocal"),Cl=Al.varying("positionPrevious"),Rl=Sl.mul(El).xyz.varying("v_positionWorld").context({needsPositionReassign:!0}),Pl=El.transformDirection(Sl).varying("v_positionWorldDirection").normalize().toVar("positionWorldDirection").context({needsPositionReassign:!0}),Bl=Wn((e=>e.context.setupPositionView()),"vec3").once()().varying("v_positionView").context({needsPositionReassign:!0}),Fl=Bl.negate().varying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Il extends en{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Ue&&1===s.side?"false":e.getFrontFacing()}}const Ul=Kn(Hn(Il)).mul(2).sub(1),Dl=ol("normal","vec3"),Ol=Wn((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),ro(0,1,0)):Dl),"vec3").once()().toVar("normalLocal"),Ll=Bl.dFdx().cross(Bl.dFdy()).normalize().toVar("normalFlat"),kl=Wn((e=>{let t;return t=!0===e.material.flatShading?Ll:Bh(Wl(Ol),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),zl=Bh(kl.transformDirection(bl),"v_normalWorld").normalize().toVar("normalWorld"),Gl=Wn((e=>e.context.setupNormal()),"vec3").once()().mul(Ul).toVar("transformedNormalView"),Vl=Gl.transformDirection(bl).toVar("transformedNormalWorld"),jl=Wn((e=>e.context.setupClearcoatNormal()),"vec3").once()().mul(Ul).toVar("transformedClearcoatNormalView"),Hl=Wn((([e,t=Sl])=>{const s=mo(t),i=e.div(ro(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),Wl=Wn((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=wl.mul(e);return bl.transformDirection(i)})),$l=So(0).onReference((({material:e})=>e)).onRenderUpdate((({material:e})=>e.refractionRatio)),ql=Fl.negate().reflect(Gl),Yl=Fl.negate().refract(Gl,$l),Xl=ql.transformDirection(bl).toVar("reflectVector"),Kl=Yl.transformDirection(bl).toVar("reflectVector");class Ql extends dl{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?Xl:e.mapping===T?Kl:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),ro(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==De&&s.isRenderTargetTexture?t:ro(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Zl=jn(Ql);class Jl extends To{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 eu=(e,t,s)=>zn(new Jl(e,t,s));class tu extends tn{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 su extends Jl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?kr(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Wr,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 tu(this,zn(e)))}}const iu=(e,t)=>zn(new su(e,t));class ru extends tn{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 en{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=$r}element(e){return zn(new ru(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?eu(null,e,this.count):Array.isArray(this.getValueFromReference())?iu(null,e):"texture"===e?pl(null):"cubeTexture"===e?Zl(null):So(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 ou=(e,t,s)=>zn(new nu(e,t,s)),au=(e,t,s,i)=>zn(new nu(e,t,i,s));class hu 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 lu=(e,t,s=null)=>zn(new hu(e,t,s)),uu=Wn((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),ol("tangent","vec4"))))(),cu=uu.xyz.toVar("tangentLocal"),du=Ml.mul(ho(cu,0)).xyz.varying("v_tangentView").normalize().toVar("tangentView");var pu;const mu=mo(du,Bh((pu=kl.cross(du),pu.mul(uu.w).xyz),"v_bitangentView").normalize().toVar("bitangentView"),kl),gu=(()=>{let e=zo.cross(Fl);return e=e.cross(zo).normalize(),e=xh(e,Gl,Lo.mul(Eo.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),fu=Wn((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=Ul.mul(m.inverseSqrt());return sa(d.mul(i.x,g),p.mul(i.y,g),l.mul(i.z)).normalize()}));class yu extends rn{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=ro(i.xy.mul(s),i.z));let r=null;if(1===t)r=Wl(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?mu.mul(i).normalize():fu({eye_pos:Bl,surf_norm:kl,mapN:i,uv:al()})}return r}}const bu=jn(yu),xu=Wn((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||al()),forceUVContext:!0}),i=Kn(s((e=>e)));return eo(Kn(s((e=>e.add(e.dFdx())))).sub(i),Kn(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),_u=Wn((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(Ul),l=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(l).normalize()}));class vu extends rn{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=xu({textureNode:this.textureNode,bumpScale:e});return _u({surf_pos:Bl,surf_norm:kl,dHdxy:t})}}const Tu=jn(vu),Su=new Map;class wu extends en{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=Su.get(e);return void 0===s&&(s=lu(e,t),Su.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):ro();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:Kn(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=bu(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?Tu(this.getTexture("bump").r,this.getFloat("bumpScale")):kl;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?bu(this.getTexture(s),this.getCache(s+"Scale","vec2")):kl;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=po(oc.x,oc.y,oc.y.negate(),oc.x).mul(e.rg.mul(2).sub(eo(1)).normalize().mul(e.b))}else i=oc;else if(s===wu.IRIDESCENCE_THICKNESS){const e=ou("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=ou("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_WIDTH="pointWidth",wu.DISPERSION="dispersion",wu.LIGHT_MAP="light",wu.AO="ao";const Mu=Hn(wu,wu.ALPHA_TEST),Nu=Hn(wu,wu.COLOR),Au=Hn(wu,wu.SHININESS),Eu=Hn(wu,wu.EMISSIVE),Cu=Hn(wu,wu.OPACITY),Ru=Hn(wu,wu.SPECULAR),Pu=Hn(wu,wu.SPECULAR_INTENSITY),Bu=Hn(wu,wu.SPECULAR_COLOR),Fu=Hn(wu,wu.SPECULAR_STRENGTH),Iu=Hn(wu,wu.REFLECTIVITY),Uu=Hn(wu,wu.ROUGHNESS),Du=Hn(wu,wu.METALNESS),Ou=Hn(wu,wu.NORMAL).context({getUV:null}),Lu=Hn(wu,wu.CLEARCOAT),ku=Hn(wu,wu.CLEARCOAT_ROUGHNESS),zu=Hn(wu,wu.CLEARCOAT_NORMAL).context({getUV:null}),Gu=Hn(wu,wu.ROTATION),Vu=Hn(wu,wu.SHEEN),ju=Hn(wu,wu.SHEEN_ROUGHNESS),Hu=Hn(wu,wu.ANISOTROPY),Wu=Hn(wu,wu.IRIDESCENCE),$u=Hn(wu,wu.IRIDESCENCE_IOR),qu=Hn(wu,wu.IRIDESCENCE_THICKNESS),Yu=Hn(wu,wu.TRANSMISSION),Xu=Hn(wu,wu.THICKNESS),Ku=Hn(wu,wu.IOR),Qu=Hn(wu,wu.ATTENUATION_DISTANCE),Zu=Hn(wu,wu.ATTENUATION_COLOR),Ju=Hn(wu,wu.LINE_SCALE),ec=Hn(wu,wu.LINE_DASH_SIZE),tc=Hn(wu,wu.LINE_GAP_SIZE);wu.LINE_WIDTH;const sc=Hn(wu,wu.LINE_DASH_OFFSET);wu.POINT_WIDTH;const ic=Hn(wu,wu.DISPERSION),rc=Hn(wu,wu.LIGHT_MAP),nc=Hn(wu,wu.AO),oc=So(new Xe).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))})),ac=Wn((e=>e.context.setupModelViewProjection()),"vec4").once()().varying("v_modelViewProjection");class hc extends en{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=Bh(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 lc=Hn(hc,hc.VERTEX),uc=Hn(hc,hc.INSTANCE);hc.SUBGROUP,hc.INVOCATION_SUBGROUP,hc.INVOCATION_LOCAL;const cc=Hn(hc,hc.DRAW);class dc extends en{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=Hr,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=eu(s.array,"mat4",Math.max(t,1)).element(uc);else{const e=new Cr(s.array,16,1);this.buffer=e;const t=s.usage===Ie?Yh:qh,i=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];r=go(...i)}this.instanceMatrixNode=r}if(i&&null===n){const e=new Gi(i.array,3),t=i.usage===Ie?Yh:qh;this.bufferColor=e,n=ro(t(e,"vec3",3,0)),this.instanceColorNode=n}const o=r.mul(El).xyz;if(El.assign(o),e.hasGeometryAttribute("normal")){const e=Hl(Ol,r);Ol.assign(e)}null!==this.instanceColorNode&&Mo("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 pc extends dc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const mc=jn(pc);class gc extends en{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=uc:this.batchingIdNode=cc);const t=Wn((([e])=>{const t=ll(ml(this.batchMesh._indirectTexture),0),s=Qn(e).modInt(Qn(t)),i=Qn(e).div(Qn(t));return ml(this.batchMesh._indirectTexture,to(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(Qn(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=ll(ml(i),0),n=Kn(s).mul(4).toInt().toVar(),o=n.modInt(r),a=n.div(Qn(r)),h=go(ml(i,to(o,a)),ml(i,to(o.add(1),a)),ml(i,to(o.add(2),a)),ml(i,to(o.add(3),a))),l=this.batchMesh._colorsTexture;if(null!==l){const e=Wn((([e])=>{const t=ll(ml(l),0).x,s=e,i=s.modInt(t),r=s.div(t);return ml(l,to(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);Mo("vec3","vBatchColor").assign(t)}const u=mo(h);El.assign(h.mul(El));const c=Ol.div(ro(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),d=u.mul(c).xyz;Ol.assign(d),e.hasGeometryAttribute("tangent")&&cu.mulAssign(u)}}const fc=jn(gc),yc=new WeakMap;class bc extends en{static get type(){return"SkinningNode"}constructor(e,t=!1){let s,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=$r,this.skinIndexNode=ol("skinIndex","uvec4"),this.skinWeightNode=ol("skinWeight","vec4"),t?(s=ou("bindMatrix","mat4"),i=ou("bindMatrixInverse","mat4"),r=au("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=So(e.bindMatrix,"mat4"),i=So(e.bindMatrixInverse,"mat4"),r=eu(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=El){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=sa(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=Ol){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=sa(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,Cl)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Gr(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Cl.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(El.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Ol.assign(t),e.hasGeometryAttribute("tangent")&&cu.assign(t)}}generate(e,t){if("void"!==t)return El.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;yc.get(t)!==e.frameId&&(yc.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class xc extends en{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]=il(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=null,n=null,o=null,a=null,h=null,l=null;i.isNode?(a="int",o=this.getVarName(t),r="0",n=i.build(e,a),h="<"):(a=i.type||"int",o=i.name||this.getVarName(t),r=i.start,n=i.end,h=i.condition,l=i.update,"number"==typeof r?r=e.generateConst(a,r):r&&r.isNode&&(r=r.build(e,a)),"number"==typeof n?n=e.generateConst(a,n):n&&n.isNode&&(n=n.build(e,a)),void 0!==r&&void 0===n?(r+=" - 1",n="0",h=">="):void 0!==n&&void 0===r&&(r="0",h="<"),void 0===h&&(h=Number(r)>Number(n)?">=":"<"));const u={start:r,end:n,condition:h},c=u.start,d=u.end;let p="",m="",g="";l||(l="int"===a||"uint"===a?h.includes("<")?"++":"--":h.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+c,m+=o+" "+h+" "+d,g+=o+" "+l;const f=`for ( ${p}; ${m}; ${g} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\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 _c=(...e)=>zn(new xc(Vn(e,"int"))).append(),vc=new WeakMap,Tc=new pt,Sc=Wn((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Qn(lc).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return ml(e,to(h,a)).depth(r).mul(t)}));class wc extends en{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=So(1),this.updateType=$r}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=vc.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 ft(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 S=0;S<x.count;S++){const w=S*f;!0===t&&(Tc.fromBufferAttribute(x,S),m[T+w+0]=Tc.x,m[T+w+1]=Tc.y,m[T+w+2]=Tc.z,m[T+w+3]=0),!0===s&&(Tc.fromBufferAttribute(_,S),m[T+w+4]=Tc.x,m[T+w+5]=Tc.y,m[T+w+6]=Tc.z,m[T+w+7]=0),!0===i&&(Tc.fromBufferAttribute(v,S),m[T+w+8]=Tc.x,m[T+w+9]=Tc.y,m[T+w+10]=Tc.z,m[T+w+11]=4===v.itemSize?Tc.w:1)}}function y(){g.dispose(),vc.delete(e),e.removeEventListener("dispose",y)}o={count:n,texture:g,stride:u,size:new Xe(c,d)},vc.set(e,o),e.addEventListener("dispose",y)}return o}(t);!0===s&&El.mulAssign(this.morphBaseInfluence),!0===i&&Ol.mulAssign(this.morphBaseInfluence);const l=Qn(h.width);_c(n,(({i:e})=>{const t=Kn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(ml(this.mesh.morphTexture,to(Qn(e).add(1),Qn(uc))).r):t.assign(ou("morphTargetInfluences","float").element(e).toVar()),!0===s&&El.addAssign(Sc({bufferMap:o,influence:t,stride:a,width:l,depth:e,offset:Qn(0)})),!0===i&&Ol.addAssign(Sc({bufferMap:o,influence:t,stride:a,width:l,depth:e,offset:Qn(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 Mc=jn(wc);class Nc extends en{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Ac extends Nc{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Ec extends Ah{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:ro().toVar("directDiffuse"),directSpecular:ro().toVar("directSpecular"),indirectDiffuse:ro().toVar("indirectDiffuse"),indirectSpecular:ro().toVar("indirectSpecular")};return{radiance:ro().toVar("radiance"),irradiance:ro().toVar("irradiance"),iblIrradiance:ro().toVar("iblIrradiance"),ambientOcclusion:Kn(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 Cc=jn(Ec);class Rc extends Nc{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Pc,Bc;class Fc extends en{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Fc.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=jr;return this.scope!==Fc.SIZE&&this.scope!==Fc.VIEWPORT||(e=Wr),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Fc.VIEWPORT?null!==t?Bc.copy(t.viewport):(e.getViewport(Bc),Bc.multiplyScalar(e.getPixelRatio())):null!==t?(Pc.width=t.width,Pc.height=t.height):e.getDrawingBufferSize(Pc)}setup(){const e=this.scope;let t=null;return t=e===Fc.SIZE?So(Pc||(Pc=new Xe)):e===Fc.VIEWPORT?So(Bc||(Bc=new pt)):eo(Dc.div(Uc)),t}generate(e){if(this.scope===Fc.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Uc).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Fc.COORDINATE="coordinate",Fc.VIEWPORT="viewport",Fc.SIZE="size",Fc.UV="uv";const Ic=Hn(Fc,Fc.UV),Uc=Hn(Fc,Fc.SIZE),Dc=Hn(Fc,Fc.COORDINATE),Oc=Hn(Fc,Fc.VIEWPORT);Oc.zw,Oc.xy;const Lc=new Xe;class kc extends dl{static get type(){return"ViewportTextureNode"}constructor(e=Ic,t=null,s=null){null===s&&((s=new Qi).minFilter=F),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Hr}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Lc);const s=this.value;s.image.width===Lc.width&&s.image.height===Lc.height||(s.image.width=Lc.width,s.image.height=Lc.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 zc=jn(kc,null,null,{generateMipmaps:!0});let Gc=null;class Vc extends kc{static get type(){return"ViewportDepthTextureNode"}constructor(e=Ic,t=null){null===Gc&&(Gc=new Zi),super(e,t,Gc)}}const jc=jn(Vc);class Hc extends en{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===Hc.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===Hc.DEPTH_BASE)null!==s&&(i=Xc().assign(s));else if(t===Hc.DEPTH)i=e.isPerspectiveCamera?$c(Bl.z,gl,fl):Wc(Bl.z,gl,fl);else if(t===Hc.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=qc(s,gl,fl);i=Wc(e,gl,fl)}else i=s;else i=Wc(Bl.z,gl,fl);return i}}Hc.DEPTH_BASE="depthBase",Hc.DEPTH="depth",Hc.LINEAR_DEPTH="linearDepth";const Wc=(e,t,s)=>e.add(t).div(t.sub(s)),$c=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),qc=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),Yc=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Fa(e.negate().div(t)),r=Fa(s.div(t));return i.div(r)},Xc=jn(Hc,Hc.DEPTH_BASE),Kc=Hn(Hc,Hc.DEPTH);Hc.LINEAR_DEPTH;jc(),Kc.assign=e=>Xc(e);const Qc=jn(class extends en{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}});class Zc extends en{static get type(){return"ClippingNode"}constructor(e=Zc.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===Zc.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Zc.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return Wn((()=>{const s=Kn().toVar("distanceToPlane"),i=Kn().toVar("distanceToGradient"),r=Kn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=iu(t);_c(n,(({i:t})=>{const n=e.element(t);s.assign(Bl.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(Th(i.negate(),i,s))}))}const o=e.length;if(o>0){const t=iu(e),n=Kn(1).toVar("intersectionClipOpacity");_c(o,(({i:e})=>{const r=t.element(e);s.assign(Bl.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Th(i.negate(),i,s).oneMinus())})),r.mulAssign(n.oneMinus())}No.a.mulAssign(r),No.a.equal(0).discard()}))()}setupDefault(e,t){return Wn((()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=iu(t);_c(s,(({i:t})=>{const s=e.element(t);Bl.dot(s.xyz).greaterThan(s.w).discard()}))}const i=e.length;if(i>0){const t=iu(e),s=Jn(!0).toVar("clipped");_c(i,(({i:e})=>{const i=t.element(e);s.assign(Bl.dot(i.xyz).greaterThan(i.w).and(s))})),s.discard()}}))()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),Wn((()=>{const i=iu(e),r=Qc(t.getClipDistance());_c(s,(({i:e})=>{const t=i.element(e),s=Bl.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)}))}))()}}Zc.ALPHA_TO_COVERAGE="alphaToCoverage",Zc.DEFAULT="default",Zc.HARDWARE="hardware";const Jc=Wn((([e])=>ka(ra(1e4,za(ra(17,e.x).add(ra(.1,e.y)))).mul(sa(.1,$a(za(ra(13,e.y).add(e.x)))))))),ed=Wn((([e])=>Jc(eo(Jc(e.xy),e.z)))),td=Wn((([e])=>{const t=oh(Ya(Qa(e.xyz)),Ya(Za(e.xyz))),s=Kn(1).div(Kn(.05).mul(t)).toVar("pixScale"),i=eo(Pa(Da(Fa(s))),Pa(Oa(Fa(s)))),r=eo(ed(Da(i.x.mul(e.xyz))),ed(Da(i.y.mul(e.xyz)))),n=ka(Fa(s)),o=sa(ra(n.oneMinus(),r.x),ra(n,r.y)),a=nh(n,n.oneMinus()),h=ro(o.mul(o).div(ra(2,a).mul(ia(1,a))),o.sub(ra(.5,a)).div(ia(1,a)),ia(1,ia(1,o).mul(ia(1,o)).div(ra(2,a).mul(ia(1,a))))),l=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(h.x,h.y),h.z);return _h(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class sd extends js{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+Ur(this)}build(e){this.setup(e)}setupObserver(e){return new Pr(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=ho(i,No.a).max(0);if(r=this.setupOutput(e,o),Ho.assign(r),null!==this.outputNode&&(r=this.outputNode),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(r=e,null!==s&&(r=e.merge(s))):null!==s&&(r=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=ho(t)),r=this.setupOutput(e,t)}e.stack.outputNode=r,e.addFlow("fragment",e.removeStack()),e.monitor=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 Zc(Zc.ALPHA_TO_COVERAGE)):e.stack.add(zn(new Zc))}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 Zc(Zc.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?Yc(Bl.z,gl,fl):Wc(Bl.z,gl,fl))}null!==i&&Kc.assign(i).append()}setupPositionView(){return Ml.mul(El).xyz}setupModelViewProjection(){return yl.mul(Bl)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),ac}setupPosition(e){const{object:t,geometry:s}=e;var i;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Mc(t).append(),!0===t.isSkinnedMesh&&(i=t,zn(new bc(i,!0))).append(),this.displacementMap){const e=lu("displacementMap","texture"),t=lu("displacementScale","float"),s=lu("displacementBias","float");El.addAssign(Ol.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&fc(t).append(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&mc(t).append(),null!==this.positionNode&&El.assign(this.positionNode.context({isPositionNodeInput:!0})),El}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?ho(this.colorNode):Nu;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=ho(s.xyz.mul(ol("color","vec3")),s.a)),e.instanceColor){s=Mo("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=Mo("vec3","vBatchColor").mul(s)}No.assign(s);const i=this.opacityNode?Kn(this.opacityNode):Cu;if(No.a.assign(No.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Kn(this.alphaTestNode):Mu;No.a.lessThanEqual(e).discard()}!0===this.alphaHash&&No.a.lessThan(td(El)).discard(),!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&No.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?ro(0):No.rgb}setupNormal(){return this.normalNode?ro(this.normalNode):Ou}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?lu("envMap","cubeTexture"):lu("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Rc(rc)),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:nc;t.push(new Ac(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);o=Cc(n,t,s,i)}else null!==s&&(o=ro(null!==i?xh(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Ao.assign(ro(r||Eu)),o=o.add(Ao)),o}setupOutput(e,t){if(!0===this.fog){const s=e.fogNode;s&&(Ho.assign(t),t=ho(s))}return 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=js.prototype.toJSON.call(this,e),i=Dr(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 id=new Xi;class rd extends sd{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(id),this.setValues(e)}}const nd=new hr;class od extends sd{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(nd),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Kn(this.offsetNode):sc,t=this.dashScaleNode?Kn(this.dashScaleNode):Ju,s=this.dashSizeNode?Kn(this.dashSizeNode):ec,i=this.gapSizeNode?Kn(this.gapSizeNode):tc;Wo.assign(s),$o.assign(i);const r=Bh(ol("lineDistance").mul(t));(e?r.add(e):r).mod(Wo.add($o)).greaterThan(Wo).discard()}}const ad=new nr;class hd extends sd{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(ad),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Kn(this.opacityNode):Cu;No.assign(ho(zn(Gl).mul(.5).add(.5),e))}}class ld extends rn{static get type(){return"EquirectUVNode"}constructor(e=Pl){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 eo(t,s)}}const ud=jn(ld);class cd extends Ii{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 Si(5,5,5),n=ud(Pl),o=new sd;o.colorNode=pl(t,n,0),o.side=1,o.blending=0;const a=new vi(r,o),h=new Ui;h.add(a),t.minFilter===F&&(t.minFilter=P);const l=new Bi(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 dd=new WeakMap;class pd extends rn{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Zl();const t=new Fi;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Wr}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===S||s===w){if(dd.has(e)){const t=dd.get(e);gd(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new cd(s.height);i.fromEquirectangularTexture(t,e),gd(i.texture,e.mapping),this._cubeTexture=i.texture,dd.set(e,i.texture),e.addEventListener("dispose",md)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function md(e){const t=e.target;t.removeEventListener("dispose",md);const s=dd.get(t);void 0!==s&&(dd.delete(t),s.dispose())}function gd(e,t){t===S?e.mapping=v:t===w&&(e.mapping=T)}const fd=jn(pd);class yd extends Nc{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=fd(this.envNode)}}class bd extends Nc{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Kn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class xd{start(){}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class _d extends xd{constructor(){super()}indirect(e,t,s){const i=e.ambientOcclusion,r=e.reflectedLight,n=s.context.irradianceLightMap;r.indirectDiffuse.assign(ho(0)),n?r.indirectDiffuse.addAssign(n):r.indirectDiffuse.addAssign(ho(1,1,1,0)),r.indirectDiffuse.mulAssign(i),r.indirectDiffuse.mulAssign(No.rgb)}finish(e,t,s){const i=s.material,r=e.outgoingLight,n=s.context.environment;if(n)switch(i.combine){case 0:r.rgb.assign(xh(r.rgb,r.rgb.mul(n.rgb),Fu.mul(Iu)));break;case 1:r.rgb.assign(xh(r.rgb,n.rgb,Fu.mul(Iu)));break;case 2:r.rgb.addAssign(n.rgb.mul(Fu.mul(Iu)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",i.combine)}}}const vd=new Hs;class Td extends sd{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(vd),this.setValues(e)}setupNormal(){return kl}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yd(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new bd(rc)),t}setupOutgoingLight(){return No.rgb}setupLightingModel(){return new _d}}const Sd=Wn((({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))})),wd=Wn((e=>e.diffuseColor.mul(1/Math.PI))),Md=Wn((({dotNH:e})=>jo.mul(Kn(.5)).add(1).mul(Kn(1/Math.PI)).mul(e.pow(jo)))),Nd=Wn((({lightDirection:e})=>{const t=e.add(Fl).normalize(),s=Gl.dot(t).clamp(),i=Fl.dot(t).clamp(),r=Sd({f0:Go,f90:1,dotVH:i}),n=Kn(.25),o=Md({dotNH:s});return r.mul(n).mul(o)}));class Ad extends _d{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=Gl.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(wd({diffuseColor:No.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Nd({lightDirection:e})).mul(Fu))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(wd({diffuseColor:No}))),s.indirectDiffuse.mulAssign(e)}}const Ed=new or;class Cd extends sd{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ed),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yd(t):null}setupLightingModel(){return new Ad(!1)}}const Rd=new ir;class Pd extends sd{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Rd),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yd(t):null}setupLightingModel(){return new Ad}setupVariants(){const e=(this.shininessNode?Kn(this.shininessNode):Au).max(1e-4);jo.assign(e);const t=this.specularNode||Ru;Go.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Bd=Wn((e=>{if(!1===e.geometry.hasAttribute("normal"))return Kn(0);const t=kl.dFdx().abs().max(kl.dFdy().abs());return t.x.max(t.y).max(t.z)})),Fd=Wn((e=>{const{roughness:t}=e,s=Bd();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),Id=Wn((({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 na(.5,r.add(n).max(wa))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Ud=Wn((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(ro(e.mul(s),t.mul(i),o).length()),l=o.mul(ro(e.mul(r),t.mul(n),a).length());return na(.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"}]}),Dd=Wn((({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"}]}),Od=Kn(1/Math.PI),Ld=Wn((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=ro(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return Od.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"}]}),kd=Wn((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||Gl,l=r.pow2(),u=t.add(Fl).normalize(),c=h.dot(t).clamp(),d=h.dot(Fl).clamp(),p=h.dot(u).clamp(),m=Fl.dot(u).clamp();let g,f,y=Sd({f0:s,f90:i,dotVH:m});if(Ln(o)&&(y=Io.mix(y,n)),Ln(a)){const e=ko.dot(t),s=ko.dot(Fl),i=ko.dot(u),r=zo.dot(t),n=zo.dot(Fl),o=zo.dot(u);g=Ud({alphaT:Oo,alphaB:l,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=Ld({alphaT:Oo,alphaB:l,dotNH:p,dotTH:i,dotBH:o})}else g=Id({alpha:l,dotNL:c,dotNV:d}),f=Dd({alpha:l,dotNH:p});return y.mul(g).mul(f)})),zd=Wn((({roughness:e,dotNV:t})=>{const s=ho(-1,-.0275,-.572,.022),i=ho(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 eo(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),Gd=Wn((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=zd({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),Vd=Wn((({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(ro(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"}]}),jd=Wn((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Kn(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Kn(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"}]}),Hd=Wn((({dotNV:e,dotNL:t})=>Kn(1).div(Kn(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Wd=Wn((({lightDirection:e})=>{const t=e.add(Fl).normalize(),s=Gl.dot(e).clamp(),i=Gl.dot(Fl).clamp(),r=Gl.dot(t).clamp(),n=jd({roughness:Fo,dotNH:r}),o=Hd({dotNV:i,dotNL:s});return Bo.mul(n).mul(o)})),$d=Wn((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=eo(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"}]}),qd=Wn((({f:e})=>{const t=e.length();return oh(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Yd=Wn((({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,oh(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"}]}),Xd=Wn((({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=ro().toVar();return Yn(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(mo(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=ro(0).toVar();f.addAssign(Yd({v1:d,v2:p})),f.addAssign(Yd({v1:p,v2:m})),f.addAssign(Yd({v1:m,v2:g})),f.addAssign(Yd({v1:g,v2:d})),c.assign(ro(qd({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"}]}),Kd=1/6,Qd=e=>ra(Kd,ra(e,ra(e,e.negate().add(3)).sub(3)).add(1)),Zd=e=>ra(Kd,ra(e,ra(e,ra(3,e).sub(6))).add(4)),Jd=e=>ra(Kd,ra(e,ra(e,ra(-3,e).add(3)).add(3)).add(1)),ep=e=>ra(Kd,mh(e,3)),tp=e=>Qd(e).add(Zd(e)),sp=e=>Jd(e).add(ep(e)),ip=e=>sa(-1,Zd(e).div(Qd(e).add(Zd(e)))),rp=e=>sa(1,ep(e).div(Jd(e).add(ep(e)))),np=(e,t,s)=>{const i=e.uvNode,r=ra(i,t.zw).add(.5),n=Da(r),o=ka(r),a=tp(o.x),h=sp(o.x),l=ip(o.x),u=rp(o.x),c=ip(o.y),d=rp(o.y),p=eo(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),m=eo(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),g=eo(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),f=eo(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=tp(o.y).mul(sa(a.mul(e.sample(p).level(s)),h.mul(e.sample(m).level(s)))),b=sp(o.y).mul(sa(a.mul(e.sample(g).level(s)),h.mul(e.sample(f).level(s))));return y.add(b)},op=Wn((([e,t=Kn(3)])=>{const s=eo(e.size(Qn(t))),i=eo(e.size(Qn(t.add(1)))),r=na(1,s),n=na(1,i),o=np(e,ho(r,s),Da(t)),a=np(e,ho(n,i),Oa(t));return ka(t).mix(o,a)})),ap=Wn((([e,t,s,i,r])=>{const n=ro(vh(t.negate(),La(e),na(1,i))),o=ro(Ya(r[0].xyz),Ya(r[1].xyz),Ya(r[2].xyz));return La(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"}]}),hp=Wn((([e,t])=>e.mul(_h(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),lp=zc(),up=zc(),cp=Wn((([e,t,s],{material:i})=>{const r=(1===i.side?lp:up).sample(e),n=Fa(Uc.x).mul(hp(t,s));return op(r,n)})),dp=Wn((([e,t,s])=>(Yn(s.notEqual(0),(()=>{const i=Ba(t).negate().div(s);return Ra(i.negate().mul(e))})),ro(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),pp=Wn((([e,t,s,i,r,n,o,a,h,l,u,c,d,p,m])=>{let g,f;if(m){g=ho().toVar(),f=ro().toVar();const r=u.sub(1).mul(m.mul(.025)),n=ro(u.sub(r),u,u.add(r));_c({start:0,end:3},(({i:r})=>{const u=n.element(r),m=ap(e,t,c,u,a),y=o.add(m),b=l.mul(h.mul(ho(y,1))),x=eo(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(eo(x.x,x.y.oneMinus()));const _=cp(x,s,u);g.element(r).assign(_.element(r)),g.a.addAssign(_.a),f.element(r).assign(i.element(r).mul(dp(Ya(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=ap(e,t,c,u,a),n=o.add(r),m=l.mul(h.mul(ho(n,1))),y=eo(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(eo(y.x,y.y.oneMinus())),g=cp(y,s,u),f=i.mul(dp(Ya(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),x=ro(Gd({dotNV:b,specularColor:r,specularF90:n,roughness:s})),_=f.r.add(f.g,f.b).div(3);return ho(x.oneMinus().mul(y),g.a.oneMinus().mul(_).oneMinus())})),mp=mo(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),gp=(e,t)=>e.sub(t).div(e.add(t)).pow2(),fp=Wn((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=xh(e,t,Th(0,.03,i)),o=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();Yn(o.lessThan(0),(()=>ro(1)));const a=o.sqrt(),h=gp(n,e),l=Sd({f0:h,f90:1,dotVH:s}),u=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Kn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return ro(1).add(t).div(ro(1).sub(t))})(r.clamp(0,.9999)),m=gp(p,n.toVec3()),g=Sd({f0:m,f90:1,dotVH:a}),f=ro(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=ro(d).add(f),x=l.mul(g).clamp(1e-5,.9999),_=x.sqrt(),v=u.pow2().mul(g).div(ro(1).sub(x)),T=l.add(v).toVar(),S=v.sub(u).toVar();return _c({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{S.mulAssign(_);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=ro(54856e-17,44201e-17,52481e-17),r=ro(1681e3,1795300,2208400),n=ro(43278e5,93046e5,66121e5),o=Kn(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=ro(a.x.add(o),a.y,a.z).div(1.0685e-7),mp.mul(a)})(Kn(e).mul(y),Kn(e).mul(b)).mul(2);T.addAssign(S.mul(t))})),T.max(ro(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"}]}),yp=Wn((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Nh(s.lessThan(.25),Kn(-339.2).mul(r).add(Kn(161.4).mul(s)).sub(25.9),Kn(-8.48).mul(r).add(Kn(14.3).mul(s)).sub(9.95)),o=Nh(s.lessThan(.25),Kn(44).mul(r).sub(Kn(23.7).mul(s)).add(3.26),Kn(1.97).mul(r).sub(Kn(3.27).mul(s)).add(.72));return Nh(s.lessThan(.25),0,Kn(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),bp=ro(.04),xp=Kn(1);class _p extends xd{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=ro().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=ro().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=ro().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=ro().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=ro().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Gl.dot(Fl).clamp();this.iridescenceFresnel=fp({outsideIOR:Kn(1),eta2:Uo,cosTheta1:e,thinFilmThickness:Do,baseF0:Go}),this.iridescenceF0=Vd({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Rl,s=xl.sub(Rl).normalize(),i=Vl;e.backdrop=pp(i,s,Eo,No,Go,Vo,t,Sl,bl,yl,qo,Xo,Qo,Ko,this.dispersion?Zo:null),e.backdropAlpha=Yo,No.a.mulAssign(xh(1,e.backdrop.a,Yo))}}computeMultiscattering(e,t,s){const i=Gl.dot(Fl).clamp(),r=zd({roughness:Eo,dotNV:i}),n=(this.iridescenceF0?Io.mix(Go,this.iridescenceF0):Go).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=Go.add(Go.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=Gl.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(Wd({lightDirection:e}))),!0===this.clearcoat){const s=jl.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(kd({lightDirection:e,f0:bp,f90:xp,roughness:Po,normalView:jl})))}s.directDiffuse.addAssign(i.mul(wd({diffuseColor:No.rgb}))),s.directSpecular.addAssign(i.mul(kd({lightDirection:e,f0:Go,f90:1,roughness:Eo,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=Gl,d=Fl,p=Bl.toVar(),m=$d({N:c,V:d,roughness:Eo}),g=n.sample(m).toVar(),f=o.sample(m).toVar(),y=mo(ro(g.x,0,g.y),ro(0,1,0),ro(g.z,0,g.w)).toVar(),b=Go.mul(f.x).add(Go.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(b).mul(Xd({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:l,p3:u}))),r.directDiffuse.addAssign(e.mul(No).mul(Xd({N:c,V:d,P:p,mInv:mo(1,0,0,0,1,0,0,0,1),p0:a,p1:h,p2:l,p3:u})))}indirect(e,t,s){this.indirectDiffuse(e,t,s),this.indirectSpecular(e,t,s),this.ambientOcclusion(e,t,s)}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(wd({diffuseColor:No})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(Bo,yp({normal:Gl,viewDir:Fl,roughness:Fo}))),!0===this.clearcoat){const e=jl.dot(Fl).clamp(),t=Gd({dotNV:e,specularColor:bp,specularF90:xp,roughness:Po});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=ro().toVar("singleScattering"),r=ro().toVar("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(i,r,Vo);const o=i.add(r),a=No.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(i)),s.indirectSpecular.addAssign(r.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=Gl.dot(Fl).clamp().add(e),i=Eo.mul(-16).oneMinus().negate().exp2(),r=e.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=jl.dot(Fl).clamp(),s=Sd({dotVH:e,f0:bp,f90:xp}),i=t.mul(Ro.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Ro));t.assign(i)}if(!0===this.sheen){const e=Bo.r.max(Bo.g).max(Bo.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const vp=Kn(1),Tp=Kn(-2),Sp=Kn(.8),wp=Kn(-1),Mp=Kn(.4),Np=Kn(2),Ap=Kn(.305),Ep=Kn(3),Cp=Kn(.21),Rp=Kn(4),Pp=Kn(4),Bp=Kn(16),Fp=Wn((([e])=>{const t=ro($a(e)).toVar(),s=Kn(-1).toVar();return Yn(t.x.greaterThan(t.z),(()=>{Yn(t.x.greaterThan(t.y),(()=>{s.assign(Nh(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Nh(e.y.greaterThan(0),1,4))}))})).Else((()=>{Yn(t.z.greaterThan(t.y),(()=>{s.assign(Nh(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Nh(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Ip=Wn((([e,t])=>{const s=eo().toVar();return Yn(t.equal(0),(()=>{s.assign(eo(e.z,e.y).div($a(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(eo(e.x.negate(),e.z.negate()).div($a(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(eo(e.x.negate(),e.y).div($a(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(eo(e.z.negate(),e.y).div($a(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(eo(e.x.negate(),e.z).div($a(e.y)))})).Else((()=>{s.assign(eo(e.x,e.y).div($a(e.z)))})),ra(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Up=Wn((([e])=>{const t=Kn(0).toVar();return Yn(e.greaterThanEqual(Sp),(()=>{t.assign(vp.sub(e).mul(wp.sub(Tp)).div(vp.sub(Sp)).add(Tp))})).ElseIf(e.greaterThanEqual(Mp),(()=>{t.assign(Sp.sub(e).mul(Np.sub(wp)).div(Sp.sub(Mp)).add(wp))})).ElseIf(e.greaterThanEqual(Ap),(()=>{t.assign(Mp.sub(e).mul(Ep.sub(Np)).div(Mp.sub(Ap)).add(Np))})).ElseIf(e.greaterThanEqual(Cp),(()=>{t.assign(Ap.sub(e).mul(Rp.sub(Ep)).div(Ap.sub(Cp)).add(Ep))})).Else((()=>{t.assign(Kn(-2).mul(Fa(ra(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Dp=Wn((([e,t])=>{const s=e.toVar();s.assign(ra(2,s).sub(1));const i=ro(s,1).toVar();return Yn(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"}]}),Op=Wn((([e,t,s,i,r,n])=>{const o=Kn(s),a=ro(t),h=_h(Up(o),Tp,n),l=ka(h),u=Da(h),c=ro(Lp(e,a,u,i,r,n)).toVar();return Yn(l.notEqual(0),(()=>{const t=ro(Lp(e,a,u.add(1),i,r,n)).toVar();c.assign(xh(c,t,l))})),c})),Lp=Wn((([e,t,s,i,r,n])=>{const o=Kn(s).toVar(),a=ro(t),h=Kn(Fp(a)).toVar(),l=Kn(oh(Pp.sub(o),0)).toVar();o.assign(oh(o,Pp));const u=Kn(Pa(o)).toVar(),c=eo(Ip(a,h).mul(u.sub(2)).add(1)).toVar();return Yn(h.greaterThan(2),(()=>{c.y.addAssign(u),h.subAssign(3)})),c.x.addAssign(h.mul(u)),c.x.addAssign(l.mul(ra(3,Bp))),c.y.addAssign(ra(4,Pa(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(eo(),eo())})),kp=Wn((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=Ga(i),l=s.mul(h).add(r.cross(s).mul(za(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return Lp(e,l,t,n,o,a)})),zp=Wn((({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=ro(Nh(t,s,ph(s,i))).toVar();Yn(Na(d.equals(ro(0))),(()=>{d.assign(ro(i.z,0,i.x.negate()))})),d.assign(La(d));const p=ro().toVar();return p.addAssign(r.element(Qn(0)).mul(kp({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),_c({start:Qn(1),end:e},(({i:e})=>{Yn(e.greaterThanEqual(n),(()=>{il("break").append()}));const t=Kn(o.mul(Kn(e))).toVar();p.addAssign(r.element(e).mul(kp({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(kp({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))})),ho(p,1)}));let Gp=null;const Vp=new WeakMap;function jp(e){let t=Vp.get(e);if((void 0!==t?t.pmremVersion:-1)!==e.pmremVersion){const s=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}(s))return null;t=Gp.fromCubemap(e,t)}else{if(!function(e){return null!=e&&e.height>0}(s))return null;t=Gp.fromEquirectangular(e,t)}t.pmremVersion=e.pmremVersion,Vp.set(e,t)}return t.texture}class Hp extends rn{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 dt;i.isRenderTargetTexture=!0,this._texture=pl(i),this._width=So(0),this._height=So(0),this._maxMip=So(0),this.updateBeforeType=Wr}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(){let e=this._pmrem;const t=e?e.pmremVersion:-1,s=this._value;t!==s.pmremVersion&&(e=!0===s.isPMREMTexture?s:jp(s),null!==e&&(this._pmrem=e,this.updateFromTexture(e)))}setup(e){null===Gp&&(Gp=e.createPMREMGenerator()),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this));const s=this.value;e.renderer.coordinateSystem===Ue&&!0!==s.isPMREMTexture&&!0===s.isRenderTargetTexture&&(t=ro(t.x.negate(),t.yz)),t=ro(t.x,t.y.negate(),t.z);let i=this.levelNode;return null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),Op(this._texture,t,i,this._width,this._height,this._maxMip)}}const Wp=jn(Hp),$p=new WeakMap;class qp extends Nc{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=$p.get(e);void 0===i&&(i=Wp(e),$p.set(e,i)),s=i}const i=t.envMap?ou("envMapIntensity","float",e.material):ou("environmentIntensity","float",e.scene),r=!0===t.useAnisotropy||t.anisotropy>0?gu:Gl,n=s.context(Yp(Eo,r)).mul(i),o=s.context(Xp(Vl)).mul(Math.PI).mul(i),a=Qh(n),h=Qh(o);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(h);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=s.context(Yp(Po,jl)).mul(i),t=Qh(e);l.addAssign(t)}}}const Yp=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=Fl.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(bl)),s),getTextureLevel:()=>e}},Xp=e=>({getUV:()=>e,getTextureLevel:()=>Kn(1)}),Kp=new tr;class Qp 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(Kp),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new qp(t):null}setupLightingModel(){return new _p}setupSpecular(){const e=xh(ro(.04),No.rgb,Co);Go.assign(e),Vo.assign(1)}setupVariants(){const e=this.metalnessNode?Kn(this.metalnessNode):Du;Co.assign(e);let t=this.roughnessNode?Kn(this.roughnessNode):Uu;t=Fd({roughness:t}),Eo.assign(t),this.setupSpecular(),No.assign(ho(No.rgb.mul(e.oneMinus()),No.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Zp=new sr;class Jp extends Qp{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(Zp),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?Kn(this.iorNode):Ku;qo.assign(e),Go.assign(xh(nh(gh(qo.sub(1).div(qo.add(1))).mul(Bu),ro(1)).mul(Pu),No.rgb,Co)),Vo.assign(xh(Pu,1,Co))}setupLightingModel(){return new _p(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Kn(this.clearcoatNode):Lu,t=this.clearcoatRoughnessNode?Kn(this.clearcoatRoughnessNode):ku;Ro.assign(e),Po.assign(Fd({roughness:t}))}if(this.useSheen){const e=this.sheenNode?ro(this.sheenNode):Vu,t=this.sheenRoughnessNode?Kn(this.sheenRoughnessNode):ju;Bo.assign(e),Fo.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Kn(this.iridescenceNode):Wu,t=this.iridescenceIORNode?Kn(this.iridescenceIORNode):$u,s=this.iridescenceThicknessNode?Kn(this.iridescenceThicknessNode):qu;Io.assign(e),Uo.assign(t),Do.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?eo(this.anisotropyNode):Hu).toVar();Lo.assign(e.length()),Yn(Lo.equal(0),(()=>{e.assign(eo(1,0))})).Else((()=>{e.divAssign(eo(Lo)),Lo.assign(Lo.saturate())})),Oo.assign(Lo.pow2().mix(Eo.pow2(),1)),ko.assign(mu[0].mul(e.x).add(mu[1].mul(e.y))),zo.assign(mu[1].mul(e.x).sub(mu[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Kn(this.transmissionNode):Yu,t=this.thicknessNode?Kn(this.thicknessNode):Xu,s=this.attenuationDistanceNode?Kn(this.attenuationDistanceNode):Qu,i=this.attenuationColorNode?ro(this.attenuationColorNode):Zu;if(Yo.assign(e),Xo.assign(t),Ko.assign(s),Qo.assign(i),this.useDispersion){const e=this.dispersionNode?Kn(this.dispersionNode):ic;Zo.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?ro(this.clearcoatNormalNode):zu}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 em=Wn((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=eo(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=lu("gradientMap","texture").context({getUV:()=>r});return ro(e.r)}{const e=r.fwidth().mul(.5);return xh(ro(.7),ro(1),Th(Kn(.7).sub(e.x),Kn(.7).add(e.x),r.x))}}));class tm extends xd{direct({lightDirection:e,lightColor:t,reflectedLight:s},i,r){const n=em({normal:Dl,lightDirection:e,builder:r}).mul(t);s.directDiffuse.addAssign(n.mul(wd({diffuseColor:No.rgb})))}indirect({ambientOcclusion:e,irradiance:t,reflectedLight:s}){s.indirectDiffuse.addAssign(t.mul(wd({diffuseColor:No}))),s.indirectDiffuse.mulAssign(e)}}const sm=new rr;class im extends sd{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(sm),this.setValues(e)}setupLightingModel(){return new tm}}class rm extends rn{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=ro(Fl.z,0,Fl.x.negate()).normalize(),t=Fl.cross(e);return eo(e.dot(Gl),t.dot(Gl)).mul(.495).add(.5)}}const nm=Hn(rm),om=new ar;class am extends sd{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(om),this.setValues(e)}setupVariants(e){const t=nm;let s;s=e.material.matcap?lu("matcap","texture").context({getUV:()=>t}):ro(xh(.2,.8,t.y)),No.rgb.mulAssign(s.rgb)}}const hm=new Ki;class lm extends sd{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.isPointsNodeMaterial=!0,this.setDefaultValues(hm),this.setValues(e)}}class um extends rn{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 po(e,i,i.negate(),e).mul(s)}{const e=t,i=go(ho(1,0,0,0),ho(0,Ga(e.x),za(e.x).negate(),0),ho(0,za(e.x),Ga(e.x),0),ho(0,0,0,1)),r=go(ho(Ga(e.y),0,za(e.y),0),ho(0,1,0,0),ho(za(e.y).negate(),0,Ga(e.y),0),ho(0,0,0,1)),n=go(ho(Ga(e.z),za(e.z).negate(),0,0),ho(za(e.z),Ga(e.z),0,0),ho(0,0,1,0),ho(0,0,0,1));return i.mul(r).mul(n).mul(ho(s,1)).xyz}}}const cm=jn(um),dm=new ki;class pm 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.setDefaultValues(dm),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=Ml.mul(ro(r||0));let h=eo(Sl[0].xyz.length(),Sl[1].xyz.length());if(null!==o&&(h=h.mul(o)),!1===i)if(s.isPerspectiveCamera)h=h.mul(a.z.negate());else{const e=Kn(2).div(yl.element(1).element(1));h=h.mul(e.mul(2))}let l=Al.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>zn(new zh(e,t,s)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(h);const u=Kn(n||Gu),c=cm(l,u);return ho(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)}}class mm extends xd{constructor(){super(),this.shadowNode=Kn(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){No.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(No.rgb)}}const gm=new er;class fm extends sd{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(gm),this.setValues(e)}setupLightingModel(){return new mm}}Wn((({texture:e,uv:t})=>{const s=1e-4,i=ro().toVar();return Yn(t.x.lessThan(s),(()=>{i.assign(ro(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(ro(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(ro(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(ro(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(ro(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(ro(0,0,-1))})).Else((()=>{const s=.01,r=e.sample(t.add(ro(-.01,0,0))).r.sub(e.sample(t.add(ro(s,0,0))).r),n=e.sample(t.add(ro(0,-.01,0))).r.sub(e.sample(t.add(ro(0,s,0))).r),o=e.sample(t.add(ro(0,0,-.01))).r.sub(e.sample(t.add(ro(0,0,s))).r);i.assign(ro(r,n,o))})),i.normalize()}));class ym{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}setAnimationLoop(e){this._animationLoop=e}setContext(e){this._context=e}dispose(){this.stop()}}class bm{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s<e.length;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;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;s++)if(t=t.get(e[s]),void 0===t)return!1;return t.delete(e[e.length-1])}}let xm=0;class _m{constructor(e,t,s,i,r,n,o,a,h,l){this.id=xm++,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.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().monitor)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}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,")}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.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",Br(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=this._nodes.getCacheKey(this.scene,this.lightsNode);return this.object.receiveShadow&&(e+=1),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const vm=[];class Tm{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);vm[0]=e,vm[1]=t,vm[2]=n,vm[3]=r;let l=h.get(vm);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o,a),h.set(vm,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)),l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new bm)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,l,u){const c=this.getChainMap(u),d=new _m(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 Sm{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 wm=1,Mm=2,Nm=3,Am=4,Em=16;class Cm extends Sm{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===wm?this.backend.createAttribute(e):t===Mm?this.backend.createIndexAttribute(e):t===Nm?this.backend.createStorageAttribute(e):t===Am&&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 Rm(e){return null!==e.index?e.index.version:e.attributes.position.version}function Pm(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(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(t)?Js:Zs)(t,1);return r.version=Rm(e),r}class Bm extends Sm{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,Nm):this.updateAttribute(e,wm);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Mm);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Am)}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=Pm(t),e.set(t,s)):s.version!==Rm(t)&&(this.attributes.delete(s),s=Pm(t),e.set(t,s)),i=s}return i}}class Fm{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,previousFrameCalls:0,timestampCalls:0},this.compute={calls:0,frameCalls:0,timestamp:0,previousFrameCalls:0,timestampCalls: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.")}updateTimestamp(e,t){0===this[e].timestampCalls&&(this[e].timestamp=0),this[e].timestamp+=t,this[e].timestampCalls++,this[e].timestampCalls>=this[e].previousFrameCalls&&(this[e].timestampCalls=0)}reset(){const e=this.render.frameCalls;this.render.previousFrameCalls=e;const t=this.compute.frameCalls;this.compute.previousFrameCalls=t,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 Im{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Um extends Im{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Dm extends Im{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Om=0;class Lm{constructor(e,t,s,i=null,r=null){this.id=Om++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class km extends Sm{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 Lm(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 Lm(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 Lm(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 Dm(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 Um(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 zm extends Sm{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?Am:Nm;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.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 Gm(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 Vm(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 jm(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class Hm{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?(jm(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?(jm(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||Gm),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Vm),this.transparent.length>1&&this.transparent.sort(t||Vm)}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}}}class Wm{constructor(e){this.lighting=e,this.lists=new bm}get(e,t){const s=this.lists,i=[e,t];let r=s.get(i);return void 0===r&&(r=new Hm(this.lighting,e,t),s.set(i,r)),r}dispose(){this.lists=new bm}}let $m=0;class qm{constructor(){this.id=$m++,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 pt,this.scissor=!1,this.scissorValue=new pt,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.sampleCount=1,this.width=0,this.height=0,this.isRenderContext=!0}getCacheKey(){return Ym(this)}}function Ym(e){const{textures:t,activeCubeFace:s}=e,i=[s];for(const e of t)i.push(e.id);return Fr(i)}class Xm{constructor(){this.chainMaps={}}get(e=null,t=null,s=null){const i=[];let r;if(null!==e&&i.push(e),null!==t&&i.push(t),0===i.length&&i.push({id:"default"}),null===s)r="default";else{const e=s.texture.format;r=`${s.textures.length}:${e}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this.getChainMap(r);let o=n.get(i);return void 0===o&&(o=new qm,n.set(i,o)),null!==s&&(o.sampleCount=0===s.samples?1:s.samples),o}getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new bm)}dispose(){this.chainMaps={}}}const Km=new bt;class Qm extends Sm{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 Zi,l.format=e.stencilBuffer?$:W,l.type=e.stencilBuffer?V:k,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};for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,d)}if(l&&this.updateTexture(l,d),!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=Km){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===S||t===w||t===v||t===T}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class Zm extends zs{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Jm extends wo{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class eg extends en{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"}add(e){return this.nodes.push(e),this}If(e,t){const s=new kn(t);return this._currentCond=Nh(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new kn(t),i=Nh(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new kn(e),this}build(e,...t){const s=qn();$n(this);for(const t of this.nodes)t.build(e,"void");return $n(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const tg=jn(eg);new Wi,new bt,new bt,new bt,new Yt,new bt(0,0,-1),new pt,new bt,new bt,new pt,new Xe;const sg=new mt;Ic.flipX(),sg.depthTexture=new Zi(1,1);const ig=new Tr(-1,1,1,-1,0,1);class rg extends li{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new ti([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ti(t,2))}}const ng=new rg;class og extends vi{constructor(e=null){super(ng,e),this.camera=ig,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,ig)}render(e){e.render(this,ig)}}const ag=new rs,hg=new Yt;class lg extends en{static get type(){return"SceneNode"}constructor(e=lg.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===lg.BACKGROUND_BLURRINESS?i=ou("backgroundBlurriness","float",s):t===lg.BACKGROUND_INTENSITY?i=ou("backgroundIntensity","float",s):t===lg.BACKGROUND_ROTATION?i=So("mat4").label("backgroundRotation").setGroup(_o).onRenderUpdate((()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(ag.copy(s.backgroundRotation),ag.x*=-1,ag.y*=-1,ag.z*=-1,hg.makeRotationFromEuler(ag)):hg.identity(),hg})):console.error("THREE.SceneNode: Unknown scope:",t),i}}lg.BACKGROUND_BLURRINESS="backgroundBlurriness",lg.BACKGROUND_INTENSITY="backgroundIntensity",lg.BACKGROUND_ROTATION="backgroundRotation";const ug=Hn(lg,lg.BACKGROUND_BLURRINESS),cg=Hn(lg,lg.BACKGROUND_INTENSITY),dg=Hn(lg,lg.BACKGROUND_ROTATION),pg=new Xe;class mg extends dl{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 gg extends mg{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 fg extends rn{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 Zi;r.isRenderTargetTexture=!0,r.name="depth";const n=new mt(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:G,...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=So(0),this._cameraFar=So(0),this._mrt=null,this.isPassNode=!0,this.updateBeforeType=Hr}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 gg(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 gg(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=qc(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=Wc(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.scope===fg.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(pg);this.setSize(r.width,r.height);const n=t.getRenderTarget(),o=t.getMRT();this._cameraNear.value=i.near,this._cameraFar.value=i.far;for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(n),t.setMRT(o)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}fg.COLOR="color",fg.DEPTH="depth";const yg=Wn((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),bg=Wn((([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"}]}),xg=Wn((([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"}]}),_g=Wn((([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)})),vg=Wn((([e,t])=>{const s=mo(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=mo(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=_g(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Tg=mo(ro(1.6605,-.1246,-.0182),ro(-.5876,1.1329,-.1006),ro(-.0728,-.0083,1.1187)),Sg=mo(ro(.6274,.0691,.0164),ro(.3293,.9195,.088),ro(.0433,.0113,.8956)),wg=Wn((([e])=>{const t=ro(e).toVar(),s=ro(t.mul(t)).toVar(),i=ro(s.mul(s)).toVar();return Kn(15.5).mul(i.mul(s)).sub(ra(40.14,i.mul(t))).add(ra(31.96,i).sub(ra(6.868,s.mul(t))).add(ra(.4298,s).add(ra(.1191,t).sub(.00232))))})),Mg=Wn((([e,t])=>{const s=ro(e).toVar(),i=mo(ro(.856627153315983,.137318972929847,.11189821299995),ro(.0951212405381588,.761241990602591,.0767994186031903),ro(.0482516061458583,.101439036467562,.811302368396859)),r=mo(ro(1.1271005818144368,-.1413297634984383,-.14132976349843826),ro(-.11060664309660323,1.157823702216272,-.11060664309660294),ro(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Kn(-12.47393),o=Kn(4.026069);return s.mulAssign(t),s.assign(Sg.mul(s)),s.assign(i.mul(s)),s.assign(oh(s,1e-10)),s.assign(Fa(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(_h(s,0,1)),s.assign(wg(s)),s.assign(r.mul(s)),s.assign(mh(oh(ro(0),s),ro(2.2))),s.assign(Tg.mul(s)),s.assign(_h(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ng=Wn((([e,t])=>{const s=Kn(.76),i=Kn(.15);e=e.mul(t);const r=nh(e.r,nh(e.g,e.b)),n=Nh(r.lessThan(.08),r.sub(ra(6.25,r.mul(r))),.04);e.subAssign(n);const o=oh(e.r,oh(e.g,e.b));Yn(o.lessThan(s),(()=>e));const a=ia(1,s),h=ia(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const l=ia(1,na(1,i.mul(o.sub(h)).add(1)));return xh(e,ro(h),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Ag extends en{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 Eg extends Ag{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 Cg(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||Bl.z).negate()}const Rg=Wn((([e,t],s)=>{const i=Cg(s);return Th(e,t,i)})),Pg=Wn((([e],t)=>{const s=Cg(t);return e.mul(e,s,s).negate().exp().oneMinus()})),Bg=Wn((([e,t])=>ho(t.toFloat().mix(Ho.rgb,e.toVec3()),Ho.a)));jn(class extends en{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 Fg extends rn{static get type(){return"AtomicFunctionNode"}constructor(e,t,s,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.storeNode=i}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)}`),o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${a}`,this)}else e.addLineFlowCode(a,this)}}let Ig;function Ug(e){Ig=Ig||new WeakMap;let t=Ig.get(e);return void 0===t&&Ig.set(e,t={}),t}function Dg(e){const t=Ug(e);return t.shadowMatrix||(t.shadowMatrix=So("mat4").setGroup(_o).onRenderUpdate((()=>(!0!==e.castShadow&&e.shadow.updateMatrices(e),e.shadow.matrix))))}function Og(e){const t=Ug(e);return t.position||(t.position=So(new bt).setGroup(_o).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function Lg(e){const t=Ug(e);return t.viewPosition||(t.viewPosition=So(new bt).setGroup(_o).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new bt,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}Fg.ATOMIC_LOAD="atomicLoad",Fg.ATOMIC_STORE="atomicStore",Fg.ATOMIC_ADD="atomicAdd",Fg.ATOMIC_SUB="atomicSub",Fg.ATOMIC_MAX="atomicMax",Fg.ATOMIC_MIN="atomicMin",Fg.ATOMIC_AND="atomicAnd",Fg.ATOMIC_OR="atomicOr",Fg.ATOMIC_XOR="atomicXor",jn(Fg);const kg=e=>bl.transformDirection(Og(e).sub(function(e){const t=Ug(e);return t.targetPosition||(t.targetPosition=So(new bt).setGroup(_o).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}(e))),zg=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Gg=new WeakMap;class Vg extends en{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=ro().toVar("totalDiffuse"),this.totalSpecularNode=ro().toVar("totalSpecular"),this.outgoingLightNode=ro().toVar("outgoingLight"),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 Fr(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=zg(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;Gg.has(e)?i=Gg.get(e):(i=zn(new s(e)),Gg.set(e,i)),t.push(i)}}this._lightNodes=t}setupLights(e,t){for(const s of t)s.build(e)}setup(e){null===this._lightNodes&&this.setupLightsNode(e);const t=e.context,s=t.lightingModel;let i=this.outgoingLightNode;if(s){const{_lightNodes:r,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=i;const a=e.addStack();e.getDataFromNode(this).nodes=a.nodes,s.start(t,a,e),this.setupLights(e,r),s.indirect(t,a,e);const{backdrop:h,backdropAlpha:l}=t,{directDiffuse:u,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=u.add(d);null!==h&&(m=ro(null!==l?l.mix(m,h):h),t.material.transparent=!0),n.assign(m),o.assign(c.add(p)),i.assign(n.add(o)),s.finish(t,a,e),i=i.bypass(e.removeStack())}return i}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 jg extends en{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Wr,this.isShadowBaseNode=!0}setupShadowPosition({material:e}){Hg.assign(e.shadowPositionNode||Rl)}dispose(){this.updateBeforeType=jr}}const Hg=ro().toVar("shadowPositionWorld");function Wg(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new zs),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const $g=new WeakMap,qg=Wn((([e,t,s])=>{let i=Rl.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i})),Yg=e=>{let t=$g.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=ou("near","float",t).setGroup(_o),i=ou("far","float",t).setGroup(_o),r=vl(e);return qg(r,s,i)})(e):null;t=new sd,t.colorNode=ho(0,0,0,1),t.depthNode=s,t.isShadowNodeMaterial=!0,t.name="ShadowMaterial",t.fog=!1,$g.set(e,t)}return t},Xg=Wn((({depthTexture:e,shadowCoord:t})=>pl(e,t.xy).compare(t.z))),Kg=Wn((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>pl(e,t).compare(s),r=ou("mapSize","vec2",s).setGroup(_o),n=ou("radius","float",s).setGroup(_o),o=eo(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 sa(i(t.xy.add(eo(a,h)),t.z),i(t.xy.add(eo(0,h)),t.z),i(t.xy.add(eo(l,h)),t.z),i(t.xy.add(eo(c,d)),t.z),i(t.xy.add(eo(0,d)),t.z),i(t.xy.add(eo(p,d)),t.z),i(t.xy.add(eo(a,0)),t.z),i(t.xy.add(eo(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(eo(p,0)),t.z),i(t.xy.add(eo(l,0)),t.z),i(t.xy.add(eo(c,m)),t.z),i(t.xy.add(eo(0,m)),t.z),i(t.xy.add(eo(p,m)),t.z),i(t.xy.add(eo(a,u)),t.z),i(t.xy.add(eo(0,u)),t.z),i(t.xy.add(eo(l,u)),t.z)).mul(1/17)})),Qg=Wn((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>pl(e,t).compare(s),r=ou("mapSize","vec2",s).setGroup(_o),n=eo(1).div(r),o=n.x,a=n.y,h=t.xy,l=ka(h.mul(r).add(.5));return h.subAssign(l.mul(n)),sa(i(h,t.z),i(h.add(eo(o,0)),t.z),i(h.add(eo(0,a)),t.z),i(h.add(n),t.z),xh(i(h.add(eo(o.negate(),0)),t.z),i(h.add(eo(o.mul(2),0)),t.z),l.x),xh(i(h.add(eo(o.negate(),a)),t.z),i(h.add(eo(o.mul(2),a)),t.z),l.x),xh(i(h.add(eo(0,a.negate())),t.z),i(h.add(eo(0,a.mul(2))),t.z),l.y),xh(i(h.add(eo(o,a.negate())),t.z),i(h.add(eo(o,a.mul(2))),t.z),l.y),xh(xh(i(h.add(eo(o.negate(),a.negate())),t.z),i(h.add(eo(o.mul(2),a.negate())),t.z),l.x),xh(i(h.add(eo(o.negate(),a.mul(2))),t.z),i(h.add(eo(o.mul(2),a.mul(2))),t.z),l.x),l.y)).mul(1/9)})),Zg=Wn((({depthTexture:e,shadowCoord:t})=>{const s=Kn(1).toVar(),i=pl(e).sample(t.xy).rg,r=hh(t.z,i.x);return Yn(r.notEqual(Kn(1)),(()=>{const e=t.z.sub(i.x),n=oh(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=_h(ia(o,.3).div(.95-.3)),s.assign(_h(oh(r,o)))})),s})),Jg=Wn((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Kn(0).toVar(),n=Kn(0).toVar(),o=e.lessThanEqual(Kn(1)).select(Kn(0),Kn(2).div(e.sub(1))),a=e.lessThanEqual(Kn(1)).select(Kn(0),Kn(-1));_c({start:Qn(0),end:Qn(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Kn(e).mul(o)),l=i.sample(sa(Dc.xy,eo(0,h).mul(t)).div(s)).x;r.addAssign(l),n.addAssign(l.mul(l))})),r.divAssign(e),n.divAssign(e);const h=Ia(n.sub(r.mul(r)));return eo(r,h)})),ef=Wn((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=Kn(0).toVar(),n=Kn(0).toVar(),o=e.lessThanEqual(Kn(1)).select(Kn(0),Kn(2).div(e.sub(1))),a=e.lessThanEqual(Kn(1)).select(Kn(0),Kn(-1));_c({start:Qn(0),end:Qn(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(Kn(e).mul(o)),l=i.sample(sa(Dc.xy,eo(h,0).mul(t)).div(s));r.addAssign(l.x),n.addAssign(sa(l.y.mul(l.y),l.x.mul(l.x)))})),r.divAssign(e),n.divAssign(e);const h=Ia(n.sub(r.mul(r)));return eo(r,h)})),tf=[Xg,Kg,Qg,Zg];let sf;const rf=new og;class nf extends jg{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.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,Kn(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=ou("bias","float",s).setGroup(_o);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=ou("near","float",s.camera).setGroup(_o),i=ou("far","float",s.camera).setGroup(_o);n=Yc(e.negate(),t,i)}return o=ro(o.x,o.y.oneMinus(),n.add(r)),o}getShadowFilterFn(e){return tf[e]}setupShadow(e){const{renderer:t}=e,{light:s,shadow:i}=this,r=t.shadowMap.type,n=new Zi(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:X,type:G}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:X,type:G});const t=pl(n),s=pl(this.vsmShadowMapVertical.texture),r=ou("blurSamples","float",i).setGroup(_o),o=ou("radius","float",i).setGroup(_o),a=ou("mapSize","vec2",i).setGroup(_o);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new sd);h.fragmentNode=Jg({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new sd),h.fragmentNode=ef({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=ou("intensity","float",i).setGroup(_o),h=ou("normalBias","float",i).setGroup(_o),l=Dg(s).mul(Hg.add(Vl.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=pl(o.texture,u),g=xh(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 Wn((()=>{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");sf=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=Wg(e,s)),s}(r,n,sf),n.overrideMaterial=Yg(s),r.setRenderObjectFunction(((e,t,s,n,h,l,...u)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&(c&&(Gr(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,sf)}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),rf.material=this.vsmMaterialVertical,rf.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),rf.material=this.vsmMaterialHorizontal,rf.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;(t.needsUpdate||t.autoUpdate)&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}class of extends Nc{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new zs,this.colorNode=e&&e.colorNode||So(this.color).setGroup(_o),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Hr}customCacheKey(){return Ir(this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}setupShadowNode(){return((e,t)=>zn(new nf(e,t)))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const t=this.light.shadow.shadowNode;let i;i=void 0!==t?zn(t):this.setupShadowNode(e),this.shadowNode=i,this.shadowColorNode=s=this.colorNode.mul(i),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)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const af=Wn((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return s.greaterThan(0).select(r.mul(t.div(s).pow4().oneMinus().clamp().pow2()),r)})),hf=new zs,lf=Wn((([e,t])=>{const s=e.toVar(),i=$a(s),r=na(1,oh(i.x,oh(i.y,i.z)));i.mulAssign(r),s.mulAssign(r.mul(t.mul(2).oneMinus()));const n=eo(s.xy).toVar(),o=t.mul(1.5).oneMinus();return Yn(i.z.greaterThanEqual(o),(()=>{Yn(s.z.greaterThan(0),(()=>{n.x.assign(ia(4,s.x))}))})).ElseIf(i.x.greaterThanEqual(o),(()=>{const e=qa(s.x);n.x.assign(s.z.mul(e).add(e.mul(2)))})).ElseIf(i.y.greaterThanEqual(o),(()=>{const e=qa(s.y);n.x.assign(s.x.add(e.mul(2)).add(2)),n.y.assign(s.z.mul(e).sub(2))})),eo(.125,.25).mul(n).add(eo(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),uf=Wn((({depthTexture:e,bd3D:t,dp:s,texelSize:i})=>pl(e,lf(t,i.y)).compare(s))),cf=Wn((({depthTexture:e,bd3D:t,dp:s,texelSize:i,shadow:r})=>{const n=ou("radius","float",r).setGroup(_o),o=eo(-1,1).mul(n).mul(i.y);return pl(e,lf(t.add(o.xyy),i.y)).compare(s).add(pl(e,lf(t.add(o.yyy),i.y)).compare(s)).add(pl(e,lf(t.add(o.xyx),i.y)).compare(s)).add(pl(e,lf(t.add(o.yyx),i.y)).compare(s)).add(pl(e,lf(t,i.y)).compare(s)).add(pl(e,lf(t.add(o.xxy),i.y)).compare(s)).add(pl(e,lf(t.add(o.yxy),i.y)).compare(s)).add(pl(e,lf(t.add(o.xxx),i.y)).compare(s)).add(pl(e,lf(t.add(o.yxx),i.y)).compare(s)).mul(1/9)})),df=Wn((({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),o=So("float").setGroup(_o).onRenderUpdate((()=>i.camera.near)),a=So("float").setGroup(_o).onRenderUpdate((()=>i.camera.far)),h=ou("bias","float",i).setGroup(_o),l=So(i.mapSize).setGroup(_o),u=Kn(1).toVar();return Yn(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=eo(1).div(l.mul(eo(4,2)));u.assign(e({depthTexture:t,bd3D:c,dp:s,texelSize:d,shadow:i}))})),u})),pf=new pt,mf=new Xe,gf=new Xe;class ff extends nf{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?uf:cf}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:r,shadow:n}){return df({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();gf.copy(t.mapSize),gf.multiply(o),s.setSize(gf.width,gf.height),mf.copy(t.mapSize);const a=r.autoClear,h=r.getClearColor(hf),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=mf.x*o.x,h=gf.y-mf.y-mf.y*o.y;pf.set(a,h,mf.x*o.z,mf.y*o.w),s.viewport.copy(pf),t.updateMatrices(i,e),r.render(n,t.camera)}r.autoClear=a,r.setClearColor(h,l)}}const yf=Wn((({color:e,lightViewPosition:t,cutoffDistance:s,decayExponent:i},r)=>{const n=r.context.lightingModel,o=t.sub(Bl),a=o.normalize(),h=o.length(),l=af({lightDistance:h,cutoffDistance:s,decayExponent:i}),u=e.mul(l),c=r.context.reflectedLight;n.direct({lightDirection:a,lightColor:u,reflectedLight:c},r.stack,r)}));class bf extends of{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=So(0).setGroup(_o),this.decayExponentNode=So(2).setGroup(_o)}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 ff(e,t)))(this.light)}setup(e){super.setup(e),yf({color:this.colorNode,lightViewPosition:Lg(this.light),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode}).append()}}const xf=Wn((([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(ra(s,s).sub(ra(i,i)))),n})),_f=new Zm;class vf extends Sm{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(_f,ve),_f.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(_f,ve),_f.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;_f.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Eh(ho(n).mul(cg),{getUV:()=>dg.mul(zl),getTextureLevel:()=>ug});let t=ac;t=t.setZ(t.w);const i=new sd;i.name="Background.material",i.side=1,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new vi(new Ji(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=ho(n).mul(cg),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);if(!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=_f.r,e.g=_f.g,e.b=_f.b,e.a=_f.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 Tf=0;class Sf{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=Tf++}}class wf{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.monitor=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new Sf(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 Mf{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class Nf{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 Af{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class Ef extends Af{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class Cf{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let Rf=0;class Pf{constructor(e=null){this.id=Rf++,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 Bf extends en{static get type(){return"StructTypeNode"}constructor(e,t){super(),this.name=e,this.types=t,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}class Ff{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 If extends Ff{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class Uf extends Ff{constructor(e,t=new Xe){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Df extends Ff{constructor(e,t=new bt){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Of extends Ff{constructor(e,t=new pt){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class Lf extends Ff{constructor(e,t=new zs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class kf extends Ff{constructor(e,t=new Ke){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class zf extends Ff{constructor(e,t=new Yt){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Gf extends If{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Vf extends Uf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class jf extends Df{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Hf extends Of{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Wf extends Lf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $f extends kf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class qf extends zf{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Yf=[.125,.215,.35,.446,.526,.582],Xf=20,Kf=new Tr(-1,1,1,-1,0,1),Qf=new Ri(90,1),Zf=new zs;let Jf=null,ey=0,ty=0;const sy=(1+Math.sqrt(5))/2,iy=1/sy,ry=[new bt(-sy,iy,0),new bt(sy,iy,0),new bt(-iy,0,sy),new bt(iy,0,sy),new bt(0,sy,-iy),new bt(0,sy,iy),new bt(-1,1,-1),new bt(1,1,-1),new bt(-1,1,1),new bt(1,1,1)],ny=[3,1,5,0,4,2],oy=Dp(al(),ol("faceIndex")).normalize(),ay=ro(oy.x,oy.y,oy.z);class hy{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=null){if(this._setSize(256),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=r||this._allocateTargets();return this.fromSceneAsync(e,t,s,i,n),n}Jf=this._renderer.getRenderTarget(),ey=this._renderer.getActiveCubeFace(),ty=this._renderer.getActiveMipmapLevel();const n=r||this._allocateTargets();return n.depthBuffer=!0,this._sceneToCubeUV(e,s,i,n),t>0&&this._blur(n,0,0,t),this._applyPMREM(n),this._cleanup(n),n}async fromSceneAsync(e,t=0,s=.1,i=100,r=null){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=dy(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=py(),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(Jf,ey,ty),e.scissorTest=!1,uy(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Jf=this._renderer.getRenderTarget(),ey=this._renderer.getActiveCubeFace(),ty=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:G,format:H,colorSpace:ve},i=ly(e,t,s);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=ly(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+Yf.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=Yf[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=ny[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 li;v.setAttribute("position",new Qs(b,g)),v.setAttribute("uv",new Qs(x,f)),v.setAttribute("faceIndex",new Qs(_,y)),t.push(v),r.push(new vi(v,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=iu(new Array(Xf).fill(0)),r=So(new bt(0,1,0)),n=So(0),o=Kn(Xf),a=So(0),h=So(1),l=pl(null),u=So(0),c=Kn(1/t),d=Kn(1/s),p=Kn(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:ay,dTheta:n,samples:h,envMap:l,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=cy("blur");return g.uniforms=m,g.fragmentNode=zp({...m,latitudinal:a.equal(1)}),g}(i,e,t)}return i}async _compileMaterial(e){const t=new vi(this._lodPlanes[0],e);await this._renderer.compile(t,Kf)}_sceneToCubeUV(e,t,s,i){const r=Qf;r.near=t,r.far=s;const n=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],a=this._renderer,h=a.autoClear;a.getClearColor(Zf),a.autoClear=!1;let l=this._backgroundBox;if(null===l){const e=new Hs({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});l=new vi(new Si,e)}let u=!1;const c=e.background;c?c.isColor&&(l.material.color.copy(c),e.background=null,u=!0):(l.material.color.copy(Zf),u=!0),a.setRenderTarget(i),a.clear(),u&&a.render(l,r);for(let t=0;t<6;t++){const s=t%3;0===s?(r.up.set(0,n[t],0),r.lookAt(o[t],0,0)):1===s?(r.up.set(0,0,n[t]),r.lookAt(0,o[t],0)):(r.up.set(0,n[t],0),r.lookAt(0,0,o[t]));const h=this._cubeSize;uy(i,s*h,t>2?h:0,h,h),a.render(e,r)}a.autoClear=h,e.background=c}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===v||e.mapping===T;i?null===this._cubemapMaterial&&(this._cubemapMaterial=dy(e)):null===this._equirectMaterial&&(this._equirectMaterial=py(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;uy(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,Kf)}_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=ry[(i-t-1)%ry.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=h.uniforms,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):Xf;m>Xf&&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<Xf;++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];uy(t,3*b*(i>y-4?i-y+4:0),4*(this._cubeSize-b),3*b,2*b),a.setRenderTarget(t),a.render(l,Kf)}}function ly(e,t,s){const i=new mt(e,t,s);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function uy(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function cy(e){const t=new sd;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function dy(e){const t=cy("cubemap");return t.fragmentNode=Zl(e,ay),t}function py(e){const t=cy("equirect");return t.fragmentNode=pl(e,ud(ay),0),t}const my=new WeakMap,gy=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),fy=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class yy{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.monitor=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.flow={code:""},this.chaining=[],this.stack=tg(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Pf,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=my.get(this.renderer);return void 0===e&&(e=new bm,my.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new mt(e,t,s)}createCubeRenderTarget(e,t){return new cd(e,t)}createPMREMGenerator(){return new hy(this.renderer)}includes(e){return this.nodes.includes(e)}_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 Sf(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new Sf(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 Qr)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===B||e.magFilter===R||e.magFilter===F||e.minFilter===P||e.minFilter===B||e.minFilter===R||e.minFilter===F}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 Pf(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.")}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new zs:"vec2"===e?t=new Xe:"vec3"===e?t=new bt:"vec4"===e&&(t=new pt)),"float"===e)return fy(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")}( ${fy(t.r)}, ${fy(t.g)}, ${fy(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)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>4&&t&&(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 Mf(e,t);return 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||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===L)return"int";if(t===k)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;const s=function(e){return Or.get(e)}(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return gy.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof ei||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){return this.stack=tg(this.stack),this.stacks.push(qn()||this.stack),$n(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,$n(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 Mf("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e,s);let r=i.structType;if(void 0===r){const e=this.structs.index++;r=new Bf("StructType"+e,t),this.structs[s].push(r),i.structType=r}return r}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 Nf(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let n=r.variable;if(void 0===n){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),n=new Af(t,s),e.push(n),r.variable=n}return n}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 Ef(t,s),e.push(r),i.varying=r}return r}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 Cf("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}buildFunctionNode(e){const t=new Eg,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 Jm(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.cache,n=this.buildStage,o=this.stack,a={code:""};this.flow=a,this.vars={},this.cache=new Pf,this.stack=tg();for(const s of Kr)this.setBuildStage(s),a.result=e.build(this,t);return a.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.cache=r,this.stack=o,this.setBuildStage(n),a}getFunctionOperator(){return null}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){return`${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 Kr){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Qr){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 Gf(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Vf(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new jf(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new Hf(e);if("color"===t)return new Wf(e);if("mat3"===t)return new $f(e);if("mat4"===t)return new qf(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 by{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===Hr){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===Wr){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===$r&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Hr){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===Wr){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===$r&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Hr){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===Wr){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===$r&&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 xy{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}xy.isNodeFunctionInput=!0;class _y extends of{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,i=kg(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:s,reflectedLight:r},e.stack,e)}}const vy=new Yt,Ty=new Yt;let Sy=null;class wy extends of{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=So(new bt).setGroup(_o),this.halfWidth=So(new bt).setGroup(_o),this.updateType=Wr}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;Ty.identity(),vy.copy(t.matrixWorld),vy.premultiply(s),Ty.extractRotation(vy),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(Ty),this.halfHeight.value.applyMatrix4(Ty)}setup(e){let t,s;super.setup(e),e.isAvailable("float32Filterable")?(t=pl(Sy.LTC_FLOAT_1),s=pl(Sy.LTC_FLOAT_2)):(t=pl(Sy.LTC_HALF_1),s=pl(Sy.LTC_HALF_2));const{colorNode:i,light:r}=this,n=e.context.lightingModel,o=Lg(r),a=e.context.reflectedLight;n.directRectArea({lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,reflectedLight:a,ltc_1:t,ltc_2:s},e.stack,e)}static setLTC(e){Sy=e}}class My extends of{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=So(0).setGroup(_o),this.penumbraCosNode=So(0).setGroup(_o),this.cutoffDistanceNode=So(0).setGroup(_o),this.decayExponentNode=So(0).setGroup(_o)}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 Th(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:i,decayExponentNode:r,light:n}=this,o=Lg(n).sub(Bl),a=o.normalize(),h=a.dot(kg(n)),l=this.getSpotAttenuation(h),u=o.length(),c=af({lightDistance:u,cutoffDistance:i,decayExponent:r});let d=s.mul(l).mul(c);if(n.map){const e=function(e){const t=Ug(e);if(void 0===t.projectionUV){const s=Dg(e).mul(Rl);t.projectionUV=s.xyz.div(s.w)}return t.projectionUV}(n),t=pl(n.map,e.xy).onRenderUpdate((()=>n.map));d=e.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(t),d)}const p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:d,reflectedLight:p},e.stack,e)}}class Ny extends My{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=pl(t,eo(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class Ay extends of{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class Ey extends of{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Og(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=So(new zs).setGroup(_o)}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=kl.dot(i).mul(.5).add(.5),n=xh(s,t,r);e.context.irradiance.addAssign(n)}}class Cy extends of{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new bt);this.lightProbe=iu(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=xf(zl,this.lightProbe);e.context.irradiance.addAssign(t)}}class Ry{parseFunction(){console.warn("Abstract function.")}}class Py{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}Py.isNodeFunction=!0;const By=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Fy=/[a-z_0-9]+/gi,Iy="#pragma main";class Uy extends Py{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(Iy),s=-1!==t?e.slice(t+12):e,i=s.match(By);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=Fy.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 xy(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 Dy extends Ry{parseFunction(e){return new Uy(e)}}const Oy=new WeakMap;class Ly extends Sm{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new by,this.nodeBuilderCache=new Map,this.callHashCache=new bm,this.groupsData=new bm,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===vo.name)return!0;if(s===_o.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===xo.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}const i=[t,e];let r=this.groupsData.get(i);return void 0===r&&this.groupsData.set(i,r={}),r.version!==t.version&&(r.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 wf(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.monitor,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){const s=[e,t],i=this.renderer.info.calls;let r=this.callHashCache.get(s);if(void 0===r||r.callId!==i){const n=this.getEnvironmentNode(e),o=this.getFogNode(e),a=[];t&&a.push(t.getCacheKey(!0)),n&&a.push(n.getCacheKey()),o&&a.push(o.getCacheKey()),a.push(this.renderer.shadowMap.enabled?1:0),r={callId:i,cacheKey:Fr(a)},this.callHashCache.set(s,r)}return r.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===S||s.mapping===w||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return Wp(s);{let e;return e=!0===s.isCubeTexture?Zl(s):pl(s),fd(e)}}if(!0===s.isTexture)return pl(s,Ic.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=ou("color","color",s).setGroup(_o),t=ou("density","float",s).setGroup(_o);return Bg(e,Pg(t))}if(s.isFog){const e=ou("color","color",s).setGroup(_o),t=ou("near","float",s).setGroup(_o),i=ou("far","float",s).setGroup(_o);return Bg(e,Rg(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?Zl(s):!0===s.isTexture?pl(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 Oy.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=pl(e,Ic).renderOutput(t.toneMapping,t.currentColorSpace);return Oy.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 by,this.nodeBuilderCache=new Map,this.cacheLib={}}}const ky=new Wi;class zy{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++){ky.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=ky.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=ky.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowNodeMaterial,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 pt;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 zy(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class Gy{constructor(e,t){this.bundleGroup=e,this.camera=t}}class Vy{constructor(){this.bundles=new bm}get(e,t){const s=this.bundles,i=[e,t];let r=s.get(i);return void 0===r&&(r=new Gy(e,t),s.set(i,r)),r}dispose(){this.bundles=new bm}}class jy{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 Hy=new Vg;class Wy extends bm{constructor(){super()}createNode(e=[]){return(new Vg).setLights(e)}getNode(e,t){if(e.isQuadMesh)return Hy;const s=[e,t];let i=this.get(s);return void 0===i&&(i=this.createNode(),this.set(s,i)),i}}const $y=new Ui,qy=new Xe,Yy=new pt,Xy=new Yi,Ky=new Yt,Qy=new pt;class Zy{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}=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 Fm,this.nodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new jy,this.lighting=new Wy,this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new pt(0,0,this._width,this._height),this._scissor=new pt(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 og(new sd),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const l=!0===this.alpha?0:1;this._clearColor=new Zm(0,0,0,l),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr={enabled:!1},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 Ly(this,s),this._animation=new ym(this._nodes,this.info),this._attributes=new Cm(s),this._background=new vf(this,this._nodes),this._geometries=new Bm(this._attributes,this.info),this._textures=new Qm(this,s,this.info),this._pipelines=new km(s,this._nodes),this._bindings=new zm(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Tm(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Wm(this.lighting),this._bundles=new Vy,this._renderContexts=new Xm,this._animation.start(),this._initialized=!0,e()}))),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:$y;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 zy),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();const s=this._renderScene(e,t);await this.backend.resolveTimestampAsync(s,"render")}async waitForGPU(){await this.backend.waitForGPU()}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}_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 e=n.opaque;!0===this.opaque&&e.length>0&&this._renderObjects(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(qy),{depth:r,stencil:n}=this;let o=this._frameBufferTarget;return null===o&&(o=new mt(s,i,{depthBuffer:r,stencilBuffer:n,type:G,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:$y,l=this._renderTarget,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;t.coordinateSystem!==m&&(t.coordinateSystem=m,t.updateProjectionMatrix()),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld();let g=this._viewport,f=this._scissor,y=this._pixelRatio;null!==d&&(g=d.viewport,f=d.scissor,y=1),this.getDrawingBufferSize(qy),Yy.set(0,0,qy.width,qy.height);const b=void 0===g.minDepth?0:g.minDepth,x=void 0===g.maxDepth?1:g.maxDepth;p.viewportValue.copy(g).multiplyScalar(y).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=b,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(Yy),p.scissorValue.copy(f).multiplyScalar(y).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Yy),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new zy),p.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,d),Ky.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),Xy.setFromProjectionMatrix(Ky,m);const _=this._renderLists.get(e,t);if(_.begin(),this._projectObject(e,t,0,_,p.clippingContext),_.finish(),!0===this.sortObjects&&_.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=_.occlusionQueryCount,this._background.update(h,_,p),this.backend.beginRender(p);const{bundles:v,lightsNode:T,transparentDoublePass:S,transparent:w,opaque:M}=_;if(v.length>0&&this._renderBundles(v,h,T),!0===this.opaque&&M.length>0&&this._renderObjects(M,t,h,T),!0===this.transparent&&w.length>0&&this._renderTransparents(w,S,t,h,T),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i){this.setRenderTarget(l,u,c);const e=this._quad;this._nodes.hasOutputChange(d.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(d.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}return h.onAfterRender(this,e,t,d),p}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._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._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.get(null,null,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}if(this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget){const e=this._quad;this._nodes.hasOutputChange(i.texture)&&(e.material.fragmentNode=this._nodes.getOutputNode(i.texture),e.material.needsUpdate=!0),this._renderScene(e,e.camera,!1)}}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 null!==this._renderTarget?0:this.toneMapping}get currentColorSpace(){return null!==this._renderTarget?ve:this.outputColorSpace}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(),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}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),await this.backend.resolveTimestampAsync(e,"compute")}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(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=Qy.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=Qy.copy(t).floor()}else t=Qy.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){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r)}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||Xy.intersectsSprite(e)){!0===this.sortObjects&&Qy.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Ky);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,Qy.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||Xy.intersectsObject(e))){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Qy.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(Ky)),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,Qy.z,h,r)}}else n.visible&&i.push(e,t,n,s,Qy.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 o=e[n],{object:a,geometry:h,material:l,group:u,clippingContext:c}=o;if(t.isArrayCamera){const e=t.cameras;for(let t=0,n=e.length;t<n;t++){const n=e[t];if(a.layers.test(n.layers)){const e=n.viewport,t=void 0===e.minDepth?0:e.minDepth,o=void 0===e.maxDepth?1:e.maxDepth,d=this._currentRenderContext.viewportValue;d.copy(e).multiplyScalar(this._pixelRatio).floor(),d.minDepth=t,d.maxDepth=o,this.backend.updateViewport(this._currentRenderContext),this._currentRenderObjectFunction(a,s,n,h,l,u,i,c,r)}}}else this._currentRenderObjectFunction(a,s,t,h,l,u,i,c,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),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.isShadowNodeMaterial&&(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 Jy{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class eb extends Jy{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)+(Em-e%Em)%Em;var e}get buffer(){return this._buffer}update(){return!0}}class tb extends eb{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let sb=0;class ib extends tb{constructor(e,t){super("UniformBuffer_"+sb++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class rb extends tb{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%Em;0!==n&&Em-n-i<0?e+=Em-n:n%i!=0&&(e+=n%i),s.offset=e/this.bytesPerElement,e+=r*this.bytesPerElement}return Math.ceil(e/Em)*Em}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 nb=0;class ob extends rb{constructor(e,t){super(e),this.id=nb++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let ab=0;class hb extends Jy{constructor(e,t){super(e),this.id=ab++,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 lb extends hb{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 ub extends lb{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class cb extends lb{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const db={textureDimensions:"textureSize",equals:"equal"},pb={low:"lowp",medium:"mediump",high:"highp"},mb={swizzleAssign:!0,storageBuffer:!1},gb="\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 fb extends yy{constructor(e,t){super(e,t,new Dy),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]},this.useComparisonMethod=!0}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==xe}getMethod(e){return db[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?Y:q;2===i?n=r?K:X:3===i?n=r?1032:j:4===i&&(n=r?Q:H);const o={Float32Array:z,Uint8Array:I,Uint16Array:O,Uint32Array:k,Int8Array:U,Int16Array:D,Int32Array:L,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 zi(t.array,a,h,n,o[t.array.constructor.name]||z);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new dl(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="."+Zr.join("").slice(0,u),d=`ivec2(${o} % ${l}, ${o} / ${l})`,p=this.generateTextureLoad(null,n,d,null,"0");let m="vec4";i.pbo.type===k?m="uvec4":i.pbo.type===L&&(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)};`);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){const e=r.node.value;let s="";!0===e.isDataTexture&&(e.type===k?s="u":e.type===L&&(s="i")),t=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("texture3D"===r.type)t=`sampler3D ${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=pb[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!==L){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=[],s=e.getMemberTypes();for(let e=0;e<s.length;e++){const i=s[e];t.push(`layout( location = ${e} ) out ${i} m${e};`)}return t.join("\n")}getStructs(e){const t=[],s=this.structs[e];if(0===s.length)return"layout( location = 0 ) out vec4 fragColor;\n";for(let e=0,i=s.length;e<i;e++){const i=s[e];let r="\n";r+=this.getStructMembers(i),r+="\n",t.push(r)}return t.join("\n\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);t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}${i.needsInterpolation?"out":"/*out*/"} ${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=mb[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)}mb[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);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${gb}\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${gb}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\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 lb(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new ub(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new cb(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 ib(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 ob(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let yb=null,bb=null;class xb{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}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(){}copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampAsync(){}async waitForGPU(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return yb=yb||new Xe,this.renderer.getDrawingBufferSize(yb)}setScissorTest(){}getClearColor(){const e=this.renderer;return bb=bb||new Zm,e.getClearColor(bb),bb.getRGB(bb,this.renderer.currentColorSpace),bb}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Ze("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 _b=0;class vb{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 Tb{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===L,id:_b++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new vb(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}}let Sb,wb,Mb=!1;class Nb{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.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},!1===Mb&&(this._init(this.gl),Mb=!0)}_init(e){Sb={[a]:e.FUNC_ADD,[h]:e.FUNC_SUBTRACT,[l]:e.FUNC_REVERSE_SUBTRACT},wb={[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}}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(Sb[t],Sb[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(wb[s],wb[i],wb[n],wb[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}}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)}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 Ab{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===U)return s.BYTE;if(e===D)return s.SHORT;if(e===O)return s.UNSIGNED_SHORT;if(e===L)return s.INT;if(e===k)return s.UNSIGNED_INT;if(e===z)return s.FLOAT;if(e===G)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===Y)return s.RED_INTEGER;if(e===X)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===V?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 Eb,Cb,Rb,Pb=!1;class Bb{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===Pb&&(this._init(this.gl),Pb=!0)}_init(e){Eb={[M]:e.REPEAT,[N]:e.CLAMP_TO_EDGE,[A]:e.MIRRORED_REPEAT},Cb={[E]:e.NEAREST,[C]:e.NEAREST_MIPMAP_NEAREST,[R]:e.NEAREST_MIPMAP_LINEAR,[P]:e.LINEAR,[B]:e.LINEAR_MIPMAP_NEAREST,[F]:e.LINEAR_MIPMAP_LINEAR},Rb={[Me]:e.NEVER,[Be]:e.ALWAYS,[Ne]:e.LESS,[Ee]:e.LEQUAL,[Ae]:e.EQUAL,[Pe]:e.GEQUAL,[Ce]:e.GREATER,[Re]:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===E||e===C||e===R?t.NEAREST:t.LINEAR}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_INT&&(a=n.DEPTH24_STENCIL8),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,Eb[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,Eb[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,Eb[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Cb[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===P&&n?F:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Cb[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,Rb[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===E)return;if(t.minFilter!==R&&t.minFilter!==F)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){const{gl:n,backend:o}=this,{state:a}=this.backend,{textureGPU:h,glTextureType:l,glType:u,glFormat:c}=o.get(t);let d,p,m,g,f,y;null!==s?(d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=s.min.x,g=s.min.y):(d=e.image.width,p=e.image.height,m=0,g=0),null!==i?(f=i.x,y=i.y):(f=0,y=0),a.bindTexture(l,h),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment);const b=n.getParameter(n.UNPACK_ROW_LENGTH),x=n.getParameter(n.UNPACK_IMAGE_HEIGHT),_=n.getParameter(n.UNPACK_SKIP_PIXELS),v=n.getParameter(n.UNPACK_SKIP_ROWS),T=n.getParameter(n.UNPACK_SKIP_IMAGES),S=e.isCompressedTexture?e.mipmaps[r]:e.image;if(n.pixelStorei(n.UNPACK_ROW_LENGTH,S.width),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,S.height),n.pixelStorei(n.UNPACK_SKIP_PIXELS,m),n.pixelStorei(n.UNPACK_SKIP_ROWS,g),e.isRenderTargetTexture||e.isDepthTexture){const s=o.get(e),i=o.get(t),r=o.get(s.renderTarget),h=o.get(i.renderTarget),l=r.framebuffers[s.cacheKey],u=h.framebuffers[i.cacheKey];a.bindFramebuffer(n.READ_FRAMEBUFFER,l),a.bindFramebuffer(n.DRAW_FRAMEBUFFER,u);let c=n.COLOR_BUFFER_BIT;e.isDepthTexture&&(c=n.DEPTH_BUFFER_BIT),n.blitFramebuffer(m,g,d,p,f,y,d,p,c,n.NEAREST),a.bindFramebuffer(n.READ_FRAMEBUFFER,null),a.bindFramebuffer(n.DRAW_FRAMEBUFFER,null)}else e.isDataTexture?n.texSubImage2D(n.TEXTURE_2D,r,f,y,d,p,c,u,S.data):e.isCompressedTexture?n.compressedTexSubImage2D(n.TEXTURE_2D,r,f,y,S.width,S.height,c,S.data):n.texSubImage2D(n.TEXTURE_2D,r,f,y,d,p,c,u,S);n.pixelStorei(n.UNPACK_ROW_LENGTH,b),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,x),n.pixelStorei(n.UNPACK_SKIP_PIXELS,_),n.pixelStorei(n.UNPACK_SKIP_ROWS,v),n.pixelStorei(n.UNPACK_SKIP_IMAGES,T),0===r&&t.generateMipmaps&&n.generateMipmap(n.TEXTURE_2D),a.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){const{gl:s}=this,i=t.renderTarget,{samples:r,depthTexture:n,depthBuffer:o,stencilBuffer:a,width:h,height:l}=i;if(s.bindRenderbuffer(s.RENDERBUFFER,e),o&&!a){let t=s.DEPTH_COMPONENT24;r>0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,r,t,h,l)):s.renderbufferStorage(s.RENDERBUFFER,t,h,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(r>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,h,l):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,h,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.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 Fb{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 Ib{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 Ub={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 Db{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,i,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,r,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,r,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,n,1)}}}class Ob extends xb{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.trackTimestamp=!0===e.trackTimestamp,this._currentContext=null,this._knownBindings=new WeakSet}init(e){super.init(e);const t=this.parameters,s=void 0!==t.context?t.context:e.domElement.getContext("webgl2");function i(t){t.preventDefault();const s={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(s)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new Fb(this),this.capabilities=new Ib(this),this.attributeUtils=new Tb(this),this.textureUtils=new Bb(this),this.bufferRenderer=new Db(this),this.state=new Nb(this),this.utils=new Ab(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 Ue}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=this.get(e);if(this.queryRunning)return t.queryQueue||(t.queryQueue=[]),void t.queryQueue.push(e);t.activeQuery&&(this.gl.endQuery(this.disjoint.TIME_ELAPSED_EXT),t.activeQuery=null),t.activeQuery=this.gl.createQuery(),null!==t.activeQuery&&(this.gl.beginQuery(this.disjoint.TIME_ELAPSED_EXT,t.activeQuery),this.queryRunning=!0)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=this.get(e);if(t.activeQuery&&(this.gl.endQuery(this.disjoint.TIME_ELAPSED_EXT),t.gpuQueries||(t.gpuQueries=[]),t.gpuQueries.push({query:t.activeQuery}),t.activeQuery=null,this.queryRunning=!1,t.queryQueue&&t.queryQueue.length>0)){const e=t.queryQueue.shift();this.initTimestampQuery(e)}}async resolveTimestampAsync(e,t="render"){if(!this.disjoint||!this.trackTimestamp)return;const s=this.get(e);s.gpuQueries||(s.gpuQueries=[]);for(let e=0;e<s.gpuQueries.length;e++){const i=s.gpuQueries[e],r=this.gl.getQueryParameter(i.query,this.gl.QUERY_RESULT_AVAILABLE),n=this.gl.getParameter(this.disjoint.GPU_DISJOINT_EXT);if(r&&!n){const r=this.gl.getQueryParameter(i.query,this.gl.QUERY_RESULT),n=Number(r)/1e6;this.gl.deleteQuery(i.query),s.gpuQueries.splice(e,1),e--,this.renderer.info.updateTimestamp(t,n)}}}getContext(){return this.gl}beginRender(e){const{gl:t}=this,s=this.get(e);if(this.initTimestampQuery(e),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1),e.viewport?this.updateViewport(e):t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight),e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext,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){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),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),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray)}}null!==r&&(this._setFramebuffer(r),r.viewport?this.updateViewport(r):t.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)&&(r.getQueryParameter(n,r.QUERY_RESULT)>0&&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 t=this.gl,{x:s,y:i,width:r,height:n}=e.viewportValue;t.viewport(s,e.height-n-i,r,n)}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST)}clear(e,t,s,i=null,r=!0){const{gl:n}=this;if(null===i){const e=this.getClearColor();e.r*=e.a,e.g*=e.a,e.b*=e.a,i={textures:null,clearColorValue:e}}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 a;if(i.clearColorValue?a=i.clearColorValue:(a=this.getClearColor(),a.r*=a.a,a.g*=a.a,a.b*=a.a),t&&this.state.setDepthMask(!0),null===i.textures)n.clearColor(a.r,a.g,a.b,a.a),n.clear(o);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)n.clearBufferfv(n.COLOR,e,[a.r,a.g,a.b,a.a]);t&&s?n.clearBufferfi(n.DEPTH_STENCIL,0,1,0):t?n.clearBufferfv(n.DEPTH,0,[1]):s&&n.clearBufferiv(n.STENCIL,0,[0])}}}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(null,h),u=this.vaoCache[l];void 0===u?this._createVao(null,h):n.bindVertexArray(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.getIndex(),e.getAttributes());if(p=this.vaoCache[t],void 0===p){let t;({vaoGPU:p,staticVao:t}=this._createVao(e.getIndex(),e.getAttributes())),t&&(d.staticVao=p,d.geometryId=e.geometry.id)}}a.bindVertexArray(p);const m=e.getIndex(),g=l.lastOcclusionObject;if(g!==t&&void 0!==g){if(null!==g&&!0===g.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 f=this.bufferRenderer;t.isPoints?f.mode=a.POINTS:t.isLineSegments?f.mode=a.LINES:t.isLine?f.mode=a.LINE_STRIP:t.isLineLoop?f.mode=a.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),f.mode=a.LINES):f.mode=a.TRIANGLES;const{vertexCount:y,instanceCount:b}=u;let{firstVertex:x}=u;if(f.object=t,null!==m){x*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);f.index=m.count,f.type=e.type}else f.index=0;var _;t.isBatchedMesh?null!==t._multiDrawInstances?f.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances):this.hasFeature("WEBGL_multi_draw")?f.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):(_="THREE.WebGLRenderer: WEBGL_multi_draw not supported.")in Je||(Je[_]=!0,console.warn(_)):b>1?f.renderInstances(x,y,b):f.render(x,y),a.bindVertexArray(null)}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)}copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new fb(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(Ub).filter((t=>Ub[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){this.textureUtils.copyTextureToTexture(e,t,s,i,r)}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;let d=n.msaaFrameBuffer,p=n.depthRenderbuffer;const m=Ym(e);let g;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),g=n.cubeFramebuffers[m]):(n.framebuffers||(n.framebuffers={}),g=n.framebuffers[m]),void 0===g){g=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,g);const i=e.textures;if(l){n.cubeFramebuffers[m]=g;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[m]=g;for(let s=0;s<i.length;s++){const r=i[s],n=this.get(r);n.renderTarget=e.renderTarget,n.cacheKey=m;const o=t.COLOR_ATTACHMENT0+s;if(u||c){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,o,n.textureGPU,0,e)}else t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0)}s.drawBuffers(e,g)}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=m,t.framebufferTexture2D(t.FRAMEBUFFER,i,t.TEXTURE_2D,s.textureGPU,0)}}if(o>0){if(void 0===d){const i=[];d=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,d);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=d,n.msaaRenderbuffers=r,void 0===p){p=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(p,e),n.depthRenderbuffer=p;const s=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=g}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e,t){let s="";if(null!==e){s+=":"+this.get(e).id}for(let e=0;e<t.length;e++){s+=":"+this.get(t[e]).id}return s}_createVao(e,t){const{gl:s}=this,i=s.createVertexArray();let r="",n=!0;if(s.bindVertexArray(i),null!==e){const t=this.get(e);s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t.bufferGPU),r+=":"+t.id}for(let e=0;e<t.length;e++){const i=t[e],o=this.get(i);let a,h;r+=":"+o.id,s.bindBuffer(s.ARRAY_BUFFER,o.bufferGPU),s.enableVertexAttribArray(e),(i.isStorageBufferAttribute||i.isStorageInstancedBufferAttribute)&&(n=!1),!0===i.isInterleavedBufferAttribute?(a=i.data.stride*o.bytesPerElement,h=i.offset*o.bytesPerElement):(a=0,h=0),o.isInteger?s.vertexAttribIPointer(e,i.itemSize,o.type,a,h):s.vertexAttribPointer(e,i.itemSize,o.type,i.normalized,a,h),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?s.vertexAttribDivisor(e,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&s.vertexAttribDivisor(e,i.data.meshPerAttribute)}return s.bindBuffer(s.ARRAY_BUFFER,null),this.vaoCache[r]=i,{vaoGPU:i,staticVao:n}}_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)}}dispose(){this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Lb="point-list",kb="line-list",zb="line-strip",Gb="triangle-list",Vb="triangle-strip",jb="never",Hb="less",Wb="equal",$b="less-equal",qb="greater",Yb="not-equal",Xb="greater-equal",Kb="always",Qb="store",Zb="load",Jb="clear",ex="ccw",tx="none",sx="front",ix="back",rx="uint16",nx="uint32",ox={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10uFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Stencil8:"stencil8",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},ax="clamp-to-edge",hx="repeat",lx="mirror-repeat",ux="linear",cx="nearest",dx="zero",px="one",mx="src",gx="one-minus-src",fx="src-alpha",yx="one-minus-src-alpha",bx="dst",xx="one-minus-dst",_x="dst-alpha",vx="one-minus-dst-alpha",Tx="src-alpha-saturated",Sx="constant",wx="one-minus-constant",Mx="add",Nx="subtract",Ax="reverse-subtract",Ex="min",Cx="max",Rx=0,Px=15,Bx="keep",Fx="zero",Ix="replace",Ux="invert",Dx="increment-clamp",Ox="decrement-clamp",Lx="increment-wrap",kx="decrement-wrap",zx="storage",Gx="read-only-storage",Vx="write-only",jx="read-only",Hx="read-write",Wx="float",$x="unfilterable-float",qx="depth",Yx="sint",Xx="uint",Kx="2d",Qx="3d",Zx="2d",Jx="2d-array",e_="cube",t_="3d",s_="all",i_="vertex",r_="instance",n_={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 o_ extends Jy{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class a_ extends o_{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class h_ extends eb{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let l_=0;class u_ extends h_{constructor(e,t){super("StorageBuffer_"+l_++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Xr,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class c_ extends Sm{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:ux}),this.flipYSampler=e.createSampler({minFilter:cx}),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:Vb,stripIndexFormat:nx},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:Vb,stripIndexFormat:nx},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:Zx,baseArrayLayer:s}),u=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:Zx,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:Jb,storeOp:Qb,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:Zx,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:Zx,baseArrayLayer:s}),u={colorAttachments:[{view:l,loadOp:Jb,storeOp:Qb,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 d_={[Me]:"never",[Ne]:"less",[Ae]:"equal",[Ee]:"less-equal",[Ce]:"greater",[Pe]:"greater-equal",[Be]:"always",[Re]:"not-equal"},p_=[0,1,3,2,4,5];class m_{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new Zi,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===ux&&r.minFilter===ux&&r.mipmapFilter===ux&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=d_[e.compareFunction]),i.sampler=s.createSampler(r)}createDefaultTexture(e){let t;const s=g_(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||g_(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."),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=V):e&&(a=W,h=k),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===S||t===w||t===v||t===T}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new dt;s.minFilter=E,s.magFilter=E,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 Fi;s.minFilter=E,s.magFilter=E,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?p_[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},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,s,i)}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new c_(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===ox.BC1RGBAUnorm||e===ox.BC1RGBAUnormSRGB?{byteLength:8,width:4,height:4}:e===ox.BC2RGBAUnorm||e===ox.BC2RGBAUnormSRGB||e===ox.BC3RGBAUnorm||e===ox.BC3RGBAUnormSRGB?{byteLength:16,width:4,height:4}:e===ox.BC4RUnorm||e===ox.BC4RSNorm?{byteLength:8,width:4,height:4}:e===ox.BC5RGUnorm||e===ox.BC5RGSnorm||e===ox.BC6HRGBUFloat||e===ox.BC6HRGBFloat||e===ox.BC7RGBAUnorm||e===ox.BC7RGBAUnormSRGB?{byteLength:16,width:4,height:4}:e===ox.ETC2RGB8Unorm||e===ox.ETC2RGB8UnormSRGB||e===ox.ETC2RGB8A1Unorm||e===ox.ETC2RGB8A1UnormSRGB?{byteLength:8,width:4,height:4}:e===ox.ETC2RGBA8Unorm||e===ox.ETC2RGBA8UnormSRGB?{byteLength:16,width:4,height:4}:e===ox.EACR11Unorm||e===ox.EACR11Snorm?{byteLength:8,width:4,height:4}:e===ox.EACRG11Unorm||e===ox.EACRG11Snorm||e===ox.ASTC4x4Unorm||e===ox.ASTC4x4UnormSRGB?{byteLength:16,width:4,height:4}:e===ox.ASTC5x4Unorm||e===ox.ASTC5x4UnormSRGB?{byteLength:16,width:5,height:4}:e===ox.ASTC5x5Unorm||e===ox.ASTC5x5UnormSRGB?{byteLength:16,width:5,height:5}:e===ox.ASTC6x5Unorm||e===ox.ASTC6x5UnormSRGB?{byteLength:16,width:6,height:5}:e===ox.ASTC6x6Unorm||e===ox.ASTC6x6UnormSRGB?{byteLength:16,width:6,height:6}:e===ox.ASTC8x5Unorm||e===ox.ASTC8x5UnormSRGB?{byteLength:16,width:8,height:5}:e===ox.ASTC8x6Unorm||e===ox.ASTC8x6UnormSRGB?{byteLength:16,width:8,height:6}:e===ox.ASTC8x8Unorm||e===ox.ASTC8x8UnormSRGB?{byteLength:16,width:8,height:8}:e===ox.ASTC10x5Unorm||e===ox.ASTC10x5UnormSRGB?{byteLength:16,width:10,height:5}:e===ox.ASTC10x6Unorm||e===ox.ASTC10x6UnormSRGB?{byteLength:16,width:10,height:6}:e===ox.ASTC10x8Unorm||e===ox.ASTC10x8UnormSRGB?{byteLength:16,width:10,height:8}:e===ox.ASTC10x10Unorm||e===ox.ASTC10x10UnormSRGB?{byteLength:16,width:10,height:10}:e===ox.ASTC12x10Unorm||e===ox.ASTC12x10UnormSRGB?{byteLength:16,width:12,height:10}:e===ox.ASTC12x12Unorm||e===ox.ASTC12x12UnormSRGB?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=ax;return e===M?t=hx:e===A&&(t=lx),t}_convertFilterMode(e){let t=ux;return e!==E&&e!==C&&e!==R||(t=cx),t}_getBytesPerTexel(e){return e===ox.R8Unorm||e===ox.R8Snorm||e===ox.R8Uint||e===ox.R8Sint?1:e===ox.R16Uint||e===ox.R16Sint||e===ox.R16Float||e===ox.RG8Unorm||e===ox.RG8Snorm||e===ox.RG8Uint||e===ox.RG8Sint?2:e===ox.R32Uint||e===ox.R32Sint||e===ox.R32Float||e===ox.RG16Uint||e===ox.RG16Sint||e===ox.RG16Float||e===ox.RGBA8Unorm||e===ox.RGBA8UnormSRGB||e===ox.RGBA8Snorm||e===ox.RGBA8Uint||e===ox.RGBA8Sint||e===ox.BGRA8Unorm||e===ox.BGRA8UnormSRGB||e===ox.RGB9E5UFloat||e===ox.RGB10A2Unorm||e===ox.RG11B10UFloat||e===ox.Depth32Float||e===ox.Depth24Plus||e===ox.Depth24PlusStencil8||e===ox.Depth32FloatStencil8?4:e===ox.RG32Uint||e===ox.RG32Sint||e===ox.RG32Float||e===ox.RGBA16Uint||e===ox.RGBA16Sint||e===ox.RGBA16Float?8:e===ox.RGBA32Uint||e===ox.RGBA32Sint||e===ox.RGBA32Float?16:void 0}_getTypedArrayType(e){return e===ox.R8Uint?Uint8Array:e===ox.R8Sint?Int8Array:e===ox.R8Unorm?Uint8Array:e===ox.R8Snorm?Int8Array:e===ox.RG8Uint?Uint8Array:e===ox.RG8Sint?Int8Array:e===ox.RG8Unorm?Uint8Array:e===ox.RG8Snorm?Int8Array:e===ox.RGBA8Uint?Uint8Array:e===ox.RGBA8Sint?Int8Array:e===ox.RGBA8Unorm?Uint8Array:e===ox.RGBA8Snorm?Int8Array:e===ox.R16Uint?Uint16Array:e===ox.R16Sint?Int16Array:e===ox.RG16Uint?Uint16Array:e===ox.RG16Sint?Int16Array:e===ox.RGBA16Uint?Uint16Array:e===ox.RGBA16Sint?Int16Array:e===ox.R16Float||e===ox.RG16Float||e===ox.RGBA16Float?Uint16Array:e===ox.R32Uint?Uint32Array:e===ox.R32Sint?Int32Array:e===ox.R32Float?Float32Array:e===ox.RG32Uint?Uint32Array:e===ox.RG32Sint?Int32Array:e===ox.RG32Float?Float32Array:e===ox.RGBA32Uint?Uint32Array:e===ox.RGBA32Sint?Int32Array:e===ox.RGBA32Float?Float32Array:e===ox.BGRA8Unorm||e===ox.BGRA8UnormSRGB?Uint8Array:e===ox.RGB10A2Unorm||e===ox.RGB9E5UFloat||e===ox.RG11B10UFloat?Uint32Array:e===ox.Depth32Float?Float32Array:e===ox.Depth24Plus||e===ox.Depth24PlusStencil8?Uint32Array:e===ox.Depth32FloatStencil8?Float32Array:void 0}_getDimension(e){let t;return t=e.isData3DTexture?Qx:Kx,t}}function g_(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?ox.BC1RGBAUnormSRGB:ox.BC1RGBAUnorm;break;case ee:n=r===_e?ox.BC2RGBAUnormSRGB:ox.BC2RGBAUnorm;break;case te:n=r===_e?ox.BC3RGBAUnormSRGB:ox.BC3RGBAUnorm;break;case se:n=r===_e?ox.ETC2RGB8UnormSRGB:ox.ETC2RGB8Unorm;break;case ie:n=r===_e?ox.ETC2RGBA8UnormSRGB:ox.ETC2RGBA8Unorm;break;case re:n=r===_e?ox.ASTC4x4UnormSRGB:ox.ASTC4x4Unorm;break;case ne:n=r===_e?ox.ASTC5x4UnormSRGB:ox.ASTC5x4Unorm;break;case oe:n=r===_e?ox.ASTC5x5UnormSRGB:ox.ASTC5x5Unorm;break;case ae:n=r===_e?ox.ASTC6x5UnormSRGB:ox.ASTC6x5Unorm;break;case he:n=r===_e?ox.ASTC6x6UnormSRGB:ox.ASTC6x6Unorm;break;case le:n=r===_e?ox.ASTC8x5UnormSRGB:ox.ASTC8x5Unorm;break;case ue:n=r===_e?ox.ASTC8x6UnormSRGB:ox.ASTC8x6Unorm;break;case ce:n=r===_e?ox.ASTC8x8UnormSRGB:ox.ASTC8x8Unorm;break;case de:n=r===_e?ox.ASTC10x5UnormSRGB:ox.ASTC10x5Unorm;break;case pe:n=r===_e?ox.ASTC10x6UnormSRGB:ox.ASTC10x6Unorm;break;case me:n=r===_e?ox.ASTC10x8UnormSRGB:ox.ASTC10x8Unorm;break;case ge:n=r===_e?ox.ASTC10x10UnormSRGB:ox.ASTC10x10Unorm;break;case fe:n=r===_e?ox.ASTC12x10UnormSRGB:ox.ASTC12x10Unorm;break;case ye:n=r===_e?ox.ASTC12x12UnormSRGB:ox.ASTC12x12Unorm;break;case H:n=r===_e?ox.RGBA8UnormSRGB:ox.RGBA8Unorm;break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case H:switch(i){case U:n=ox.RGBA8Snorm;break;case D:n=ox.RGBA16Sint;break;case O:n=ox.RGBA16Uint;break;case k:n=ox.RGBA32Uint;break;case L:n=ox.RGBA32Sint;break;case I:n=r===_e?ox.RGBA8UnormSRGB:ox.RGBA8Unorm;break;case G:n=ox.RGBA16Float;break;case z:n=ox.RGBA32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case j:if(35902===i)n=ox.RGB9E5UFloat;else console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",i);break;case q:switch(i){case U:n=ox.R8Snorm;break;case D:n=ox.R16Sint;break;case O:n=ox.R16Uint;break;case k:n=ox.R32Uint;break;case L:n=ox.R32Sint;break;case I:n=ox.R8Unorm;break;case G:n=ox.R16Float;break;case z:n=ox.R32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case X:switch(i){case U:n=ox.RG8Snorm;break;case D:n=ox.RG16Sint;break;case O:n=ox.RG16Uint;break;case k:n=ox.RG32Uint;break;case L:n=ox.RG32Sint;break;case I:n=ox.RG8Unorm;break;case G:n=ox.RG16Float;break;case z:n=ox.RG32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case W:switch(i){case O:n=ox.Depth16Unorm;break;case k:n=ox.Depth24Plus;break;case z:n=ox.Depth32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case $:switch(i){case V:n=ox.Depth24PlusStencil8;break;case z:t&&!1===t.features.has(n_.Depth32FloatStencil8)&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),n=ox.Depth32FloatStencil8;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case Y:switch(i){case L:n=ox.R32Sint;break;case k:n=ox.R32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case K:switch(i){case L:n=ox.RG32Sint;break;case k:n=ox.RG32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Q:switch(i){case L:n=ox.RGBA32Sint;break;case k:n=ox.RGBA32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}return n}const f_=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,y_=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,b_={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 x_ extends Py{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(f_);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=y_.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=b_[r]),n.push(new xy(r,t))}const o=e.substring(t[0].length),a=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:b_[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 __ extends Ry{parseFunction(e){return new x_(e)}}const v_="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},T_={[qr]:"read",[Yr]:"write",[Xr]:"read_write"},S_={[M]:"repeat",[N]:"clamp",[A]:"mirror"},w_={vertex:v_?v_.VERTEX:1,fragment:v_?v_.FRAGMENT:2,compute:v_?v_.COMPUTE:4},M_={instance:!0,swizzleAssign:!1,storageBuffer:!0},N_={"^^":"tsl_xor"},A_={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>"},E_={},C_={tsl_xor:new Ag("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Ag("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Ag("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Ag("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Ag("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Ag("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Ag("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Ag("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 Ag("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 Ag("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Ag("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 Ag("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Ag("\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")},R_={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)&&(C_.pow_float=new Ag("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),C_.pow_vec2=new Ag("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 ) ); }",[C_.pow_float]),C_.pow_vec3=new Ag("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 ) ); }",[C_.pow_float]),C_.pow_vec4=new Ag("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 ) ); }",[C_.pow_float]),R_.pow_float="tsl_pow_float",R_.pow_vec2="tsl_pow_vec2",R_.pow_vec3="tsl_pow_vec3",R_.pow_vec4="tsl_pow_vec4");let P_="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(P_+="diagnostic( off, derivative_uniformity );\n");class B_ extends yy{constructor(e,t){super(e,t,new __),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_${S_[e.wrapS]}S_${S_[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let s=E_[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(C_.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===N?(i.push(C_.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===A?(i.push(C_.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",E_[t]=s=new Ag(n,i)}return s.build(this),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 Ch(new sl(`textureDimensions( ${n} )`,o)),i.dimensionsSnippet[s]=r,(e.isDataArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Ch(new sl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Ch(new sl("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===E&&e.magFilter===E||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?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=N_[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?qr:e.access}getStorageAccess(e,t){return T_[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 i;const o=e.groupNode,a=o.name,h=this.getBindGroupArray(a,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let n=null;const a=this.getNodeAccess(e,s);if("texture"===t||"storageTexture"===t?n=new lb(r.name,r.node,o,a):"cubeTexture"===t?n=new ub(r.name,r.node,o,a):"texture3D"===t&&(n=new cb(r.name,r.node,o,a)),n.store=!0===e.isStorageTextureNode,n.setVisibility(w_[s]),"fragment"!==s&&"compute"!==s||!1!==this.isUnfilterable(e.value)||!1!==n.store)h.push(n),i=[n];else{const e=new a_(`${r.name}_sampler`,r.node,o);e.setVisibility(w_[s]),h.push(e,n),i=[e,n]}}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const r=new("buffer"===t?ib:u_)(e,o);r.setVisibility(w_[s]),h.push(r),i=r}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new ob(a,o),n.setVisibility(w_[s]),e[a]=n,h.push(n)),i=this.getNodeUniform(r,t),n.addUniform(i)}n.uniformGPU=i}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","id","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=[],s=e.getMemberTypes();for(let e=0;e<s.length;e++){const i=s[e];t.push(`\t@location( ${e} ) m${e} : ${i}<f32>`)}const i=this.getBuiltins("output");return i&&t.push("\t"+i),t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,i=s.length;e<i;e++){const i=s[e],r=i.name;let n=`struct ${r} {\n`;n+=this.getStructMembers(i),n+="\n}",t.push(n),t.push(`\nvar<private> output : ${r};\n\n`)}return t.join("\n\n")}getVar(e,t){return`var ${t} : ${this.getType(e)}`}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)};`);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}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<${g_(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.bufferType),n=t.bufferCount,a=n>0&&"buffer"===r.type?", "+n:"",h=t.isAtomic?`atomic<${s}>`:`${s}`,l=`\t${r.name} : array< ${h}${a} >\n`,u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+t.id,l,u,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){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\t`),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.nodeType,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;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}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 A_[e]||e}isAvailable(e){let t=M_[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),M_[e]=t),t}_getWGSLMethod(e){return void 0!==C_[e]&&this._include(e),R_[e]}_include(e){const t=C_[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// 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${P_}\n\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\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// 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 = id.x + id.y * numWorkgroups.x * u32(${t}) + id.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 F_{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=ox.Depth24PlusStencil8:e.depth&&(t=ox.Depth24Plus),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?Lb:e.isLineSegments||e.isMesh&&!0===t.wireframe?kb:e.isLine?zb:e.isMesh?Gb: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(){return navigator.userAgent.includes("Quest")?ox.BGRA8Unorm:navigator.gpu.getPreferredCanvasFormat()}}const I_=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),U_=new Map([[ei,["float16"]]]),D_=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class O_{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&&(a.constructor===Int16Array||a.constructor===Uint16Array)){const e=new Uint32Array(a.length);for(let t=0;t<a.length;t++)e[t]=a[t];a=e}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}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).buffer,n=t.array,o=this._isTypedArray(n),a=t.updateRanges;if(0===a.length)i.queue.writeBuffer(r,0,n,0);else{const e=o?1:n.BYTES_PER_ELEMENT;for(let t=0,s=a.length;t<s;t++){const s=a[t],o=s.start*e,h=s.count*e;i.queue.writeBuffer(r,0,n,o,h)}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?r_:i_):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?r_:i_),!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=D_.get(i);else{const e=(U_.get(r)||I_.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 L_{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===Xr||s.access===Yr)?t.type=zx:t.type=Gx),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===Xr?Hx:i===Yr?Vx:jx,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=$x)),s.texture.isDepthTexture)i.sampleType=qx;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture){const e=s.texture.type;e===L?i.sampleType=Yx:e===k?i.sampleType=Xx:e===z&&(this.backend.hasFeature("float32-filterable")?i.sampleType=Wx:i.sampleType=$x)}s.isSampledCubeTexture?i.viewDimension=e_:s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?i.viewDimension=Jx:s.isSampledTexture3D&&(i.viewDimension=t_),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)}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=s_;let n;n=t.isSampledCubeTexture?e_:t.isSampledTexture3D?t_:t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Jx:Zx,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 k_{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),S=this._getSampleCount(e.context),w={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},x,{targets:y}),primitive:_,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:l.createPipelineLayout({bindGroupLayouts:d})},M={},N=e.context.depth,A=e.context.stencil;if(!0!==N&&!0!==A||(!0===N&&(M.format=T,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),!0===A&&(M.stencilFront=g,M.stencilBack={},M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),w.depthStencil=M),null===t)c.pipeline=l.createRenderPipeline(w);else{const e=new Promise((e=>{l.createRenderPipelineAsync(w).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:Mx},s={srcFactor:r,dstFactor:n,operation:Mx}};if(e.premultipliedAlpha)switch(i){case 1:r(px,yx,px,yx);break;case 2:r(px,px,px,px);break;case 3:r(dx,gx,dx,px);break;case 4:r(dx,mx,dx,fx)}else switch(i){case 1:r(fx,yx,px,yx);break;case 2:r(fx,px,fx,px);break;case 3:r(dx,gx,dx,px);break;case 4:r(dx,mx,dx,mx)}}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 200:t=dx;break;case 201:t=px;break;case 202:t=mx;break;case 203:t=gx;break;case m:t=fx;break;case g:t=yx;break;case 208:t=bx;break;case 209:t=xx;break;case 206:t=_x;break;case 207:t=vx;break;case 210:t=Tx;break;case 211:t=Sx;break;case 212:t=wx;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=jb;break;case 519:t=Kb;break;case 513:t=Hb;break;case 515:t=$b;break;case 514:t=Wb;break;case 518:t=Xb;break;case 516:t=qb;break;case 517:t=Yb;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case we:t=Bx;break;case 0:t=Fx;break;case 7681:t=Ix;break;case 5386:t=Ux;break;case 7682:t=Dx;break;case 7683:t=Ox;break;case 34055:t=Lx;break;case 34056:t=kx;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case a:t=Mx;break;case 101:t=Nx;break;case 102:t=Ax;break;case 103:t=Ex;break;case 104:t=Cx;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?rx:nx),s.side){case 0:i.frontFace=ex,i.cullMode=ix;break;case 1:i.frontFace=ex,i.cullMode=sx;break;case 2:i.frontFace=ex,i.cullMode=tx;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?Px:Rx}_getDepthCompare(e){let t;if(!1===e.depthTest)t=Kb;else{const s=e.depthFunc;switch(s){case 0:t=jb;break;case 1:t=Kb;break;case 2:t=Hb;break;case 3:t=$b;break;case 4:t=Wb;break;case 5:t=Xb;break;case 6:t=qb;break;case 7:t=Yb;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class z_ extends xb{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.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new F_(this),this.attributeUtils=new O_(this),this.bindingUtils=new L_(this),this.pipelineUtils=new k_(this),this.textureUtils=new m_(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(n_),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(n_.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!==s.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==s.samples||i.loadOp!==t.loadOp){r={},i.descriptors=r;const e=()=>{s.removeEventListener("dispose",e),this.delete(s)};s.addEventListener("dispose",e)}const n=e.getCacheKey();let o=r[n];if(void 0===o){const a=e.textures,h=[];let l;for(let i=0;i<a.length;i++){const r=this.get(a[i]),n={label:`colorAttachment_${i}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:Zx};s.isRenderTarget3D?(l=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=t_,n.depthOrArrayLayers=a[i].image.depth):s.isRenderTargetArray&&(n.dimension=Jx,n.depthOrArrayLayers=a[i].image.depth);const o=r.texture.createView(n);let u,c;void 0!==r.msaaTexture?(u=r.msaaTexture.createView(),c=o):(u=o,c=void 0),h.push({view:u,depthSlice:l,resolveTarget:c,loadOp:Zb,storeOp:Qb,...t})}if(o={colorAttachments:h},e.depth){const t={view:this.get(e.depthTexture).texture.createView()};o.depthStencilAttachment=t}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,i.depthSlice=l,i.loadOp=h[0].loadOp}return 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:Zb}),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=Jb,i.storeOp=Qb):(i.loadOp=Zb,i.storeOp=Qb)}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=Jb,t.storeOp=Qb):(t.loadOp=Zb,t.storeOp=Qb)}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=Jb,o.depthStoreOp=Qb):(o.depthLoadOp=Zb,o.depthStoreOp=Qb)),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=Jb,o.stencilStoreOp=Qb):(o.stencilLoadOp=Zb,o.stencilStoreOp=Qb));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.prepareTimestampBuffer(e,t.encoder),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)}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();if(!0===this.renderer.alpha){const t=e.a;a={r:e.r*t,g:e.g*t,b:e.b*t,a:t}}else 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=Jb,e.storeOp=Qb}(h||l)&&(o=t.depthStencilAttachment)}else{if(h=i.depth,l=i.stencil,e){u=this._getRenderPassDescriptor(i,{loadOp:Jb}).colorAttachments}if(h||l){o={view:this.get(i.depthTexture).texture.createView()}}}h&&(t?(o.depthLoadOp=Jb,o.depthClearValue=n.getClearDepth(),o.depthStoreOp=Qb):(o.depthLoadOp=Zb,o.depthStoreOp=Qb)),l&&(s?(o.stencilLoadOp=Jb,o.stencilClearValue=n.getClearStencil(),o.stencilStoreOp=Qb):(o.stencilLoadOp=Zb,o.stencilStoreOp=Qb));const c=r.createCommandEncoder({});c.beginRenderPass({colorAttachments:u,depthStencilAttachment:o}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={};this.initTimestampQuery(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder(),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.prepareTimestampBuffer(e,t.cmdEncoderGPU),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=e.getBindings(),o=this.get(i),a=this.get(r).pipeline,h=o.currentSets,l=o.currentPass,u=e.getDrawParameters();if(null===u)return;h.pipeline!==a&&(l.setPipeline(a),h.pipeline=a);const c=h.bindingGroups;for(let e=0,t=n.length;e<t;e++){const t=n[e],s=this.get(t);c[t.index]!==t.id&&(l.setBindGroup(t.index,s.group),c[t.index]=t.id)}const d=e.getIndex(),p=null!==d;if(!0===p&&h.index!==d){const e=this.get(d).buffer,t=d.array instanceof Uint16Array?rx:nx;l.setIndexBuffer(e,t),h.index=d}const m=e.getVertexBuffers();for(let e=0,t=m.length;e<t;e++){const t=m[e];if(h.attributes[e]!==t){const s=this.get(t).buffer;l.setVertexBuffer(e,s),h.attributes[e]=t}}if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(l.endOcclusionQuery(),o.occlusionQueryIndex++),!0===s.occlusionTest&&(l.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=s),o.lastOcclusionObject=s)}if(!0===s.isBatchedMesh){const e=s._multiDrawStarts,t=s._multiDrawCounts,i=s._multiDrawCount,r=s._multiDrawInstances;for(let s=0;s<i;s++){const i=r?r[s]:1,n=i>1?0:s;!0===p?l.drawIndexed(t[s],i,e[s]/d.array.BYTES_PER_ELEMENT,0,n):l.draw(t[s],i,e[s],n)}}else if(!0===p){const{vertexCount:i,instanceCount:r,firstVertex:n}=u,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;l.drawIndexedIndirect(e,0)}else l.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=u,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;l.drawIndirect(e,0)}else l.draw(i,r,n,0);t.update(s,i,r)}}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)}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=this.get(e);if(!s.timeStampQuerySet){const i=e.isComputeNode?"compute":"render",r=this.device.createQuerySet({type:"timestamp",count:2,label:`timestamp_${i}_${e.id}`}),n={querySet:r,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1};Object.assign(t,{timestampWrites:n}),s.timeStampQuerySet=r}}prepareTimestampBuffer(e,t){if(!this.trackTimestamp)return;const s=this.get(e),i=2*BigInt64Array.BYTES_PER_ELEMENT;void 0===s.currentTimestampQueryBuffers&&(s.currentTimestampQueryBuffers={resolveBuffer:this.device.createBuffer({label:"timestamp resolve buffer",size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),resultBuffer:this.device.createBuffer({label:"timestamp result buffer",size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})});const{resolveBuffer:r,resultBuffer:n}=s.currentTimestampQueryBuffers;t.resolveQuerySet(s.timeStampQuerySet,0,2,r,0),"unmapped"===n.mapState&&t.copyBufferToBuffer(r,0,n,0,i)}async resolveTimestampAsync(e,t="render"){if(!this.trackTimestamp)return;const s=this.get(e);if(void 0===s.currentTimestampQueryBuffers)return;const{resultBuffer:i}=s.currentTimestampQueryBuffers;"unmapped"===i.mapState&&i.mapAsync(GPUMapMode.READ).then((()=>{const e=new BigUint64Array(i.getMappedRange()),s=Number(e[1]-e[0])/1e6;this.renderer.info.updateTimestamp(t,s),i.unmap()}))}createNodeBuilder(e,t){return new B_(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){let n=0,o=0,a=0,h=0,l=0,u=0,c=e.image.width,d=e.image.height;null!==s&&(h=s.x,l=s.y,u=s.z||0,c=s.width,d=s.height),null!==i&&(n=i.x,o=i.y,a=i.z||0);const p=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),m=this.get(e).texture,g=this.get(t).texture;p.copyTextureToTexture({texture:m,mipLevel:r,origin:{x:h,y:l,z:u}},{texture:g,mipLevel:r,origin:{x:n,y:o,z:a}},[c,d,1]),this.device.queue.submit([p.finish()])}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=Zb;if(t.depth&&(e.depthStencilAttachment.depthLoadOp=Zb),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=Zb),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 G_ extends fr{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 V_ extends jy{constructor(){super(),this.addMaterial(Pd,"MeshPhongMaterial"),this.addMaterial(Qp,"MeshStandardMaterial"),this.addMaterial(Jp,"MeshPhysicalMaterial"),this.addMaterial(im,"MeshToonMaterial"),this.addMaterial(Td,"MeshBasicMaterial"),this.addMaterial(Cd,"MeshLambertMaterial"),this.addMaterial(hd,"MeshNormalMaterial"),this.addMaterial(am,"MeshMatcapMaterial"),this.addMaterial(rd,"LineBasicMaterial"),this.addMaterial(od,"LineDashedMaterial"),this.addMaterial(lm,"PointsMaterial"),this.addMaterial(pm,"SpriteMaterial"),this.addMaterial(fm,"ShadowMaterial"),this.addLight(bf,vr),this.addLight(_y,wr),this.addLight(wy,Nr),this.addLight(My,fr),this.addLight(Ay,Mr),this.addLight(Ey,ur),this.addLight(Cy,Er),this.addLight(Ny,G_),this.addToneMapping(yg,1),this.addToneMapping(bg,2),this.addToneMapping(xg,3),this.addToneMapping(vg,4),this.addToneMapping(Mg,6),this.addToneMapping(Ng,7)}}class j_ extends Zy{constructor(e={}){let t;e.forceWebGL?t=Ob:(t=z_,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Ob(e)));super(new t(e),e),this.library=new V_,this.isWebGPURenderer=!0}}const H_={type:"change"},W_={type:"start"},$_={type:"end"},q_=1e-6,Y_=-1,X_=0,K_=1,Q_=2,Z_=3,J_=4,ev=new e.Vector2,tv=new e.Vector2,sv=new e.Vector3,iv=new e.Vector3,rv=new e.Vector3,nv=new e.Quaternion,ov=new e.Vector3,av=new e.Vector3,hv=new e.Vector3,lv=new e.Vector3;class uv extends e.Controls{constructor(t,s=null){super(t,s),this.enabled=!0,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.state=Y_,this.keyState=Y_,this.target=new e.Vector3,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=dv.bind(this),this._onPointerDown=cv.bind(this),this._onPointerUp=pv.bind(this),this._onPointerCancel=mv.bind(this),this._onContextMenu=vv.bind(this),this._onMouseWheel=_v.bind(this),this._onKeyDown=fv.bind(this),this._onKeyUp=gv.bind(this),this._onTouchStart=Tv.bind(this),this._onTouchMove=Sv.bind(this),this._onTouchEnd=wv.bind(this),this._onMouseDown=yv.bind(this),this._onMouseMove=bv.bind(this),this._onMouseUp=xv.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(),this.handleResize()),this.update()}connect(){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)>q_&&(this.dispatchEvent(H_),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>q_||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(H_),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=Y_,this.keyState=Y_,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(H_),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(tv.copy(this._panEnd).sub(this._panStart),tv.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;tv.x*=e,tv.y*=t}tv.multiplyScalar(this._eye.length()*this.panSpeed),iv.copy(this._eye).cross(this.object.up).setLength(tv.x),iv.add(sv.copy(this.object.up).setLength(tv.y)),this.object.position.add(iv),this.target.add(iv),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(tv.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){lv.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=lv.length();e?(this._eye.copy(this.object.position).sub(this.target),ov.copy(this._eye).normalize(),av.copy(this.object.up).normalize(),hv.crossVectors(av,ov).normalize(),av.setLength(this._moveCurr.y-this._movePrev.y),hv.setLength(this._moveCurr.x-this._movePrev.x),lv.copy(av.add(hv)),rv.crossVectors(lv,this._eye).normalize(),e*=this.rotateSpeed,nv.setFromAxisAngle(rv,e),this._eye.applyQuaternion(nv),this.object.up.applyQuaternion(nv),this._lastAxis.copy(rv),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),nv.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(nv),this.object.up.applyQuaternion(nv)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===J_?(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 ev.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),ev}_getMouseOnCircle(e,t){return ev.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),ev}_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 cv(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 dv(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function pv(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 mv(e){this._removePointer(e)}function gv(){!1!==this.enabled&&(this.keyState=Y_,window.addEventListener("keydown",this._onKeyDown))}function fv(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===Y_&&(e.code!==this.keys[X_]||this.noRotate?e.code!==this.keys[K_]||this.noZoom?e.code!==this.keys[Q_]||this.noPan||(this.keyState=Q_):this.keyState=K_:this.keyState=X_))}function yv(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=K_;break;case e.MOUSE.ROTATE:this.state=X_;break;case e.MOUSE.PAN:this.state=Q_;break;default:this.state=Y_}const i=this.keyState!==Y_?this.keyState:this.state;i!==X_||this.noRotate?i!==K_||this.noZoom?i!==Q_||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(W_)}function bv(e){const t=this.keyState!==Y_?this.keyState:this.state;t!==X_||this.noRotate?t!==K_||this.noZoom?t!==Q_||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 xv(){this.state=Y_,this.dispatchEvent($_)}function _v(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(W_),this.dispatchEvent($_)}}function vv(e){!1!==this.enabled&&e.preventDefault()}function Tv(e){if(this._trackPointer(e),1===this._pointers.length)this.state=Z_,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=J_;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(W_)}function Sv(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 wv(e){switch(this._pointers.length){case 0:this.state=Y_;break;case 1:this.state=Z_,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=J_;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($_)}const Mv={type:"change"},Nv={type:"start"},Av={type:"end"},Ev=new e.Ray,Cv=new e.Plane,Rv=Math.cos(70*e.MathUtils.DEG2RAD),Pv=new e.Vector3,Bv=2*Math.PI,Fv=-1,Iv=0,Uv=1,Dv=2,Ov=3,Lv=4,kv=5,zv=6,Gv=1e-6;class Vv extends e.Controls{constructor(t,s=null){super(t,s),this.state=Fv,this.enabled=!0,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=Hv.bind(this),this._onPointerDown=jv.bind(this),this._onPointerUp=Wv.bind(this),this._onContextMenu=Zv.bind(this),this._onMouseWheel=Yv.bind(this),this._onKeyDown=Xv.bind(this),this._onTouchStart=Kv.bind(this),this._onTouchMove=Qv.bind(this),this._onMouseDown=$v.bind(this),this._onMouseMove=qv.bind(this),this._interceptControlDown=Jv.bind(this),this._interceptControlUp=eT.bind(this),null!==this.domElement&&this.connect(),this.update()}connect(){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(Mv),this.update(),this.state=Fv}update(t=null){const s=this.object.position;Pv.copy(s).sub(this.target),Pv.applyQuaternion(this._quat),this._spherical.setFromVector3(Pv),this.autoRotate&&this.state===Fv&&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+=Bv:i>Math.PI&&(i-=Bv),r<-Math.PI?r+=Bv:r>Math.PI&&(r-=Bv),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(Pv.setFromSpherical(this._spherical),Pv.applyQuaternion(this._quatInverse),s.copy(this.target).add(Pv),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=Pv.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=Pv.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):(Ev.origin.copy(this.object.position),Ev.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ev.direction))<Rv?this.object.lookAt(this.target):(Cv.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ev.intersectPlane(Cv,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)>Gv||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Gv||this._lastTargetPosition.distanceToSquared(this.target)>Gv)&&(this.dispatchEvent(Mv),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?Bv/60*this.autoRotateSpeed*e:Bv/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){Pv.setFromMatrixColumn(t,0),Pv.multiplyScalar(-e),this._panOffset.add(Pv)}_panUp(e,t){!0===this.screenSpacePanning?Pv.setFromMatrixColumn(t,1):(Pv.setFromMatrixColumn(t,0),Pv.crossVectors(this.object.up,Pv)),Pv.multiplyScalar(e),this._panOffset.add(Pv)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Pv.copy(i).sub(this.target);let r=Pv.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(Bv*this._rotateDelta.x/t.clientHeight),this._rotateUp(Bv*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(Bv*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(-Bv*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(Bv*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(-Bv*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(Bv*this._rotateDelta.x/t.clientHeight),this._rotateUp(Bv*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 jv(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 Hv(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function Wv(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(Av),this.state=Fv;break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function $v(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=Uv;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=Dv}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=Iv}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=Iv}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=Dv}break;default:this.state=Fv}this.state!==Fv&&this.dispatchEvent(Nv)}function qv(e){switch(this.state){case Iv:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case Uv:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case Dv:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function Yv(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===Fv&&(e.preventDefault(),this.dispatchEvent(Nv),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(Av))}function Xv(e){!1!==this.enabled&&this._handleKeyDown(e)}function Kv(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=Ov;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=Lv;break;default:this.state=Fv}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=kv;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=zv;break;default:this.state=Fv}break;default:this.state=Fv}this.state!==Fv&&this.dispatchEvent(Nv)}function Qv(e){switch(this._trackPointer(e),this.state){case Ov:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case Lv:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case kv:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case zv:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Fv}}function Zv(e){!1!==this.enabled&&e.preventDefault()}function Jv(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function eT(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const tT={type:"change"},sT=1e-6,iT=new e.Quaternion;class rT 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=nT.bind(this),this._onKeyUp=oT.bind(this),this._onPointerMove=hT.bind(this),this._onPointerDown=aT.bind(this),this._onPointerUp=lT.bind(this),this._onPointerCancel=uT.bind(this),this._onContextMenu=cT.bind(this),null!==s&&this.connect()}connect(){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),iT.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(iT),(this._lastPosition.distanceToSquared(t.position)>sT||8*(1-this._lastQuaternion.dot(t.quaternion))>sT)&&(this.dispatchEvent(tT),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 nT(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 oT(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 aT(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 hT(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 lT(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 uT(){!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 cT(e){!1!==this.enabled&&e.preventDefault()}const dT={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 pT{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 mT=new e.OrthographicCamera(-1,1,1,-1,0,1);class gT 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 fT=new gT;class yT{constructor(t){this._mesh=new e.Mesh(fT,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,mT)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class bT extends pT{constructor(t,s){super(),this.textureID=void 0!==s?s:"tDiffuse",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 yT(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 xT extends pT{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 _T extends pT{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class vT{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 bT(dT),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!==xT&&(i instanceof xT?s=!0:i instanceof _T&&(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 TT extends pT{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 ST(){return ST=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},ST.apply(null,arguments)}function wT(e,t){return wT=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},wT(e,t)}function MT(e){return MT=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},MT(e)}function NT(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(NT=function(){return!!e})()}function AT(e){var t="function"==typeof Map?new Map:void 0;return AT=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(NT())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&wT(r,s.prototype),r}(e,arguments,MT(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),wT(s,e)},AT(e)}var ET={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 CT(){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 RT=function(e){var t,s;function i(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,CT.apply(void 0,[ET[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 s=e,(t=i).prototype=Object.create(s.prototype),t.prototype.constructor=t,wT(t,s),i}(AT(Error));function PT(e){return Math.round(255*e)}function BT(e,t,s){return PT(e)+","+PT(t)+","+PT(s)}function FT(e,t,s,i){if(void 0===i&&(i=BT),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 IT={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 UT=/^#[a-fA-F0-9]{6}$/,DT=/^#[a-fA-F0-9]{8}$/,OT=/^#[a-fA-F0-9]{3}$/,LT=/^#[a-fA-F0-9]{4}$/,kT=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,zT=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,GT=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,VT=/^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 jT(e){if("string"!=typeof e)throw new RT(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return IT[t]?"#"+IT[t]:e}(e);if(t.match(UT))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(DT)){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(OT))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(LT)){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=kT.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=zT.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=GT.exec(t);if(o){var a="rgb("+FT(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",h=kT.exec(a);if(!h)throw new RT(4,t,a);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var l=VT.exec(t.substring(0,50));if(l){var u="rgb("+FT(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",c=kT.exec(u);if(!c)throw new RT(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 RT(5)}function HT(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}}(jT(e))}var WT=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 $T(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function qT(e){return $T(Math.round(255*e))}function YT(e,t,s){return WT("#"+qT(e)+qT(t)+qT(s))}function XT(e,t,s){return FT(e,t,s,YT)}function KT(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return WT("#"+$T(e)+$T(t)+$T(s));if("object"==typeof e&&void 0===t&&void 0===s)return WT("#"+$T(e.red)+$T(e.green)+$T(e.blue));throw new RT(6)}function QT(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?KT(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new RT(7)}function ZT(e){if("object"!=typeof e)throw new RT(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return QT(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 KT(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?XT(e.hue,e.saturation,e.lightness):"rgba("+FT(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new RT(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 XT(e.hue,e.saturation,e.lightness);throw new RT(1)}(e);throw new RT(8)}function JT(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):JT(e,t,i)}}function eS(e){return JT(e,e.length,[])}function tS(e,t,s){return Math.max(e,Math.min(t,s))}eS((function(e,t){if("transparent"===t)return t;var s=HT(t);return ZT(ST({},s,{hue:s.hue+parseFloat(e)}))})),eS((function(e,t){if("transparent"===t)return t;var s=HT(t);return ZT(ST({},s,{lightness:tS(0,1,s.lightness-parseFloat(e))}))})),eS((function(e,t){if("transparent"===t)return t;var s=HT(t);return ZT(ST({},s,{saturation:tS(0,1,s.saturation-parseFloat(e))}))})),eS((function(e,t){if("transparent"===t)return t;var s=HT(t);return ZT(ST({},s,{lightness:tS(0,1,s.lightness+parseFloat(e))}))}));var sS=eS((function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=jT(t),r=ST({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=jT(s),o=ST({},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 QT({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))})})),iS=sS;var rS=eS((function(e,t){if("transparent"===t)return t;var s=jT(t);return QT(ST({},s,{alpha:tS(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))})),nS=rS;eS((function(e,t){if("transparent"===t)return t;var s=HT(t);return ZT(ST({},s,{saturation:tS(0,1,s.saturation+parseFloat(e))}))})),eS((function(e,t){return"transparent"===t?t:ZT(ST({},HT(t),{hue:parseFloat(e)}))})),eS((function(e,t){return"transparent"===t?t:ZT(ST({},HT(t),{lightness:parseFloat(e)}))})),eS((function(e,t){return"transparent"===t?t:ZT(ST({},HT(t),{saturation:parseFloat(e)}))})),eS((function(e,t){return"transparent"===t?t:iS(parseFloat(e),"rgb(0, 0, 0)",t)})),eS((function(e,t){return"transparent"===t?t:iS(parseFloat(e),"rgb(255, 255, 255)",t)})),eS((function(e,t){if("transparent"===t)return t;var s=jT(t);return QT(ST({},s,{alpha:tS(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}));var oS,aS=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-aS.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*aS.Bounce.In(2*e):.5*aS.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}}}}),hS=function(){return performance.now()},lS=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=hS()),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}(),uS={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=uS.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)},Bezier:function(e,t){for(var s=0,i=e.length-1,r=Math.pow,n=uS.Utils.Bernstein,o=0;o<=i;o++)s+=r(1-t,i-o)*r(t,o)*e[o]*n(i,o);return s},CatmullRom:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=uS.Utils.CatmullRom;return e[0]===e[s]?(t<0&&(r=Math.floor(i=s*(1+t))),n(e[(r-1+s)%s],e[r],e[(r+1)%s],e[(r+2)%s],i-r)):t<0?e[0]-(n(e[0],e[0],e[1],e[1],-i)-e[0]):t>1?e[s]-(n(e[s],e[s],e[s-1],e[s-1],i-s)-e[s]):n(e[r?r-1:0],e[r],e[s<r+1?s:r+1],e[s<r+2?s:r+2],i-r)},Utils:{Linear:function(e,t,s){return(t-e)*s+e},Bernstein:function(e,t){var s=uS.Utils.Factorial;return s(e)/s(t)/s(e-t)},Factorial:(oS=[1],function(e){var t=1;if(oS[e])return oS[e];for(var s=e;s>1;s--)t*=s;return oS[e]=t,t}),CatmullRom:function(e,t,s,i,r){var n=.5*(s-e),o=.5*(i-t),a=r*r;return(2*t-2*s+n+o)*(r*a)+(-3*t+3*s-2*n-o)*a+n*r+t}}},cS=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),dS=new lS,pS=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=aS.Linear.None,this._interpolationFunction=uS.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=cS.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=dS,dS.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=hS()),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=hS()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=hS()),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=aS.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=uS.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=hS()),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}(),mS=dS;mS.getAll.bind(mS),mS.removeAll.bind(mS),mS.add.bind(mS),mS.remove.bind(mS),mS.update.bind(mS);function gS(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var fS="object"==typeof global&&global&&global.Object===Object&&global,yS="object"==typeof self&&self&&self.Object===Object&&self,bS=fS||yS||Function("return this")(),xS=function(){return bS.Date.now()},_S=/\s/;var vS=/^\s+/;function TS(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&_S.test(e.charAt(t)););return t}(e)+1).replace(vS,""):e}var SS=bS.Symbol,wS=Object.prototype,MS=wS.hasOwnProperty,NS=wS.toString,AS=SS?SS.toStringTag:void 0;var ES=Object.prototype.toString;var CS=SS?SS.toStringTag:void 0;function RS(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":CS&&CS in Object(e)?function(e){var t=MS.call(e,AS),s=e[AS];try{e[AS]=void 0;var i=!0}catch(e){}var r=NS.call(e);return i&&(t?e[AS]=s:delete e[AS]),r}(e):function(e){return ES.call(e)}(e)}var PS=/^[-+]0x[0-9a-f]+$/i,BS=/^0b[01]+$/i,FS=/^0o[0-7]+$/i,IS=parseInt;function US(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]"==RS(e)}(e))return NaN;if(gS(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=gS(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=TS(e);var s=BS.test(e);return s||FS.test(e)?IS(e.slice(2),s?2:8):PS.test(e)?NaN:+e}var DS=Math.max,OS=Math.min;function LS(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=xS();if(m(e))return f(e);a=setTimeout(g,function(e){var s=t-(e-h);return c?OS(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=xS(),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=US(t)||0,gS(s)&&(u=!!s.leading,n=(c="maxWait"in s)?DS(US(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(xS())},y}function kS(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 zS(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function GS(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 kS(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)?kS(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 VS=zS((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}));var jS,HS,WS,$S,qS,YS,XS,KS,QS,ZS,JS,ew,tw,sw,iw=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,EventDispatcher:e.EventDispatcher,MOUSE:e.MOUSE,Quaternion:e.Quaternion,Spherical:e.Spherical,Clock:e.Clock},rw=(jS={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)}},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.toolTipElem&&(t.toolTipElem.style.display="none",t.toolTipElem.innerHTML="")},triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{default:function(){return-1},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){if(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)})),e.enablePointerInteraction){var t=null;if(e.hoverDuringDrag||!e.isPointerDragging){var s=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y).filter((function(t){return e.hoverFilter(t.object)})).sort((function(t,s){return e.hoverOrderComparator(t.object,s.object)})),i=s.length?s[0]:null;t=i?i.object:null,e.intersectionPoint=i?i.point:null}t!==e.hoverObj&&(e.onHover(t,e.hoverObj),e.toolTipElem.style.display=(e.toolTipElem.innerHTML=t&&("function"==typeof(r=e.tooltipContent)?r:"string"==typeof r?function(e){return e[r]}:function(e){return r})(t)||"")?"initial":"none",e.hoverObj=t)}e.tweenGroup.update()}var r;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 pS(a).to(n,i).easing(aS.Quadratic.Out).onUpdate(l).start()),e.tweenGroup.add(new pS(h).to(o,i/3).easing(aS.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 iw.Vector3(t.x,t.y,t.z);e.controls.target?e.controls.target=s:r.lookAt(s)}function c(){return Object.assign(new iw.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 iw.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 iw.Box3(new iw.Vector3(0,0,0),new iw.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 iw.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 iw.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new iw.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new iw.Vector3))},intersectingObjects:function(e,t,s){var i=new iw.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new iw.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,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 iw.Scene,camera:new iw.PerspectiveCamera,clock:new iw.Clock,tweenGroup:new lS}},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.toolTipElem=document.createElement("div"),t.toolTipElem.classList.add("scene-tooltip"),t.container.appendChild(t.toolTipElem),t.pointerPos=new iw.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,t.toolTipElem.style.top="".concat(t.pointerPos.y,"px"),t.toolTipElem.style.left="".concat(t.pointerPos.x,"px"),t.toolTipElem.style.transform="translate(-".concat(t.pointerPos.x/t.width*100,"%, ").concat(t.height-t.pointerPos.y<100?"calc(-100% - 8px)":"21px",")")}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.intersectionPoint),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersectionPoint)}))}),{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",(function(e){t.onRightClick&&e.preventDefault()})),t.renderer=new(a?j_:iw.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 vT(t.renderer),t.postProcessingComposer.addPass(new TT(t.scene,t.camera)),t.controls=new{trackball:uv,orbit:Vv,fly:rT}[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 iw.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"))&&(e.container.style.width="".concat(e.width,"px"),e.container.style.height="".concat(e.height,"px"),[e.renderer,e.postProcessingComposer].concat(r(e.extraRenderers)).forEach((function(t){return t.setSize(e.width,e.height)})),e.camera.aspect=e.width/e.height,e.camera.updateProjectionMatrix()),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 iw.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var s=jT(e.backgroundColor).alpha;void 0===s&&(s=1),e.renderer.setClearColor(new iw.Color(nS(1,e.backgroundColor)),s)}function i(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new iw.TextureLoader).load(e.backgroundImageUrl,(function(t){t.colorSpace=iw.SRGBColorSpace,e.skysphere.material=new iw.MeshBasicMaterial({map:t,side:iw.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&i()})):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&i())),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)})))}},HS=jS.stateInit,WS=void 0===HS?function(){return{}}:HS,$S=jS.props,qS=void 0===$S?{}:$S,YS=jS.methods,XS=void 0===YS?{}:YS,KS=jS.aliases,QS=void 0===KS?{}:KS,ZS=jS.init,JS=void 0===ZS?function(){}:ZS,ew=jS.update,tw=void 0===ew?function(){}:ew,sw=Object.keys(qS).map((function(e){return new VS(e,qS[e])})),function e(){for(var t=arguments.length,s=new Array(t),i=0;i<t;i++)s[i]=arguments[i];var r=!!(this instanceof e?this.constructor:void 0),n=r?s.shift():void 0,o=s[0],a=void 0===o?{}:o,h=Object.assign({},WS instanceof Function?WS(a):WS,{initialised:!1}),l={};function u(e){return c(e,a),d(),u}var c=function(e,t){JS.call(u,e,h,t),h.initialised=!0},d=LS((function(){h.initialised&&(tw.call(u,h,l),l={})}),1);return sw.forEach((function(e){u[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=h[t];if(!arguments.length)return s;var r=void 0===e?a:e;return h[t]=r,n.call(u,r,h,s),!l.hasOwnProperty(t)&&(l[t]=s),i&&d(),u}}(e)})),Object.keys(XS).forEach((function(e){u[e]=function(){for(var t,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];return(t=XS[e]).call.apply(t,[u,h].concat(i))}})),Object.entries(QS).forEach((function(e){var t=GS(e,2),s=t[0],i=t[1];return u[s]=u[i]})),u.resetProps=function(){return sw.forEach((function(e){u[e.name](e.defaultVal)})),u},u.resetProps(),h._rerender=d,r&&n&&u(n),u});return rw}));