// Version 1.80.1 3d-force-graph - https://github.com/vasturiano/3d-force-graph !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t()}(this,function(){"use strict";!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===n&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".graph-info-msg {\n top: 50%;\n width: 100%;\n text-align: center;\n color: lavender;\n opacity: 0.7;\n font-size: 22px;\n position: absolute;\n font-family: Sans-serif;\n}\n\n.scene-container .clickable {\n cursor: pointer;\n}\n\n.scene-container .grabbable {\n cursor: move;\n cursor: grab;\n cursor: -moz-grab;\n cursor: -webkit-grab;\n}\n\n.scene-container .grabbable:active {\n cursor: grabbing;\n cursor: -moz-grabbing;\n cursor: -webkit-grabbing;\n}");const e="186",t=0,n=1,i=2,r=0,s=1,a=2,o=3,l=1,u=3,c=0,h=1,d=2,p=100,f=101,m=102,g=103,_=104,v=200,y=201,b=202,x=203,S=204,T=205,M=206,w=207,E=208,A=209,R=210,C=211,N=212,P=213,L=214,D=0,I=1,U=2,F=3,O=4,B=5,k=6,z=7,V=0,G=1,H=2,W=1,j=2,$=3,X=4,q=5,Y=6,K=7,Z=301,Q=302,J=303,ee=304,te=306,ne=1e3,ie=1001,re=1002,se=1003,ae=1004,oe=1005,le=1006,ue=1007,ce=1008,he=1009,de=1010,pe=1011,fe=1012,me=1013,ge=1014,_e=1015,ve=1016,ye=1017,be=1018,xe=1020,Se=35902,Te=35899,Me=1021,we=1022,Ee=1023,Ae=1026,Re=1027,Ce=1028,Ne=1029,Pe=1030,Le=1031,De=1032,Ie=1033,Ue=33776,Fe=33777,Oe=33778,Be=33779,ke=35840,ze=35841,Ve=35842,Ge=35843,He=36196,We=37492,je=37496,$e=37488,Xe=37489,qe=37490,Ye=37491,Ke=37808,Ze=37809,Qe=37810,Je=37811,et=37812,tt=37813,nt=37814,it=37815,rt=37816,st=37817,at=37818,ot=37819,lt=37820,ut=37821,ct=36492,ht=36494,dt=36495,pt=36283,ft=36284,mt=36285,gt=36286,_t="",vt="srgb",yt="srgb-linear",bt="linear",xt="srgb",St=7680,Tt=512,Mt=513,wt=514,Et=515,At=516,Rt=517,Ct=518,Nt=519,Pt=35044,Lt=35048,Dt="300 es",It=2e3,Ut=2001,Ft="compute",Ot="render",Bt="depthTextureCompare",kt=0,zt=1,Vt=2;function Gt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Ht(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Wt(){const e=Ht("canvas");return e.style.display="block",e}const jt={};function $t(...e){const t="THREE."+e.shift();console.log(t,...e)}function Xt(e){const t=e[0];if("string"==typeof t&&t.startsWith("TSL:")){const t=e[1];t&&t.isStackTrace?e[0]+=" "+t.getLocation():e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function qt(...e){const t="THREE."+(e=Xt(e)).shift();{const n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function Yt(...e){const t="THREE."+(e=Xt(e)).shift();{const n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Kt(...e){const t=e.join(" ");t in jt||(jt[t]=!0,qt(...e))}function Zt(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}const Qt={[D]:1,[U]:6,[O]:7,[F]:5,[I]:0,[k]:2,[z]:4,[B]:3};class Jt{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return void 0!==n&&(void 0!==n[e]&&-1!==n[e].indexOf(t))}removeEventListener(e,t){const n=this._listeners;if(void 0===n)return;const i=n[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const n=t[e.type];if(void 0!==n){e.target=this;const t=n.slice(0);for(let n=0,i=t.length;n>8&255]+en[e>>16&255]+en[e>>24&255]+"-"+en[255&t]+en[t>>8&255]+"-"+en[t>>16&15|64]+en[t>>24&255]+"-"+en[63&n|128]+en[n>>8&255]+"-"+en[n>>16&255]+en[n>>24&255]+en[255&i]+en[i>>8&255]+en[i>>16&255]+en[i>>24&255]).toLowerCase()}function an(e,t,n){return Math.max(t,Math.min(n,e))}function on(e,t){return(e%t+t)%t}function ln(e,t,n){return(1-n)*e+n*t}function un(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray: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("THREE.MathUtils: Invalid component type.")}}function cn(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:case Uint8ClampedArray: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("THREE.MathUtils: Invalid component type.")}}const hn={DEG2RAD:nn,RAD2DEG:rn,generateUUID:sn,clamp:an,euclideanModulo:on,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:ln,damp:function(e,t,n,i){return ln(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(on(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-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&&(tn=e);let t=tn+=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*nn},radToDeg:function(e){return e*rn},isPowerOfTwo:function(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===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,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),u=s((t+i)/2),c=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),f=a((i-t)/2);switch(r){case"XYX":e.set(o*c,l*h,l*d,o*u);break;case"YZY":e.set(l*d,o*c,l*h,o*u);break;case"ZXZ":e.set(l*h,l*d,o*c,o*u);break;case"XZX":e.set(o*c,l*f,l*p,o*u);break;case"YXY":e.set(l*p,o*c,l*f,o*u);break;case"ZYZ":e.set(l*f,l*p,o*c,o*u);break;default:qt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:cn,denormalize:un};class dn{static{dn.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,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,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+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=an(this.x,e.x,t.x),this.y=an(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=an(this.x,e,t),this.y=an(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(an(n,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 n=this.dot(e)/t;return Math.acos(an(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,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 n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class pn{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,s,a){let o=n[i+0],l=n[i+1],u=n[i+2],c=n[i+3],h=r[s+0],d=r[s+1],p=r[s+2],f=r[s+3];if(c!==f||o!==h||l!==d||u!==p){let e=o*h+l*d+u*p+c*f;e<0&&(h=-h,d=-d,p=-p,f=-f,e=-e);let t=1-a;if(e<.9995){const n=Math.acos(e),i=Math.sin(n);t=Math.sin(t*n)/i,o=o*t+h*(a=Math.sin(a*n)/i),l=l*t+d*a,u=u*t+p*a,c=c*t+f*a}else{o=o*t+h*a,l=l*t+d*a,u=u*t+p*a,c=c*t+f*a;const e=1/Math.sqrt(o*o+l*l+u*u+c*c);o*=e,l*=e,u*=e,c*=e}}e[t]=o,e[t+1]=l,e[t+2]=u,e[t+3]=c}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],u=n[i+3],c=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+u*c+o*d-l*h,e[t+1]=o*p+u*h+l*c-a*d,e[t+2]=l*p+u*d+a*h-o*c,e[t+3]=u*p-a*c-o*h-l*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,n,i){return this._x=e,this._y=t,this._z=n,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 n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),u=a(i/2),c=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"YXZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"ZXY":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"ZYX":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"YZX":this._x=h*u*c+l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c-h*d*p;break;case"XZY":this._x=h*u*c-l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c+h*d*p;break;default:qt("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=n+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>c){const e=2*Math.sqrt(1+n-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-n-c);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(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=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(an(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);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 n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=n*u+s*a+i*l-r*o,this._y=i*u+s*o+r*a-n*l,this._z=r*u+s*l+n*o-i*a,this._w=s*u-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){let n=e._x,i=e._y,r=e._z,s=e._w,a=this.dot(e);a<0&&(n=-n,i=-i,r=-r,s=-s,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);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 fn{static{fn.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,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("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,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(gn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(gn.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),u=2*(a*t-r*i),c=2*(r*n-s*t);return this.x=t+o*l+s*c-a*u,this.y=n+o*u+a*l-r*c,this.z=i+o*c+r*u-s*l,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,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+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=an(this.x,e.x,t.x),this.y=an(this.y,e.y,t.y),this.z=an(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=an(this.x,e,t),this.y=an(this.y,e,t),this.z=an(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(an(n,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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return mn.copy(this).projectOnVector(e),this.sub(mn)}reflect(e){return this.sub(mn.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 n=this.dot(e)/t;return Math.acos(an(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+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,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,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(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,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,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const mn=new fn,gn=new pn;class _n{static{_n.prototype.isMatrix3=!0}constructor(e,t,n,i,r,s,a,o,l){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=r,u[5]=o,u[6]=n,u[7]=s,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.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 n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],u=n[4],c=n[7],h=n[2],d=n[5],p=n[8],f=i[0],m=i[3],g=i[6],_=i[1],v=i[4],y=i[7],b=i[2],x=i[5],S=i[8];return r[0]=s*f+a*_+o*b,r[3]=s*m+a*v+o*x,r[6]=s*g+a*y+o*S,r[1]=l*f+u*_+c*b,r[4]=l*m+u*v+c*x,r[7]=l*g+u*y+c*S,r[2]=h*f+d*_+p*b,r[5]=h*m+d*v+p*x,r[8]=h*g+d*y+p*S,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],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-n*r*u+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=u*s-a*l,h=a*o-u*r,d=l*r-s*o,p=t*c+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=c*f,e[1]=(i*l-u*n)*f,e[2]=(a*n-i*s)*f,e[3]=h*f,e[4]=(u*t-i*o)*f,e[5]=(i*r-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*r)*f,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,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return Kt("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(vn.makeScale(e,t)),this}rotate(e){return Kt("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(vn.makeRotation(-e)),this}translate(e,t){return Kt("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(vn.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),n=Math.sin(e);return this.set(t,-n,0,n,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,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const vn=new _n,yn=(new _n).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),bn=(new _n).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function xn(){const e={enabled:!0,workingColorSpace:yt,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===xt&&(e.r=Tn(e.r),e.g=Tn(e.g),e.b=Tn(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===xt&&(e.r=Mn(e.r),e.g=Mn(e.g),e.b=Mn(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===_t?bt:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Kt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Kt("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[yt]:{primaries:t,whitePoint:i,transfer:bt,toXYZ:yn,fromXYZ:bn,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:vt},outputColorSpaceConfig:{drawingBufferColorSpace:vt}},[vt]:{primaries:t,whitePoint:i,transfer:xt,toXYZ:yn,fromXYZ:bn,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:vt}}}),e}const Sn=xn();function Tn(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Mn(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let wn;class En{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{void 0===wn&&(wn=Ht("canvas")),wn.width=e.width,wn.height=e.height;const t=wn.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=wn}return n.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Ht("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Pn).x}get height(){return this.source.getSize(Pn).y}get depth(){return this.source.getSize(Pn).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(void 0===n){qt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n:qt(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}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 ne:e.x=e.x-Math.floor(e.x);break;case ie:e.x=e.x<0?0:1;break;case re: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 ne:e.y=e.y-Math.floor(e.y);break;case ie:e.y=e.y<0?0:1;break;case re: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++}}Ln.DEFAULT_IMAGE=null,Ln.DEFAULT_MAPPING=300,Ln.DEFAULT_ANISOTROPY=1;class Dn{static{Dn.prototype.isVector4=!0}constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,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,n,i){return this.x=e,this.y=t,this.z=n,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("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=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,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const s=.01,a=.1,o=e.elements,l=o[0],u=o[4],c=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(u-h)o&&e>_?e_?o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),u.length>0&&(n.animations=u),c.length>0&&(n.nodes=c)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=null!==e.pivot?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;to+u?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-u&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,o.eventsEnabled&&o.dispatchEvent({type:"gripUpdated",data:e,target:this})));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(pi)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new di;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}const mi={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},gi={h:0,s:0,l:0},_i={h:0,s:0,l:0};function vi(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class yi{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){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,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=vt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Sn.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=Sn.workingColorSpace){return this.r=e,this.g=t,this.b=n,Sn.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=Sn.workingColorSpace){if(e=on(e,1),t=an(t,0,1),n=an(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=vi(r,i,e+1/3),this.g=vi(r,i,e),this.b=vi(r,i,e-1/3)}return Sn.colorSpaceToWorking(this,i),this}setStyle(e,t=vt){function n(t){void 0!==t&&parseFloat(t)<1&&qt("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:qt("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);qt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=vt){const n=mi[e.toLowerCase()];return void 0!==n?this.setHex(n,t):qt("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=Tn(e.r),this.g=Tn(e.g),this.b=Tn(e.b),this}copyLinearToSRGB(e){return this.r=Mn(e.r),this.g=Mn(e.g),this.b=Mn(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=vt){return Sn.workingToColorSpace(bi.copy(this),e),65536*Math.round(an(255*bi.r,0,255))+256*Math.round(an(255*bi.g,0,255))+Math.round(an(255*bi.b,0,255))}getHexString(e=vt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Sn.workingColorSpace){Sn.workingToColorSpace(bi.copy(this),t);const n=bi.r,i=bi.g,r=bi.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const u=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=u<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Si.subVectors(i,t),Ti.subVectors(n,t),Mi.subVectors(e,t);const s=Si.dot(Si),a=Si.dot(Ti),o=Si.dot(Mi),l=Ti.dot(Ti),u=Ti.dot(Mi),c=s*l-a*a;if(0===c)return r.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,wi)&&(wi.x>=0&&wi.y>=0&&wi.x+wi.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,wi)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,wi.x),o.addScaledVector(s,wi.y),o.addScaledVector(a,wi.z),o)}static getInterpolatedAttribute(e,t,n,i,r,s){return Li.setScalar(0),Di.setScalar(0),Ii.setScalar(0),Li.fromBufferAttribute(e,t),Di.fromBufferAttribute(e,n),Ii.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(Li,r.x),s.addScaledVector(Di,r.y),s.addScaledVector(Ii,r.z),s}static isFrontFacing(e,t,n,i){return Si.subVectors(n,t),Ti.subVectors(e,t),Si.cross(Ti).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),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 Si.subVectors(this.c,this.b),Ti.subVectors(this.a,this.b),.5*Si.cross(Ti).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ui.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ui.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return Ui.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Ui.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ui.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;Ei.subVectors(i,n),Ai.subVectors(r,n),Ci.subVectors(e,n);const o=Ei.dot(Ci),l=Ai.dot(Ci);if(o<=0&&l<=0)return t.copy(n);Ni.subVectors(e,i);const u=Ei.dot(Ni),c=Ai.dot(Ni);if(u>=0&&c<=u)return t.copy(i);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0)return s=o/(o-u),t.copy(n).addScaledVector(Ei,s);Pi.subVectors(e,r);const d=Ei.dot(Pi),p=Ai.dot(Pi);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(Ai,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return Ri.subVectors(r,i),a=(c-u)/(c-u+(d-p)),t.copy(i).addScaledVector(Ri,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(Ei,s).addScaledVector(Ai,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Fi{constructor(e=new fn(1/0,1/0,1/0),t=new fn(-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,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bi),Bi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter($i),Xi.subVectors(this.max,$i),zi.subVectors(e.a,$i),Vi.subVectors(e.b,$i),Gi.subVectors(e.c,$i),Hi.subVectors(Vi,zi),Wi.subVectors(Gi,Vi),ji.subVectors(zi,Gi);let t=[0,-Hi.z,Hi.y,0,-Wi.z,Wi.y,0,-ji.z,ji.y,Hi.z,0,-Hi.x,Wi.z,0,-Wi.x,ji.z,0,-ji.x,-Hi.y,Hi.x,0,-Wi.y,Wi.x,0,-ji.y,ji.x,0];return!!Ki(t,zi,Vi,Gi,Xi)&&(t=[1,0,0,0,1,0,0,0,1],!!Ki(t,zi,Vi,Gi,Xi)&&(qi.crossVectors(Hi,Wi),t=[qi.x,qi.y,qi.z],Ki(t,zi,Vi,Gi,Xi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Bi).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()||(Oi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Oi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Oi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Oi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Oi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Oi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Oi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Oi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Oi)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Oi=[new fn,new fn,new fn,new fn,new fn,new fn,new fn,new fn],Bi=new fn,ki=new Fi,zi=new fn,Vi=new fn,Gi=new fn,Hi=new fn,Wi=new fn,ji=new fn,$i=new fn,Xi=new fn,qi=new fn,Yi=new fn;function Ki(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){Yi.fromArray(e,s);const a=r.x*Math.abs(Yi.x)+r.y*Math.abs(Yi.y)+r.z*Math.abs(Yi.z),o=t.dot(Yi),l=n.dot(Yi),u=i.dot(Yi);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const Zi=Qi();function Qi(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=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 s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Ji(e){Math.abs(e)>65504&&qt("DataUtils.toHalfFloat(): Value out of range."),e=an(e,-65504,65504),Zi.floatView[0]=e;const t=Zi.uint32View[0],n=t>>23&511;return Zi.baseTable[n]+((8388607&t)>>Zi.shiftTable[n])}function er(e){const t=e>>10;return Zi.uint32View[0]=Zi.mantissaTable[Zi.offsetTable[t]+(1023&e)]+Zi.exponentTable[t],Zi.floatView[0]}const tr=new fn,nr=new dn;let ir=0;class rr extends Jt{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ir++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=Pt,this.updateRanges=[],this.gpuType=_e,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,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;ithis.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;cr.subVectors(e,this.center);const t=cr.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(cr,n/e),this.radius+=n}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):(hr.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cr.copy(e.center).add(hr)),this.expandByPoint(cr.copy(e.center).sub(hr))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let pr=0;const fr=new Bn,mr=new hi,gr=new fn,_r=new Fi,vr=new Fi,yr=new fn;class br extends Jt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:pr++}),this.uuid=sn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?ar:sr)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}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 n=this.attributes.normal;if(void 0!==n){const t=(new _n).getNormalMatrix(e);n.applyNormalMatrix(t),n.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._transformed=!0,this}applyQuaternion(e){return fr.makeRotationFromQuaternion(e),this.applyMatrix4(fr),this}rotateX(e){return fr.makeRotationX(e),this.applyMatrix4(fr),this}rotateY(e){return fr.makeRotationY(e),this.applyMatrix4(fr),this}rotateZ(e){return fr.makeRotationZ(e),this.applyMatrix4(fr),this}translate(e,t,n){return fr.makeTranslation(e,t,n),this.applyMatrix4(fr),this}scale(e,t,n){return fr.makeScale(e,t,n),this.applyMatrix4(fr),this}lookAt(e){return mr.lookAt(e),mr.updateMatrix(),this.applyMatrix4(mr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(gr).negate(),this.translate(gr.x,gr.y,gr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let n=0,i=e.length;nt.count&&qt("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 Fi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Yt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new fn(-1/0,-1/0,-1/0),new fn(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),void 0!==this.parameters&&!0!==this._transformed){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);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 n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=a.toJSON()),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone());const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e1)?null:t.copy(e.start).addScaledVector(i,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<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 n=t||Er.getNormalMatrix(e),i=this.coplanarPoint(Mr).applyMatrix4(e),r=this.normal.applyMatrix3(n).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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}let Rr=0;class Cr extends Jt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Rr++}),this.uuid=sn(),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=S,this.blendDst=T,this.blendEquation=p,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new yi(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=St,this.stencilZFail=St,this.stencilZPass=St,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){qt(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector2&&n&&n.isVector2||i&&i.isEuler&&n&&n.isEuler||i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:qt(`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 n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.retroreflectivity&&(n.retroreflectivity=this.retroreflectivity),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),void 0!==this.rotation&&(n.rotation=this.rotation),void 0!==this.depthPacking&&(n.depthPacking=this.depthPacking),void 0!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.linecap&&(n.linecap=this.linecap),void 0!==this.linejoin&&(n.linejoin=this.linejoin),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),void 0!==this.wireframe&&(n.wireframe=this.wireframe),void 0!==this.wireframeLinewidth&&(n.wireframeLinewidth=this.wireframeLinewidth),void 0!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),void 0!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),void 0!==this.flatShading&&(n.flatShading=this.flatShading),void 0!==this.fog&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}fromJSON(e,t){if(void 0!==e.uuid&&(this.uuid=e.uuid),void 0!==e.name&&(this.name=e.name),void 0!==e.color&&void 0!==this.color&&this.color.setHex(e.color),void 0!==e.roughness&&(this.roughness=e.roughness),void 0!==e.metalness&&(this.metalness=e.metalness),void 0!==e.sheen&&(this.sheen=e.sheen),void 0!==e.sheenColor&&(this.sheenColor=(new yi).setHex(e.sheenColor)),void 0!==e.sheenRoughness&&(this.sheenRoughness=e.sheenRoughness),void 0!==e.emissive&&void 0!==this.emissive&&this.emissive.setHex(e.emissive),void 0!==e.specular&&void 0!==this.specular&&this.specular.setHex(e.specular),void 0!==e.specularIntensity&&(this.specularIntensity=e.specularIntensity),void 0!==e.specularColor&&void 0!==this.specularColor&&this.specularColor.setHex(e.specularColor),void 0!==e.shininess&&(this.shininess=e.shininess),void 0!==e.clearcoat&&(this.clearcoat=e.clearcoat),void 0!==e.clearcoatRoughness&&(this.clearcoatRoughness=e.clearcoatRoughness),void 0!==e.dispersion&&(this.dispersion=e.dispersion),void 0!==e.retroreflectivity&&(this.retroreflectivity=e.retroreflectivity),void 0!==e.iridescence&&(this.iridescence=e.iridescence),void 0!==e.iridescenceIOR&&(this.iridescenceIOR=e.iridescenceIOR),void 0!==e.iridescenceThicknessRange&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),void 0!==e.transmission&&(this.transmission=e.transmission),void 0!==e.thickness&&(this.thickness=e.thickness),void 0!==e.attenuationDistance&&(this.attenuationDistance=e.attenuationDistance),void 0!==e.attenuationColor&&void 0!==this.attenuationColor&&this.attenuationColor.setHex(e.attenuationColor),void 0!==e.anisotropy&&(this.anisotropy=e.anisotropy),void 0!==e.anisotropyRotation&&(this.anisotropyRotation=e.anisotropyRotation),void 0!==e.fog&&(this.fog=e.fog),void 0!==e.flatShading&&(this.flatShading=e.flatShading),void 0!==e.blending&&(this.blending=e.blending),void 0!==e.combine&&(this.combine=e.combine),void 0!==e.side&&(this.side=e.side),void 0!==e.shadowSide&&(this.shadowSide=e.shadowSide),void 0!==e.opacity&&(this.opacity=e.opacity),void 0!==e.transparent&&(this.transparent=e.transparent),void 0!==e.alphaTest&&(this.alphaTest=e.alphaTest),void 0!==e.alphaHash&&(this.alphaHash=e.alphaHash),void 0!==e.depthFunc&&(this.depthFunc=e.depthFunc),void 0!==e.depthTest&&(this.depthTest=e.depthTest),void 0!==e.depthWrite&&(this.depthWrite=e.depthWrite),void 0!==e.colorWrite&&(this.colorWrite=e.colorWrite),void 0!==e.clippingPlanes&&(this.clippingPlanes=e.clippingPlanes.map(e=>(new Ar).fromJSON(e))),void 0!==e.clipIntersection&&(this.clipIntersection=e.clipIntersection),void 0!==e.clipShadows&&(this.clipShadows=e.clipShadows),void 0!==e.depthPacking&&(this.depthPacking=e.depthPacking),void 0!==e.blendSrc&&(this.blendSrc=e.blendSrc),void 0!==e.blendDst&&(this.blendDst=e.blendDst),void 0!==e.blendEquation&&(this.blendEquation=e.blendEquation),void 0!==e.blendSrcAlpha&&(this.blendSrcAlpha=e.blendSrcAlpha),void 0!==e.blendDstAlpha&&(this.blendDstAlpha=e.blendDstAlpha),void 0!==e.blendEquationAlpha&&(this.blendEquationAlpha=e.blendEquationAlpha),void 0!==e.blendColor&&void 0!==this.blendColor&&this.blendColor.setHex(e.blendColor),void 0!==e.blendAlpha&&(this.blendAlpha=e.blendAlpha),void 0!==e.stencilWriteMask&&(this.stencilWriteMask=e.stencilWriteMask),void 0!==e.stencilFunc&&(this.stencilFunc=e.stencilFunc),void 0!==e.stencilRef&&(this.stencilRef=e.stencilRef),void 0!==e.stencilFuncMask&&(this.stencilFuncMask=e.stencilFuncMask),void 0!==e.stencilFail&&(this.stencilFail=e.stencilFail),void 0!==e.stencilZFail&&(this.stencilZFail=e.stencilZFail),void 0!==e.stencilZPass&&(this.stencilZPass=e.stencilZPass),void 0!==e.stencilWrite&&(this.stencilWrite=e.stencilWrite),void 0!==e.wireframe&&(this.wireframe=e.wireframe),void 0!==e.wireframeLinewidth&&(this.wireframeLinewidth=e.wireframeLinewidth),void 0!==e.wireframeLinecap&&(this.wireframeLinecap=e.wireframeLinecap),void 0!==e.wireframeLinejoin&&(this.wireframeLinejoin=e.wireframeLinejoin),void 0!==e.rotation&&(this.rotation=e.rotation),void 0!==e.linewidth&&(this.linewidth=e.linewidth),void 0!==e.linecap&&(this.linecap=e.linecap),void 0!==e.linejoin&&(this.linejoin=e.linejoin),void 0!==e.dashSize&&(this.dashSize=e.dashSize),void 0!==e.gapSize&&(this.gapSize=e.gapSize),void 0!==e.scale&&(this.scale=e.scale),void 0!==e.polygonOffset&&(this.polygonOffset=e.polygonOffset),void 0!==e.polygonOffsetFactor&&(this.polygonOffsetFactor=e.polygonOffsetFactor),void 0!==e.polygonOffsetUnits&&(this.polygonOffsetUnits=e.polygonOffsetUnits),void 0!==e.dithering&&(this.dithering=e.dithering),void 0!==e.alphaToCoverage&&(this.alphaToCoverage=e.alphaToCoverage),void 0!==e.premultipliedAlpha&&(this.premultipliedAlpha=e.premultipliedAlpha),void 0!==e.forceSinglePass&&(this.forceSinglePass=e.forceSinglePass),void 0!==e.allowOverride&&(this.allowOverride=e.allowOverride),void 0!==e.visible&&(this.visible=e.visible),void 0!==e.toneMapped&&(this.toneMapped=e.toneMapped),void 0!==e.userData&&(this.userData=e.userData),void 0!==e.vertexColors&&("number"==typeof e.vertexColors?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),void 0!==e.size&&(this.size=e.size),void 0!==e.sizeAttenuation&&(this.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(this.map=t[e.map]||null),void 0!==e.matcap&&(this.matcap=t[e.matcap]||null),void 0!==e.alphaMap&&(this.alphaMap=t[e.alphaMap]||null),void 0!==e.bumpMap&&(this.bumpMap=t[e.bumpMap]||null),void 0!==e.bumpScale&&(this.bumpScale=e.bumpScale),void 0!==e.normalMap&&(this.normalMap=t[e.normalMap]||null),void 0!==e.normalMapType&&(this.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),this.normalScale=(new dn).fromArray(t)}return void 0!==e.displacementMap&&(this.displacementMap=t[e.displacementMap]||null),void 0!==e.displacementScale&&(this.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(this.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(this.roughnessMap=t[e.roughnessMap]||null),void 0!==e.metalnessMap&&(this.metalnessMap=t[e.metalnessMap]||null),void 0!==e.emissiveMap&&(this.emissiveMap=t[e.emissiveMap]||null),void 0!==e.emissiveIntensity&&(this.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(this.specularMap=t[e.specularMap]||null),void 0!==e.specularIntensityMap&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),void 0!==e.specularColorMap&&(this.specularColorMap=t[e.specularColorMap]||null),void 0!==e.envMap&&(this.envMap=t[e.envMap]||null),void 0!==e.envMapRotation&&this.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(this.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(this.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(this.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(this.lightMap=t[e.lightMap]||null),void 0!==e.lightMapIntensity&&(this.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(this.aoMap=t[e.aoMap]||null),void 0!==e.aoMapIntensity&&(this.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(this.gradientMap=t[e.gradientMap]||null),void 0!==e.clearcoatMap&&(this.clearcoatMap=t[e.clearcoatMap]||null),void 0!==e.clearcoatRoughnessMap&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),void 0!==e.clearcoatNormalMap&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),void 0!==e.clearcoatNormalScale&&(this.clearcoatNormalScale=(new dn).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(this.iridescenceMap=t[e.iridescenceMap]||null),void 0!==e.iridescenceThicknessMap&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),void 0!==e.transmissionMap&&(this.transmissionMap=t[e.transmissionMap]||null),void 0!==e.thicknessMap&&(this.thicknessMap=t[e.thicknessMap]||null),void 0!==e.anisotropyMap&&(this.anisotropyMap=t[e.anisotropyMap]||null),void 0!==e.sheenColorMap&&(this.sheenColorMap=t[e.sheenColorMap]||null),void 0!==e.sheenRoughnessMap&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class Nr extends Cr{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new yi(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Pr=new fn,Lr=new fn,Dr=new fn,Ir=new fn;class Ur{constructor(e=new fn,t=new fn(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,Pr)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Pr.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Pr.copy(this.origin).addScaledVector(this.direction,t),Pr.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Lr.copy(e).add(t).multiplyScalar(.5),Dr.copy(t).sub(e).normalize(),Ir.copy(this.origin).sub(Lr);const r=.5*e.distanceTo(t),s=-this.direction.dot(Dr),a=Ir.dot(this.direction),o=-Ir.dot(Dr),l=Ir.lengthSq(),u=Math.abs(1-s*s);let c,h,d,p;if(u>0)if(c=s*o-a,h=s*a-o,p=r*u,c>=0)if(h>=-p)if(h<=p){const e=1/u;c*=e,h*=e,d=c*(c+s*h+2*a)+h*(s*c+h+2*o)+l}else h=r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*r+a)),h=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(c=Math.max(0,-(s*r+a)),h=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l);else h=s>0?-r:r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,c),i&&i.copy(Lr).addScaledVector(Dr,h),d}intersectSphere(e,t){if(e.radius<0)return null;Pr.subVectors(e.center,this.origin);const n=Pr.dot(this.direction),i=Pr.dot(Pr)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,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 n,i,r,s,a,o;const l=1/this.direction.x,u=1/this.direction.y,c=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),u>=0?(r=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(r=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(e.min.z-h.z)*c,o=(e.max.z-h.z)*c):(a=(e.max.z-h.z)*c,o=(e.min.z-h.z)*c),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Pr)}intersectTriangle(e,t,n,i,r){const s=this.origin,a=this.direction,o=a.x,l=a.y,u=a.z,c=e.x-s.x,h=e.y-s.y,d=e.z-s.z,p=t.x-s.x,f=t.y-s.y,m=t.z-s.z,g=n.x-s.x,_=n.y-s.y,v=n.z-s.z,y=Math.abs(o),b=Math.abs(l),x=Math.abs(u);let S,T,M,w,E,A,R,C,N,P,L,D;if(y>=b&&y>=x?(M=o,A=c,N=p,D=g,o>=0?(S=l,T=u,w=h,E=d,R=f,C=m,P=_,L=v):(S=u,T=l,w=d,E=h,R=m,C=f,P=v,L=_)):b>=x?(M=l,A=h,N=f,D=_,l>=0?(S=u,T=o,w=d,E=c,R=m,C=p,P=v,L=g):(S=o,T=u,w=c,E=d,R=p,C=m,P=g,L=v)):(M=u,A=d,N=m,D=v,u>=0?(S=o,T=l,w=c,E=h,R=p,C=f,P=g,L=_):(S=l,T=o,w=h,E=c,R=f,C=p,P=_,L=g)),0===M)return null;const I=S/M,U=T/M,F=w-I*A,O=E-U*A,B=R-I*N,k=C-U*N,z=P-I*D,V=L-U*D,G=z*k-V*B,H=F*V-O*z,W=B*O-k*F;if(i){if(G<0||H<0||W<0)return null}else if((G<0||H<0||W<0)&&(G>0||H>0||W>0))return null;const j=G+H+W;if(0===j)return null;const $=1/M*(G*A+H*N+W*D);return(j>0?$<0:$>0)?null:this.at($/j,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 Fr extends Cr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new yi(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 qn,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 Or=new Bn,Br=new Ur,kr=new dr,zr=new fn,Vr=new fn,Gr=new fn,Hr=new fn,Wr=new fn,jr=new fn,$r=new fn,Xr=new fn;class qr extends hi{constructor(e=new br,t=new Fr){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}Or.copy(r).invert(),Br.copy(e.ray).applyMatrix4(Or),null!==n.boundingBox&&!1===Br.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,Br)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,u=r.attributes.uv1,c=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;rn.far?null:{distance:u,point:Xr.clone(),object:e}}(e,t,n,i,Vr,Gr,Hr,$r);if(c){const e=new fn;Ui.getBarycoord($r,Vr,Gr,Hr,e),r&&(c.uv=Ui.getInterpolatedAttribute(r,o,l,u,e,new dn)),s&&(c.uv1=Ui.getInterpolatedAttribute(s,o,l,u,e,new dn)),a&&(c.normal=Ui.getInterpolatedAttribute(a,o,l,u,e,new fn),c.normal.dot(i.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new fn,materialIndex:0};Ui.getNormal(Vr,Gr,Hr,t.normal),c.face=t,c.barycoord=e}return c}class Kr extends Ln{constructor(e=null,t=1,n=1,i,r,s,a,o,l=1003,u=1003,c,h){super(null,s,a,o,l,u,i,r,c,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Zr extends rr{constructor(e,t,n,i=1){super(e,t,n),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 Qr=new dr,Jr=new dn(.5,.5),es=new fn;class ts{constructor(e=new Ar,t=new Ar,n=new Ar,i=new Ar,r=new Ar,s=new Ar){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){const i=this.planes,r=e.elements,s=r[0],a=r[1],o=r[2],l=r[3],u=r[4],c=r[5],h=r[6],d=r[7],p=r[8],f=r[9],m=r[10],g=r[11],_=r[12],v=r[13],y=r[14],b=r[15];if(i[0].setComponents(l-s,d-u,g-p,b-_).normalize(),i[1].setComponents(l+s,d+u,g+p,b+_).normalize(),i[2].setComponents(l+a,d+c,g+f,b+v).normalize(),i[3].setComponents(l-a,d-c,g-f,b-v).normalize(),n)i[4].setComponents(o,h,m,y).normalize(),i[5].setComponents(l-o,d-h,g-m,b-y).normalize();else if(i[4].setComponents(l-o,d-h,g-m,b-y).normalize(),t===It)i[5].setComponents(l+o,d+h,g+m,b+y).normalize();else{if(t!==Ut)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,h,m,y).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Qr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Qr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Qr)}intersectsSprite(e){Qr.center.set(0,0,0);const t=Jr.distanceTo(e.center);return Qr.radius=.7071067811865476+t,Qr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Qr)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,es.y=i.normal.y>0?e.max.y:e.min.y,es.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(es)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const ns=new Bn;class is{constructor(){this.coordinateSystem=It,this._frustums=[],this._count=0}setFromArrayCamera(e){const t=e.cameras,n=this._frustums;for(let e=0;ei)return;cs.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(cs);return lt.far?void 0:{distance:l,point:hs.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class ps extends Cr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new yi(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 fs extends Ln{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=se,this.minFilter=se,this.generateMipmaps=!1,this.needsUpdate=!0}}class ms extends Ln{constructor(e=[],t=301,n,i,r,s,a,o,l,u){super(e,t,n,i,r,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class gs extends Ln{constructor(e,t,n=1014,i,r,s,a=1003,o=1003,l,u=1026,c=1){if(u!==Ae&&u!==Re)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:c},i,r,s,a,o,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Rn(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}}class _s extends gs{constructor(e,t=1014,n=301,i,r,s=1003,a=1003,o,l=1026){const u={width:e,height:e,depth:1},c=[u,u,u,u,u,u];super(e,e,t,n,i,r,s,a,o,l),this.image=c,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class vs extends Ln{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ys extends br{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,n,i,r,s,p,f,m,g,_){const v=s/m,y=p/g,b=s/2,x=p/2,S=f/2,T=m+1,M=g+1;let w=0,E=0;const A=new fn;for(let s=0;s0?1:-1,u.push(A.x,A.y,A.z),c.push(o/m),c.push(1-s/g),w+=1}}for(let e=0;e0||0!==i)&&(u.push(s,a,l),v+=3),(t>0||i!==r-1)&&(u.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new lr(c,3)),this.setAttribute("normal",new lr(h,3)),this.setAttribute("uv",new lr(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new bs(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class xs extends bs{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new xs(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ss{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){qt("Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const u=n[i];return(i+(s-u)/(n[i+1]-u))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new dn:new fn);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new fn,i=[],r=[],s=[],a=new fn,o=new Bn;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new fn)}r[0]=new fn,s[0]=new fn;let l=Number.MAX_VALUE;const u=Math.abs(i[0].x),c=Math.abs(i[0].y),h=Math.abs(i[0].z);u<=l&&(l=u,n.set(1,0,0)),c<=l&&(l=c,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(an(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(an(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Ts extends Ss{constructor(e=0,t=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new dn){const n=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===u&&l===r-1&&(l=r-2,u=1),this.closed||l>0?a=i[(l-1)%r]:(Es.subVectors(i[0],i[1]).add(i[0]),a=Es);const c=i[l%r],h=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],c=i[s>i.length-3?i.length-1:s+2];return n.set(Ns(a,o.x,l.x,u.x,c.x),Ns(a,o.y,l.y,u.y,c.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t0)&&d.push(t,r,l),(e!==n-1||o0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),void 0!==e.uniforms)for(const n in e.uniforms){const i=e.uniforms[n];switch(this.uniforms[n]={},i.type){case"t":this.uniforms[n].value=t[i.value]||null;break;case"c":this.uniforms[n].value=(new yi).setHex(i.value);break;case"v2":this.uniforms[n].value=(new dn).fromArray(i.value);break;case"v3":this.uniforms[n].value=(new fn).fromArray(i.value);break;case"v4":this.uniforms[n].value=(new Dn).fromArray(i.value);break;case"m3":this.uniforms[n].value=(new _n).fromArray(i.value);break;case"m4":this.uniforms[n].value=(new Bn).fromArray(i.value);break;default:this.uniforms[n].value=i.value}}if(void 0!==e.defines&&(this.defines=e.defines),void 0!==e.vertexShader&&(this.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(this.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(this.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)this.extensions[t]=e.extensions[t];return void 0!==e.lights&&(this.lights=e.lights),void 0!==e.clipping&&(this.clipping=e.clipping),this}}class $s extends js{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Xs extends Cr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new yi(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 yi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dn(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 qn,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 qs extends Xs{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 dn(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return an(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 yi(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 yi(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new yi(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=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 retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){this._retroreflectivity>0!=e>0&&this.version++,this._retroreflectivity=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.retroreflectivity=e.retroreflectivity,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 Ys extends Cr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new yi(16777215),this.specular=new yi(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new yi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new qn,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ks extends Cr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new yi(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new yi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dn(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 Zs extends Cr{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dn(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 Qs extends Cr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new yi(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new yi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new qn,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Js extends Cr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class ea extends Cr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class ta extends Cr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new yi(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new dn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class na extends rs{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}}const ia={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(ra(e)||(this.files[e]=t))},get:function(e){if(!1!==this.enabled&&!ra(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function ra(e){try{const t=e.slice(e.indexOf(":")+1);return"blob:"===new URL(t).protocol}catch(e){return!1}}class sa{constructor(e,t,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,!1===s&&void 0!==i.onStart&&i.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.onError(e)},this.resolveURL=function(e){return e=e.normalize("NFC"),r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=l.length;te.start-t.start);let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\n#define inverseTransformDirection transformDirectionByInverseViewMatrix\nvec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );\n}\nvec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * reflectVec );\n\t\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 getIBLRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 retroVec = normalize( mix( viewDir, normal, pow4( roughness ) ) );\n\t\t\t\tretroVec = transformDirectionByInverseViewMatrix( retroVec, viewMatrix );\n\t\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * retroVec, roughness );\n\t\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t\t#ifdef USE_RETROREFLECTION\n\t\t\tvec3 getIBLAnisotropyRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\t\treturn getIBLRetroRadiance( viewDir, bentNormal, roughness );\n\t\t\t\t#else\n\t\t\t\t\treturn vec3( 0.0 );\n\t\t\t\t#endif\n\t\t\t}\n\t\t#endif\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_SUN_LIGHTS > 0\n\tstruct SunLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform SunLight sunLights[ NUM_SUN_LIGHTS ];\n\tvoid getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) {\n\t\tlight.color = sunLight.color;\n\t\tlight.direction = sunLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif\n#include ",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_RETROREFLECTION\n\tmaterial.retroreflectivity = retroreflectivity;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\tvec2 dfg;\n\tvec3 multiScatteringCompensation;\n\t#ifdef USE_RETROREFLECTION\n\t\tfloat retroreflectivity;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0Dielectric;\n\t\tvec3 iridescenceF0Metallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\treturn 0.5 / max( gv + gl, EPSILON );\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\tvec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroViewDir = reflect( - geometryViewDir, geometryNormal );\n\t\tvec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material );\n\t\tspecularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation;\n\tvec3 halfDir = normalize( directLight.direction + geometryViewDir );\n\tfloat dotVH = saturate( dot( geometryViewDir, halfDir ) );\n\tvec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroHalfDir = normalize( directLight.direction + retroViewDir );\n\t\tfloat dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) );\n\t\tvec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH );\n\t\tF = mix( F, retroF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering );\n\t#endif\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI;\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tvec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tvec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );\n\t\tmaterial.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );\n\t}\n#endif\n#ifdef STANDARD\n\tfloat dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );\n\tmaterial.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;\n\t#if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )\n\t\tfloat EssMs = material.dfg.x + material.dfg.y;\n\t\tmaterial.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );\n\t#endif\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SUN_LIGHTS > 0 ) && defined( RE_Direct )\n\tSunLight sunLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) {\n\t\tsunLight = sunLights[ i ];\n\t\tgetSunLightInfo( sunLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS )\n\t\tsunLightShadow = sunLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#ifdef USE_LIGHT_PROBES_GRID\n\t\tvec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n\t\tvec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );\n\t\tirradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 iblRadiance = getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tvec3 iblRadiance = getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_RETROREFLECTION\n\t\t#ifdef USE_ANISOTROPY\n\t\t\tvec3 retroIBLRadiance = getIBLAnisotropyRetroRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t\t#else\n\t\t\tvec3 retroIBLRadiance = getIBLRetroRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t\t#endif\n\t\tiblRadiance = mix( iblRadiance, retroIBLRadiance, saturate( material.retroreflectivity ) );\n\t#endif\n\tradiance += iblRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",lightprobes_pars_fragment:"#ifdef USE_LIGHT_PROBES_GRID\nuniform highp sampler3D probesSH;\nuniform vec3 probesMin;\nuniform vec3 probesMax;\nuniform vec3 probesResolution;\nvec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {\n\tvec3 res = probesResolution;\n\tvec3 gridRange = probesMax - probesMin;\n\tvec3 resMinusOne = res - 1.0;\n\tvec3 probeSpacing = gridRange / resMinusOne;\n\tvec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;\n\tvec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );\n\tuvw = uvw * resMinusOne / res + 0.5 / res;\n\tfloat nz = res.z;\n\tfloat paddedSlices = nz + 2.0;\n\tfloat atlasDepth = 7.0 * paddedSlices;\n\tfloat uvZBase = uvw.z * nz + 1.0;\n\tvec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );\n\tvec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );\n\tvec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );\n\tvec3 c0 = s0.xyz;\n\tvec3 c1 = vec3( s0.w, s1.xy );\n\tvec3 c2 = vec3( s1.zw, s2.x );\n\tvec3 c3 = s2.yzw;\n\tvec3 c4 = s3.xyz;\n\tvec3 c5 = vec3( s3.w, s4.xy );\n\tvec3 c6 = vec3( s4.zw, s5.x );\n\tvec3 c7 = s5.yzw;\n\tvec3 c8 = s6.xyz;\n\tfloat x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;\n\tvec3 result = c0 * 0.886227;\n\tresult += c1 * 2.0 * 0.511664 * y;\n\tresult += c2 * 2.0 * 0.511664 * z;\n\tresult += c3 * 2.0 * 0.511664 * x;\n\tresult += c4 * 2.0 * 0.429043 * x * y;\n\tresult += c5 * 2.0 * 0.429043 * y * z;\n\tresult += c6 * ( 0.743125 * z * z - 0.247708 );\n\tresult += c7 * 2.0 * 0.429043 * x * z;\n\tresult += c8 * 0.429043 * ( x * x - y * y );\n\treturn max( result, vec3( 0.0 ) );\n}\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#if defined( USE_PACKED_NORMALMAP )\n\t\tmapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );\n\t#endif\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t\t#ifdef FLIP_SIDED\n\t\t\tvBitangent = - vBitangent;\n\t\t#endif\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\t#define SUN_LIGHT_CASCADES 2\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tuniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];\n\t\tuniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t\tstruct SunLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tfloat getSunShadow(\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\t\tsampler2DShadow shadowMap,\n\t\t\t#else\n\t\t\t\tsampler2D shadowMap,\n\t\t\t#endif\n\t\t\tSunLightShadow sunLightShadow,\n\t\t\tint shadowIndex\n\t\t) {\n\t\t\tvec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 );\n\t\t\tfloat viewDepth = vSunShadowWorldPosition.w;\n\t\t\tint cascadeOffset = shadowIndex * SUN_LIGHT_CASCADES;\n\t\t\tfloat shadow = 1.0;\n\t\t\tfor ( int i = SUN_LIGHT_CASCADES - 1; i >= 0; i -- ) {\n\t\t\t\tvec4 cascade = sunShadowCascade[ cascadeOffset + i ];\n\t\t\t\tif ( viewDepth >= cascade.x && viewDepth < cascade.y ) {\n\t\t\t\t\tfloat cascadeShadow = getShadow(\n\t\t\t\t\t\tshadowMap,\n\t\t\t\t\t\tsunLightShadow.shadowMapSize,\n\t\t\t\t\t\tsunLightShadow.shadowIntensity,\n\t\t\t\t\t\tsunLightShadow.shadowBias,\n\t\t\t\t\t\tsunLightShadow.shadowRadius,\n\t\t\t\t\t\tsunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition\n\t\t\t\t\t);\n\t\t\t\t\tshadow = mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn shadow;\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#ifdef HAS_NORMAL\n\t\tvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t#else\n\t\tvec3 shadowWorldNormal = vec3( 0.0 );\n\t#endif\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z );\n\t\tvSunShadowWorldNormal = shadowWorldNormal;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) {\n\t\tsunLight = sunLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distance_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_RETROREFLECTION\n\tuniform float retroreflectivity;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},Qa={common:{diffuse:{value:new yi(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new _n},alphaMap:{value:null},alphaMapTransform:{value:new _n},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new _n}},envmap:{envMap:{value:null},envMapRotation:{value:new _n},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new _n}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new _n}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new _n},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new _n},normalScale:{value:new dn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new _n},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new _n}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new _n}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new _n}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new yi(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new fn},probesMax:{value:new fn},probesResolution:{value:new fn}},points:{diffuse:{value:new yi(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new _n},alphaTest:{value:0},uvTransform:{value:new _n}},sprite:{diffuse:{value:new yi(16777215)},opacity:{value:1},center:{value:new dn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new _n},alphaMap:{value:null},alphaMapTransform:{value:new _n},alphaTest:{value:0}}},Ja={basic:{uniforms:Vs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.fog]),vertexShader:Za.meshbasic_vert,fragmentShader:Za.meshbasic_frag},lambert:{uniforms:Vs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new yi(0)},envMapIntensity:{value:1}}]),vertexShader:Za.meshlambert_vert,fragmentShader:Za.meshlambert_frag},phong:{uniforms:Vs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new yi(0)},specular:{value:new yi(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Za.meshphong_vert,fragmentShader:Za.meshphong_frag},standard:{uniforms:Vs([Qa.common,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.roughnessmap,Qa.metalnessmap,Qa.fog,Qa.lights,{emissive:{value:new yi(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag},toon:{uniforms:Vs([Qa.common,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.gradientmap,Qa.fog,Qa.lights,{emissive:{value:new yi(0)}}]),vertexShader:Za.meshtoon_vert,fragmentShader:Za.meshtoon_frag},matcap:{uniforms:Vs([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,{matcap:{value:null}}]),vertexShader:Za.meshmatcap_vert,fragmentShader:Za.meshmatcap_frag},points:{uniforms:Vs([Qa.points,Qa.fog]),vertexShader:Za.points_vert,fragmentShader:Za.points_frag},dashed:{uniforms:Vs([Qa.common,Qa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Za.linedashed_vert,fragmentShader:Za.linedashed_frag},depth:{uniforms:Vs([Qa.common,Qa.displacementmap]),vertexShader:Za.depth_vert,fragmentShader:Za.depth_frag},normal:{uniforms:Vs([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,{opacity:{value:1}}]),vertexShader:Za.meshnormal_vert,fragmentShader:Za.meshnormal_frag},sprite:{uniforms:Vs([Qa.sprite,Qa.fog]),vertexShader:Za.sprite_vert,fragmentShader:Za.sprite_frag},background:{uniforms:{uvTransform:{value:new _n},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Za.background_vert,fragmentShader:Za.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new _n}},vertexShader:Za.backgroundCube_vert,fragmentShader:Za.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Za.cube_vert,fragmentShader:Za.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Za.equirect_vert,fragmentShader:Za.equirect_frag},distance:{uniforms:Vs([Qa.common,Qa.displacementmap,{referencePosition:{value:new fn},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Za.distance_vert,fragmentShader:Za.distance_frag},shadow:{uniforms:Vs([Qa.lights,Qa.fog,{color:{value:new yi(0)},opacity:{value:1}}]),vertexShader:Za.shadow_vert,fragmentShader:Za.shadow_frag}};Ja.physical={uniforms:Vs([Ja.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new _n},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new _n},clearcoatNormalScale:{value:new dn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new _n},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new _n},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new _n},sheen:{value:0},sheenColor:{value:new yi(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new _n},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new _n},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new _n},transmissionSamplerSize:{value:new dn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new _n},attenuationDistance:{value:0},attenuationColor:{value:new yi(0)},specularColor:{value:new yi(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new _n},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new _n},anisotropyVector:{value:new dn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new _n}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag};const eo={r:0,b:0,g:0},to=new Bn,no=new _n;function io(e,t,n,i,r,s){const a=new yi(0);let o,l,u=!0===r?0:1,c=null,h=0,d=null;function p(e){let n=!0===e.isScene?e.background:null;if(n&&n.isTexture){const i=e.backgroundBlurriness>0;n=t.get(n,i)}return n}function f(t,i){t.getRGB(eo,Hs(e)),n.buffers.color.setClear(eo.r,eo.g,eo.b,i,s)}return{getClearColor:function(){return a},setClearColor:function(e,t=1){a.set(e),u=t,f(a,u)},getClearAlpha:function(){return u},setClearAlpha:function(e){u=e,f(a,u)},render:function(t){let i=!1;const r=p(t);null===r?f(a,u):r&&r.isColor&&(f(r,1),i=!0);const o=e.xr.getEnvironmentBlendMode();"additive"===o?n.buffers.color.setClear(0,0,0,1,s):"alpha-blend"===o&&n.buffers.color.setClear(0,0,0,0,s),(e.autoClear||i)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const r=p(n);r&&(r.isCubeTexture||r.mapping===te)?(void 0===l&&(l=new qr(new ys(1,1,1),new js({name:"BackgroundCubeMaterial",uniforms:zs(Ja.backgroundCube.uniforms),vertexShader:Ja.backgroundCube.vertexShader,fragmentShader:Ja.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l)),l.material.uniforms.envMap.value=r,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(to.makeRotationFromEuler(n.backgroundRotation)).transpose(),r.isCubeTexture&&!1===r.isRenderTargetTexture&&l.material.uniforms.backgroundRotation.value.premultiply(no),l.material.toneMapped=Sn.getTransfer(r.colorSpace)!==xt,c===r&&h===r.version&&d===e.toneMapping||(l.material.needsUpdate=!0,c=r,h=r.version,d=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):r&&r.isTexture&&(void 0===o&&(o=new qr(new Fs(2,2),new js({name:"BackgroundMaterial",uniforms:zs(Ja.background.uniforms),vertexShader:Ja.background.vertexShader,fragmentShader:Ja.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),o.geometry.deleteAttribute("normal"),Object.defineProperty(o.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(o)),o.material.uniforms.t2D.value=r,o.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,o.material.toneMapped=Sn.getTransfer(r.colorSpace)!==xt,!0===r.matrixAutoUpdate&&r.updateMatrix(),o.material.uniforms.uvTransform.value.copy(r.matrix),c===r&&h===r.version&&d===e.toneMapping||(o.material.needsUpdate=!0,c=r,h=r.version,d=e.toneMapping),o.layers.enableAll(),t.unshift(o,o.geometry,o.material,0,0,null))},dispose:function(){void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0),void 0!==o&&(o.geometry.dispose(),o.material.dispose(),o=void 0)}}}function ro(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=u(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],i=[],r=[];for(let e=0;e=0){const n=r[t];let i=a[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,m,l,g),_&&function(e,t,n,i){const r={},a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=a[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,i,r,s){c();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const u=l.buffer,c=l.type,p=l.bytesPerElement,m=c===e.INT||c===e.UNSIGNED_INT||o.gpuType===me;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(qt("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,u=!0===n.reversedDepthBuffer&&t.has("EXT_clip_control");!0===n.reversedDepthBuffer&&!1===u&&qt("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===Ee||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===ve&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==he&&n!==_e&&!r&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))},precision:a,logarithmicDepthBuffer:l,reversedDepthBuffer:u,maxTextures:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),maxVertexTextures:e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),maxSamples:e.getParameter(e.MAX_SAMPLES),samples:e.getParameter(e.SAMPLES)}}function oo(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new Ar,o=new _n,l={value:null,needsUpdate:!1};function u(e,n,i,r){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==r||null===u){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===u||u.length0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=f.clippingState||null;l.value=r,r=u(h,o,t,c);for(let e=0;e!==t;++e)r[e]=n[e];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}no.set(-1,0,0,0,1,0,0,0,1);const lo=new Ra,uo=new yi;let co=null,ho=0,po=0,fo=!1;const mo=new fn,go=new fn;let _o=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=mo}=r;co=this._renderer.getRenderTarget(),ho=this._renderer.getActiveCubeFace(),po=this._renderer.getActiveMipmapLevel(),fo=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=xo(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=bo(),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())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];h.set(i,c*u*e);for(let t=0;t4&&i--}return{lodMeshes:n,sizeLods:t}}(i)),this._blurMaterial=function(e,t,n){const i=new js({name:"SphericalGaussianBlur",defines:{SAMPLES:20,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:So(),fragmentShader:"\n\n\t\t\tprecision highp float;\n\t\t\tprecision highp int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform float sigma;\n\t\t\tuniform float mipInt;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\t#define PI 3.14159265359\n\t\t\t#define GOLDEN_ANGLE 2.39996322973\n\n\t\t\tvoid main() {\n\n\t\t\t\tif ( sigma == 0.0 ) {\n\n\t\t\t\t\tgl_FragColor = vec4( bilinearCubeUV( envMap, vOutputDirection, mipInt ), 1.0 );\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\n\t\t\t\tvec3 up = abs( outputDirection.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\t\tvec3 tangent = normalize( cross( up, outputDirection ) );\n\t\t\t\tvec3 bitangent = cross( outputDirection, tangent );\n\n\t\t\t\t// Truncate the kernel at three standard deviations or at the antipode.\n\t\t\t\tfloat thetaMax = min( 3.0 * sigma, PI );\n\t\t\t\tfloat truncation = 1.0 - exp( - 0.5 * thetaMax * thetaMax / ( sigma * sigma ) );\n\n\t\t\t\tvec3 accumColor = vec3( 0.0 );\n\t\t\t\tfloat accumWeight = 0.0;\n\n\t\t\t\tfor ( int i = 0; i < SAMPLES; i ++ ) {\n\n\t\t\t\t\t// Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral.\n\t\t\t\t\tfloat stratum = ( float( i ) + 0.5 ) / float( SAMPLES );\n\t\t\t\t\tfloat theta = sigma * sqrt( - 2.0 * log( 1.0 - stratum * truncation ) );\n\t\t\t\t\tfloat phi = float( i ) * GOLDEN_ANGLE;\n\n\t\t\t\t\tvec3 offset = cos( phi ) * tangent + sin( phi ) * bitangent;\n\t\t\t\t\tvec3 sampleDirection = cos( theta ) * outputDirection + sin( theta ) * offset;\n\n\t\t\t\t\t// Correct the planar sample density to solid angle.\n\t\t\t\t\tfloat weight = sin( theta ) / theta;\n\n\t\t\t\t\taccumColor += weight * bilinearCubeUV( envMap, sampleDirection, mipInt );\n\t\t\t\t\taccumWeight += weight;\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = vec4( accumColor / accumWeight, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return i}(i,e,t),this._ggxMaterial=function(e,t,n){const i=new js({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:256,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:So(),fragmentShader:'\n\n\t\t\tprecision highp float;\n\t\t\tprecision highp int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform float roughness;\n\t\t\tuniform float mipInt;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\t#define PI 3.14159265359\n\n\t\t\t// Van der Corput radical inverse\n\t\t\tfloat radicalInverse_VdC(uint bits) {\n\t\t\t\tbits = (bits << 16u) | (bits >> 16u);\n\t\t\t\tbits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n\t\t\t\tbits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n\t\t\t\tbits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n\t\t\t\tbits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n\t\t\t\treturn float(bits) * 2.3283064365386963e-10; // / 0x100000000\n\t\t\t}\n\n\t\t\t// Hammersley sequence\n\t\t\tvec2 hammersley(uint i, uint N) {\n\t\t\t\treturn vec2(float(i) / float(N), radicalInverse_VdC(i));\n\t\t\t}\n\n\t\t\t// GGX VNDF importance sampling (Eric Heitz 2018)\n\t\t\t// "Sampling the GGX Distribution of Visible Normals"\n\t\t\t// https://jcgt.org/published/0007/04/01/\n\t\t\tvec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {\n\t\t\t\tfloat alpha = roughness * roughness;\n\n\t\t\t\t// Section 4.1: Orthonormal basis\n\t\t\t\tvec3 T1 = vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 T2 = cross(V, T1);\n\n\t\t\t\t// Section 4.2: Parameterization of projected area\n\t\t\t\tfloat r = sqrt(Xi.x);\n\t\t\t\tfloat phi = 2.0 * PI * Xi.y;\n\t\t\t\tfloat t1 = r * cos(phi);\n\t\t\t\tfloat t2 = r * sin(phi);\n\t\t\t\tfloat s = 0.5 * (1.0 + V.z);\n\t\t\t\tt2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;\n\n\t\t\t\t// Section 4.3: Reprojection onto hemisphere\n\t\t\t\tvec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;\n\n\t\t\t\t// Section 3.4: Transform back to ellipsoid configuration\n\t\t\t\treturn normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));\n\t\t\t}\n\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(vOutputDirection);\n\t\t\t\tvec3 V = N; // Assume view direction equals normal for pre-filtering\n\n\t\t\t\tvec3 prefilteredColor = vec3(0.0);\n\t\t\t\tfloat totalWeight = 0.0;\n\n\t\t\t\t// For very low roughness, just sample the environment directly\n\t\t\t\tif (roughness < 0.001) {\n\t\t\t\t\tgl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Tangent space basis for VNDF sampling\n\t\t\t\tvec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 tangent = normalize(cross(up, N));\n\t\t\t\tvec3 bitangent = cross(N, tangent);\n\n\t\t\t\tfor(uint i = 0u; i < uint(GGX_SAMPLES); i++) {\n\t\t\t\t\tvec2 Xi = hammersley(i, uint(GGX_SAMPLES));\n\n\t\t\t\t\t// For PMREM, V = N, so in tangent space V is always (0, 0, 1)\n\t\t\t\t\tvec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);\n\n\t\t\t\t\t// Transform H back to world space\n\t\t\t\t\tvec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);\n\t\t\t\t\tvec3 L = normalize(2.0 * dot(V, H) * H - V);\n\n\t\t\t\t\tfloat NdotL = max(dot(N, L), 0.0);\n\n\t\t\t\t\tif(NdotL > 0.0) {\n\t\t\t\t\t\t// Sample environment at fixed mip level\n\t\t\t\t\t\t// VNDF importance sampling handles the distribution filtering\n\t\t\t\t\t\tvec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);\n\n\t\t\t\t\t\t// Weight by NdotL for the split-sum approximation\n\t\t\t\t\t\t// VNDF PDF naturally accounts for the visible microfacet distribution\n\t\t\t\t\t\tprefilteredColor += sampleColor * NdotL;\n\t\t\t\t\t\ttotalWeight += NdotL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (totalWeight > 0.0) {\n\t\t\t\t\tprefilteredColor = prefilteredColor / totalWeight;\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = vec4(prefilteredColor, 1.0);\n\t\t\t}\n\t\t',blending:0,depthTest:!1,depthWrite:!1});return i}(i,e,t)}return i}_compileMaterial(e){const t=new qr(new br,e);this._renderer.compile(t,lo)}_sceneToCubeUV(e,t,n,i,r){const s=new Ta(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,u=l.autoClear,c=l.toneMapping;l.getClearColor(uo),l.toneMapping=0,l.autoClear=!1;l.state.buffers.depth.getReversed()&&(l.setRenderTarget(i),l.clearDepth(),l.setRenderTarget(null)),null===this._backgroundBox&&(this._backgroundBox=new qr(new ys,new Fr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let p=!1;const f=e.background;f?f.isColor&&(d.color.copy(f),e.background=null,p=!0):(d.color.copy(uo),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;yo(i,n*u,t>2?u:0,u,u),l.setRenderTarget(i),p&&l.render(h,s),l.render(e,s)}l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===Z||e.mapping===Q;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=xo()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=bo());const r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;r.uniforms.envMap.value=e;const a=this._cubeSize;yo(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,lo)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;th-4?n-h+4:0),f=4*(this._cubeSize-d);o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,yo(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,lo),o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,yo(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,lo)}_blur(e,t,n,i){const r=this._pingPongRenderTarget,s=Math.min(i,Math.PI)/Math.SQRT2;this._blurPass(e,r,t,n,s),this._blurPass(r,e,n,n,s)}_blurPass(e,t,n,i,r){const s=this._renderer,a=this._blurMaterial,o=this._lodMeshes[i];o.material=a;const l=a.uniforms;l.envMap.value=e.texture,l.sigma.value=r,l.mipInt.value=this._lodMax-n;const u=this._sizeLods[i];yo(t,3*u*(i>this._lodMax-4?i-this._lodMax+4:0),4*(this._cubeSize-u),3*u,2*u),s.setRenderTarget(t),s.render(o,lo)}};function vo(e,t,n){const i=new Un(e,t,n);return i.texture.mapping=te,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function yo(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function bo(){return new js({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:So(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function xo(){return new js({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:So(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function So(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 outputDirection;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = outputDirection;\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}class To extends Un{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new ms(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={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 \n\t\t\t\t\t#include \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 \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 ys(5,5,5),r=new js({name:"CubemapFromEquirect",uniforms:zs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new qr(i,r),a=t.minFilter;t.minFilter===ce&&(t.minFilter=le);return new Fa(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}function Mo(e){let t=new WeakMap,n=new WeakMap,i=null;function r(e,t){return t===J?e.mapping=Z:t===ee&&(e.mapping=Q),e}function s(e){const n=e.target;n.removeEventListener("dispose",s);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}function a(e){const t=e.target;t.removeEventListener("dispose",a);const i=n.get(t);void 0!==i&&(n.delete(t),i.dispose())}return{get:function(o,l=!1){return null==o?null:l?function(t){if(t&&t.isTexture){const r=t.mapping,s=r===J||r===ee,o=r===Z||r===Q;if(s||o){let r=n.get(t);const l=void 0!==r?r.texture.pmremVersion:0;if(t.isRenderTargetTexture&&t.pmremVersion!==l)return null===i&&(i=new _o(e)),r=s?i.fromEquirectangular(t,r):i.fromCubemap(t,r),r.texture.pmremVersion=t.pmremVersion,n.set(t,r),r.texture;if(void 0!==r)return r.texture;{const l=t.image;return s&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let i=0;i0){const a=new To(i.height);return a.fromEquirectangularTexture(e,n),t.set(n,a),n.addEventListener("dispose",s),r(a.texture,n.mapping)}return null}}}return n}(o)},dispose:function(){t=new WeakMap,n=new WeakMap,null!==i&&(i.dispose(),i=null)}}}function wo(e){const t={};function n(n){if(void 0!==t[n])return t[n];const i=e.getExtension(n);return t[n]=i,i}return{has:function(e){return null!==n(e)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(e){const t=n(e);return null===t&&Kt("WebGLRenderer: "+e+" extension not supported."),t}}}function Eo(e,t,n,i){const r={},s=new WeakMap;function a(e){const o=e.target;null!==o.index&&t.remove(o.index);for(const e in o.attributes)t.remove(o.attributes[e]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(t.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(e){const n=[],i=e.index,r=e.attributes.position;let a=0;if(void 0===r)return;if(null!==i){const e=i.array;a=i.version;for(let t=0,i=e.length;t=65535?ar:sr)(n,1);o.version=a;const l=s.get(e);l&&t.remove(l),s.set(e,o)}return{get:function(e,t){return!0===r[t.id]||(t.addEventListener("dispose",a),r[t.id]=!0,n.memory.geometries++),t},update:function(n){const i=n.attributes;for(const n in i)t.update(i[n],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const n=e.index;null!==n&&t.versiont.maxTextureSize&&(b=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const x=new Float32Array(y*b*4*c),S=new Fn(x,y,b,c);S.type=_e,S.needsUpdate=!0;const T=4*v;for(let w=0;w\n\t\t\t#include \n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = texture2D( tDiffuse, vUv );\n\n\t\t\t\t#ifdef LINEAR_TONE_MAPPING\n\t\t\t\t\tgl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( REINHARD_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CINEON_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( ACES_FILMIC_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( AGX_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( NEUTRAL_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CUSTOM_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef SRGB_TRANSFER\n\t\t\t\t\tgl_FragColor = sRGBTransferOETF( gl_FragColor );\n\t\t\t\t#endif\n\t\t\t}",depthTest:!1,depthWrite:!1}),h=new qr(u,c),d=new Ra(-1,1,1,-1,0,1);let p,f=null,m=null,g=!1,_=null,v=[],y=!1;this.setSize=function(e,t){a.setSize(e,t),null!==o&&o.setSize(e,t),null!==l&&l.setSize(e,t);for(let n=0;n0&&!0===v[0].isRenderPass;const t=a.width,n=a.height;v.length>0&&null===o&&(o=new Un(t,n,{type:ve,depthBuffer:!1,stencilBuffer:!1}),l=new Un(t,n,{type:ve,depthBuffer:!1,stencilBuffer:!1}));for(let e=0;e0)return e;const r=t*n;let s=Bo[r];if(void 0===s&&(s=new Float32Array(r),Bo[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function Wo(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n0&&(this.seq=i.concat(r))}setValue(e,t,n,i){const r=this.map[t];void 0!==r&&r.setValue(e,n,i)}setOptional(e,t,n){const i=t[n];void 0!==i&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,s=t.length;r!==s;++r){const s=t[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,i)}}static seqWithValue(e,t){const n=[];for(let i=0,r=e.length;i!==r;++i){const r=e[i];r.id in t&&n.push(r)}return n}}function Bl(e,t,n){const i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}let kl=0;const zl=new _n;function Vl(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+function(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function Gl(e,t){const n=function(e){Sn._getMatrix(zl,Sn.workingColorSpace,e);const t=`mat3( ${zl.elements.map(e=>e.toFixed(4))} )`;switch(Sn.getTransfer(e)){case bt:return[t,"LinearTransferOETF"];case xt:return[t,"sRGBTransferOETF"];default:return qt("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}const Hl={[W]:"Linear",[j]:"Reinhard",[$]:"Cineon",[X]:"ACESFilmic",[Y]:"AgX",[K]:"Neutral",[q]:"Custom"};function Wl(e,t){const n=Hl[t];return void 0===n?(qt("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const jl=new fn;function $l(){Sn.getLuminanceCoefficients(jl);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${jl.x.toFixed(4)}, ${jl.y.toFixed(4)}, ${jl.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function Xl(e){return""!==e}function ql(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Yl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Kl=/^[ \t]*#include +<([\w\d./]+)>/gm;function Zl(e){return e.replace(Kl,Jl)}const Ql=new Map;function Jl(e,t){let n=Za[t];if(void 0===n){const e=Ql.get(t);if(void 0===e)throw new Error("THREE.WebGLProgram: Can not resolve #include <"+t+">");n=Za[e],qt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Zl(n)}const eu=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function tu(e){return e.replace(eu,nu)}function nu(e,t,n,i){let r="";for(let e=parseInt(t);e0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(Xl).join("\n"),_.length>0&&(_+="\n")):(g=[iu(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexNormals?"#define HAS_NORMAL":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Xl).join("\n"),_=[iu(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.retroreflection?"#define USE_RETROREFLECTION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas||n.batchingColor?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Za.tonemapping_pars_fragment:"",0!==n.toneMapping?Wl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Za.colorspace_pars_fragment,Gl("linearToOutputTexel",n.outputColorSpace),$l(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(Xl).join("\n")),a=Zl(a),a=ql(a,n),a=Yl(a,n),o=Zl(o),o=ql(o,n),o=Yl(o,n),a=tu(a),o=tu(o),!0!==n.isRawShaderMaterial&&(v="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",n.glslVersion===Dt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Dt?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+_);const y=v+g+a,b=v+_+o,x=Bl(r,r.VERTEX_SHADER,y),S=Bl(r,r.FRAGMENT_SHADER,b);function T(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(m)||"",i=r.getShaderInfoLog(x)||"",s=r.getShaderInfoLog(S)||"",a=n.trim(),o=i.trim(),l=s.trim();let u=!0,c=!0;if(!1===r.getProgramParameter(m,r.LINK_STATUS))if(u=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,m,x,S);else{const e=Vl(r,x,"vertex"),n=Vl(r,S,"fragment");Yt("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+a+"\n"+e+"\n"+n)}else""!==a?qt("WebGLProgram: Program Info Log:",a):""!==o&&""!==l||(c=!1);c&&(t.diagnostics={runnable:u,programLog:a,vertexShader:{log:o,prefix:g},fragmentShader:{log:l,prefix:_}})}r.deleteShader(x),r.deleteShader(S),M=new Ol(r,m),w=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r0,X=r.clearcoat>0,q=r.dispersion>0,Y=r.retroreflectivity>0,K=r.iridescence>0,Z=r.sheen>0,Q=r.transmission>0,J=$&&!!r.anisotropyMap,ee=X&&!!r.clearcoatMap,ne=X&&!!r.clearcoatNormalMap,ie=X&&!!r.clearcoatRoughnessMap,re=K&&!!r.iridescenceMap,se=K&&!!r.iridescenceThicknessMap,ae=Z&&!!r.sheenColorMap,oe=Z&&!!r.sheenRoughnessMap,le=!!r.specularMap,ue=!!r.specularColorMap,ce=!!r.specularIntensityMap,he=Q&&!!r.transmissionMap,de=Q&&!!r.thicknessMap,pe=!!r.gradientMap,fe=!!r.alphaMap,me=r.alphaTest>0,ge=!!r.alphaHash,_e=!!r.extensions;let ve=0;r.toneMapped&&(null!==P&&!0!==P.isXRRenderTarget||(ve=e.toneMapping));const ye={shaderID:T,shaderType:r.type,shaderName:r.name,vertexShader:E,fragmentShader:A,defines:r.defines,customVertexShaderID:R,customFragmentShaderID:C,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.glslVersion,precision:d,batching:I,batchingColor:I&&null!==m._colorsTexture,instancing:D,instancingColor:D&&null!==m.instanceColor,instancingMorph:D&&null!==m.morphTexture,outputColorSpace:null===P?e.outputColorSpace:!0===P.isXRRenderTarget?P.texture.colorSpace:Sn.workingColorSpace,alphaToCoverage:!!r.alphaToCoverage,map:U,matcap:F,envMap:O,envMapMode:O&&x.mapping,envMapCubeUVHeight:S,aoMap:B,lightMap:k,bumpMap:z,normalMap:V,displacementMap:G,emissiveMap:H,normalMapObjectSpace:V&&1===r.normalMapType,normalMapTangentSpace:V&&0===r.normalMapType,packedNormalMap:V&&0===r.normalMapType&&du(r.normalMap.format),metalnessMap:W,roughnessMap:j,anisotropy:$,anisotropyMap:J,clearcoat:X,clearcoatMap:ee,clearcoatNormalMap:ne,clearcoatRoughnessMap:ie,dispersion:q,retroreflection:Y,iridescence:K,iridescenceMap:re,iridescenceThicknessMap:se,sheen:Z,sheenColorMap:ae,sheenRoughnessMap:oe,specularMap:le,specularColorMap:ue,specularIntensityMap:ce,transmission:Q,transmissionMap:he,thicknessMap:de,gradientMap:pe,opaque:!1===r.transparent&&1===r.blending&&!1===r.alphaToCoverage,alphaMap:fe,alphaTest:me,alphaHash:ge,combine:r.combine,mapUv:U&&f(r.map.channel),aoMapUv:B&&f(r.aoMap.channel),lightMapUv:k&&f(r.lightMap.channel),bumpMapUv:z&&f(r.bumpMap.channel),normalMapUv:V&&f(r.normalMap.channel),displacementMapUv:G&&f(r.displacementMap.channel),emissiveMapUv:H&&f(r.emissiveMap.channel),metalnessMapUv:W&&f(r.metalnessMap.channel),roughnessMapUv:j&&f(r.roughnessMap.channel),anisotropyMapUv:J&&f(r.anisotropyMap.channel),clearcoatMapUv:ee&&f(r.clearcoatMap.channel),clearcoatNormalMapUv:ne&&f(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ie&&f(r.clearcoatRoughnessMap.channel),iridescenceMapUv:re&&f(r.iridescenceMap.channel),iridescenceThicknessMapUv:se&&f(r.iridescenceThicknessMap.channel),sheenColorMapUv:ae&&f(r.sheenColorMap.channel),sheenRoughnessMapUv:oe&&f(r.sheenRoughnessMap.channel),specularMapUv:le&&f(r.specularMap.channel),specularColorMapUv:ue&&f(r.specularColorMap.channel),specularIntensityMapUv:ce&&f(r.specularIntensityMap.channel),transmissionMapUv:he&&f(r.transmissionMap.channel),thicknessMapUv:de&&f(r.thicknessMap.channel),alphaMapUv:fe&&f(r.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(V||$),vertexNormals:!!v.attributes.normal,vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!v.attributes.color&&4===v.attributes.color.itemSize,pointsUvs:!0===m.isPoints&&!!v.attributes.uv&&(U||fe),fog:!!_,useFog:!0===r.fog,fogExp2:!!_&&_.isFogExp2,flatShading:!1===r.wireframe&&(!0===r.flatShading||void 0===v.attributes.normal&&!1===V&&(r.isMeshLambertMaterial||r.isMeshPhongMaterial||r.isMeshStandardMaterial||r.isMeshPhysicalMaterial)),sizeAttenuation:!0===r.sizeAttenuation,logarithmicDepthBuffer:h,reversedDepthBuffer:L,skinning:!0===m.isSkinnedMesh,hasPositionAttribute:void 0!==v.attributes.position,morphTargets:void 0!==v.morphAttributes.position,morphNormals:void 0!==v.morphAttributes.normal,morphColors:void 0!==v.morphAttributes.color,morphTargetsCount:w,morphTextureStride:N,numSunLights:a.sun.length,numDirLights:a.directional.length,numPointLights:a.point.length,numSpotLights:a.spot.length,numSpotLightMaps:a.spotLightMap.length,numRectAreaLights:a.rectArea.length,numHemiLights:a.hemi.length,numSunLightShadows:a.sunShadowMap.length,numDirLightShadows:a.directionalShadowMap.length,numPointLightShadows:a.pointShadowMap.length,numSpotLightShadows:a.spotShadowMap.length,numSpotLightShadowsWithMaps:a.numSpotLightShadowsWithMaps,numLightProbes:a.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:r.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:ve,decodeVideoTexture:U&&!0===r.map.isVideoTexture&&Sn.getTransfer(r.map.colorSpace)===xt,decodeVideoTextureEmissive:H&&!0===r.emissiveMap.isVideoTexture&&Sn.getTransfer(r.emissiveMap.colorSpace)===xt,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionClipCullDistance:_e&&!0===r.extensions.clipCullDistance&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(_e&&!0===r.extensions.multiDraw||I)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:r.customProgramCacheKey()};return ye.vertexUv1s=l.has(1),ye.vertexUv2s=l.has(2),ye.vertexUv3s=l.has(3),l.clear(),ye},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){a.disableAll(),t.instancing&&a.enable(0);t.instancingColor&&a.enable(1);t.instancingMorph&&a.enable(2);t.matcap&&a.enable(3);t.envMap&&a.enable(4);t.normalMapObjectSpace&&a.enable(5);t.normalMapTangentSpace&&a.enable(6);t.clearcoat&&a.enable(7);t.iridescence&&a.enable(8);t.alphaTest&&a.enable(9);t.vertexColors&&a.enable(10);t.vertexAlphas&&a.enable(11);t.vertexUv1s&&a.enable(12);t.vertexUv2s&&a.enable(13);t.vertexUv3s&&a.enable(14);t.vertexTangents&&a.enable(15);t.anisotropy&&a.enable(16);t.alphaHash&&a.enable(17);t.batching&&a.enable(18);t.dispersion&&a.enable(19);t.retroreflection&&a.enable(24);t.batchingColor&&a.enable(20);t.gradientMap&&a.enable(21);t.packedNormalMap&&a.enable(22);t.vertexNormals&&a.enable(23);e.push(a.mask),a.disableAll(),t.fog&&a.enable(0);t.useFog&&a.enable(1);t.flatShading&&a.enable(2);t.logarithmicDepthBuffer&&a.enable(3);t.reversedDepthBuffer&&a.enable(4);t.skinning&&a.enable(5);t.morphTargets&&a.enable(6);t.morphNormals&&a.enable(7);t.morphColors&&a.enable(8);t.premultipliedAlpha&&a.enable(9);t.shadowMapEnabled&&a.enable(10);t.doubleSided&&a.enable(11);t.flipSided&&a.enable(12);t.useDepthPacking&&a.enable(13);t.dithering&&a.enable(14);t.transmission&&a.enable(15);t.sheen&&a.enable(16);t.opaque&&a.enable(17);t.pointsUvs&&a.enable(18);t.decodeVideoTexture&&a.enable(19);t.decodeVideoTextureEmissive&&a.enable(20);t.alphaToCoverage&&a.enable(21);t.numLightProbeGrids>0&&a.enable(22);t.hasPositionAttribute&&a.enable(23);e.push(a.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=p[e.type];let n;if(t){const e=Ja[t];n=Ws.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i=c.get(n);return void 0!==i?++i.usedTimes:(i=new lu(e,n,t,r),u.push(i),c.set(n,i)),i},releaseProgram:function(e){if(0===--e.usedTimes){const t=u.indexOf(e);u[t]=u[u.length-1],u.pop(),c.delete(e.cacheKey),e.destroy()}},releaseShaderCache:function(e){o.remove(e)},programs:u,dispose:function(){o.dispose()}}}function fu(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let n=e.get(t);return void 0===n&&(n={},e.set(t,n)),n},remove:function(t){e.delete(t)},update:function(t,n,i){e.get(t)[n]=i},dispose:function(){e=new WeakMap}}}function mu(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.materialVariant!==t.materialVariant?e.materialVariant-t.materialVariant:e.z!==t.z?e.z-t.z:e.id-t.id}function gu(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 _u(){const e=[];let t=0;const n=[],i=[],r=[];function s(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function a(n,i,r,a,o,l){let u=e[t];return void 0===u?(u={id:n.id,object:n,geometry:i,material:r,materialVariant:s(n),groupOrder:a,renderOrder:n.renderOrder,z:o,group:l},e[t]=u):(u.id=n.id,u.object=n,u.geometry=i,u.material=r,u.materialVariant=s(n),u.groupOrder=a,u.renderOrder=n.renderOrder,u.z=o,u.group=l),t++,u}return{opaque:n,transmissive:i,transparent:r,init:function(){t=0,n.length=0,i.length=0,r.length=0},push:function(e,t,s,o,l,u,c){!0===c.reversedDepth&&(l=-l);const h=a(e,t,s,o,l,u);s.transmission>0?i.push(h):!0===s.transparent?r.push(h):n.push(h)},unshift:function(e,t,s,o,l,u){const c=a(e,t,s,o,l,u);s.transmission>0?i.unshift(c):!0===s.transparent?r.unshift(c):n.unshift(c)},finish:function(){for(let n=t,i=e.length;n1&&n.sort(e||mu),i.length>1&&i.sort(t||gu),r.length>1&&r.sort(t||gu)}}}function vu(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new _u,e.set(t,[r])):n>=i.length?(r=new _u,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function yu(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"SunLight":case"DirectionalLight":n={direction:new fn,color:new yi};break;case"SpotLight":n={position:new fn,direction:new fn,color:new yi,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new fn,color:new yi,distance:0,decay:0};break;case"HemisphereLight":n={direction:new fn,skyColor:new yi,groundColor:new yi};break;case"RectAreaLight":n={color:new yi,position:new fn,halfWidth:new fn,halfHeight:new fn}}return e[t.id]=n,n}}}let bu=0;function xu(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Su(e){const t=new yu,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"SunLight":case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dn,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),i={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)i.probe.push(new fn);const r=new fn,s=new Bn,a=new Bn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let l=0,u=0,c=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0,y=0,b=0,x=0;r.sort(xu);for(let e=0,S=r.length;e0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=Qa.LTC_FLOAT_1,i.rectAreaLTC2=Qa.LTC_FLOAT_2):(i.rectAreaLTC1=Qa.LTC_HALF_1,i.rectAreaLTC2=Qa.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const S=i.hash;S.sunLength===l&&S.directionalLength===h&&S.pointLength===d&&S.spotLength===p&&S.rectAreaLength===f&&S.hemiLength===m&&S.numSunShadows===u&&S.numDirectionalShadows===g&&S.numPointShadows===_&&S.numSpotShadows===v&&S.numSpotMaps===y&&S.numLightProbes===x||(i.sun.length=l,i.directional.length=h,i.spot.length=p,i.rectArea.length=f,i.point.length=d,i.hemi.length=m,i.sunShadow.length=u,i.sunShadowMap.length=u,i.sunShadowMatrix.length=c,i.sunShadowCascade.length=c,i.directionalShadow.length=g,i.directionalShadowMap.length=g,i.directionalShadowMatrix.length=g,i.pointShadow.length=_,i.pointShadowMap.length=_,i.pointShadowMatrix.length=_,i.spotShadow.length=v,i.spotShadowMap.length=v,i.spotLightMatrix.length=v+y-b,i.spotLightMap.length=y,i.numSpotLightShadowsWithMaps=b,i.numLightProbes=x,S.sunLength=l,S.directionalLength=h,S.pointLength=d,S.spotLength=p,S.rectAreaLength=f,S.hemiLength=m,S.numSunShadows=u,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=y,S.numLightProbes=x,i.version=bu++)},setupView:function(e,t){let n=0,o=0,l=0,u=0,c=0,h=0;const d=t.matrixWorldInverse;for(let t=0,p=e.length;t=r.length?(s=new Tu(e),r.push(s)):s=r[i],s},dispose:function(){t=new WeakMap}}}const wu=[new fn(1,0,0),new fn(-1,0,0),new fn(0,1,0),new fn(0,-1,0),new fn(0,0,1),new fn(0,0,-1)],Eu=[new fn(0,-1,0),new fn(0,-1,0),new fn(0,0,1),new fn(0,0,-1),new fn(0,-1,0),new fn(0,-1,0)],Au=new Bn,Ru=new fn,Cu=new fn;function Nu(e,t,n){let i=new ts;const r=new dn,s=new dn,a=new Dn,o=new Js,l=new ea,u={},p=n.maxTextureSize,f={[c]:1,[h]:0,[d]:2},m=new js({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new dn},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"}),g=m.clone();g.defines.HORIZONTAL_PASS=1;const _=new br;_.setAttribute("position",new rr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new qr(_,m),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let b=this.type;function x(n,i){const s=t.update(v);m.defines.VSM_SAMPLES!==n.blurSamples&&(m.defines.VSM_SAMPLES=n.blurSamples,g.defines.VSM_SAMPLES=n.blurSamples,m.needsUpdate=!0,g.needsUpdate=!0),null===n.mapPass?n.mapPass=new Un(r.x,r.y,{format:Pe,type:ve}):n.mapPass.width===n.map.width&&n.mapPass.height===n.map.height||n.mapPass.setSize(n.map.width,n.map.height),m.uniforms.shadow_pass.value=n.map.depthTexture,m.uniforms.resolution.value.set(n.map.width,n.map.height),m.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,m,v,null),g.uniforms.shadow_pass.value=n.mapPass.texture,g.uniforms.resolution.value.set(n.map.width,n.map.height),g.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,g,v,null)}function S(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=s.uuid,t=n.uuid;let i=u[e];void 0===i&&(i={},u[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",M)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:f[n.side],s.alphaMap=n.alphaMap,s.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function T(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||n.intersectsFrustum(i))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let u=0,c=t.length;ue.needsUpdate=!0):e.material.needsUpdate=!0)});for(let l=0,u=t.length;lp||r.y>p)&&(r.x>p&&(s.x=Math.floor(p/f.x),r.x=s.x*f.x,c.mapSize.x=s.x),r.y>p&&(s.y=Math.floor(p/f.y),r.y=s.y*f.y,c.mapSize.y=s.y));const m=e.state.buffers.depth.getReversed();if(c.camera._reversedDepth=m,null===c.map||!0===d){if(null!==c.map&&(null!==c.map.depthTexture&&(c.map.depthTexture.dispose(),c.map.depthTexture=null),c.map.dispose()),3===this.type){if(u.isPointLight){qt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}c.map=new Un(r.x,r.y,{format:Pe,type:ve,minFilter:le,magFilter:le,generateMipmaps:!1}),c.map.texture.name=u.name+".shadowMap",c.map.depthTexture=new gs(r.x,r.y,_e),c.map.depthTexture.name=u.name+".shadowMapDepth",c.map.depthTexture.format=Ae,c.map.depthTexture.compareFunction=null,c.map.depthTexture.minFilter=se,c.map.depthTexture.magFilter=se}else u.isPointLight?(c.map=new To(r.x),c.map.depthTexture=new _s(r.x,ge)):(c.map=new Un(r.x,r.y),c.map.depthTexture=new gs(r.x,r.y,ge)),c.map.depthTexture.name=u.name+".shadowMap",c.map.depthTexture.format=Ae,1===this.type?(c.map.depthTexture.compareFunction=m?Ct:Et,c.map.depthTexture.minFilter=le,c.map.depthTexture.magFilter=le):(c.map.depthTexture.compareFunction=null,c.map.depthTexture.minFilter=se,c.map.depthTexture.magFilter=se);c.camera.updateProjectionMatrix()}!0===c.map.isWebGLCubeRenderTarget||c.map.width===r.x&&c.map.height===r.y||c.map.setSize(r.x,r.y);const g=c.map.isWebGLCubeRenderTarget?6:c.getViewportCount();!0!==u.isPointLight&&c.updateMatrices(u,o);for(let t=0;t=1):-1!==K.indexOf("OpenGL ES")&&(Y=parseFloat(/^OpenGL ES (\d)/.exec(K)[1]),q=Y>=2);let Z=null,Q={};const J=e.getParameter(e.SCISSOR_BOX),ee=e.getParameter(e.VIEWPORT),te=(new Dn).fromArray(J),ne=(new Dn).fromArray(ee);function ie(t,n,i,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;an||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===d&&(d=m(n,s));const a=t?m(n,s):d;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),qt("WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in e&&qt("WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,i,r,s,a,o=!1){if(null!==n){if(void 0!==e[n])return e[n];qt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let l;s&&(l=t.get("EXT_texture_norm16"),l||qt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let u=i;if(i===e.RED&&(r===e.FLOAT&&(u=e.R32F),r===e.HALF_FLOAT&&(u=e.R16F),r===e.UNSIGNED_BYTE&&(u=e.R8),r===e.UNSIGNED_SHORT&&l&&(u=l.R16_EXT),r===e.SHORT&&l&&(u=l.R16_SNORM_EXT)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(u=e.R8UI),r===e.UNSIGNED_SHORT&&(u=e.R16UI),r===e.UNSIGNED_INT&&(u=e.R32UI),r===e.BYTE&&(u=e.R8I),r===e.SHORT&&(u=e.R16I),r===e.INT&&(u=e.R32I)),i===e.RG&&(r===e.FLOAT&&(u=e.RG32F),r===e.HALF_FLOAT&&(u=e.RG16F),r===e.UNSIGNED_BYTE&&(u=e.RG8),r===e.UNSIGNED_SHORT&&l&&(u=l.RG16_EXT),r===e.SHORT&&l&&(u=l.RG16_SNORM_EXT)),i===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(u=e.RG8UI),r===e.UNSIGNED_SHORT&&(u=e.RG16UI),r===e.UNSIGNED_INT&&(u=e.RG32UI),r===e.BYTE&&(u=e.RG8I),r===e.SHORT&&(u=e.RG16I),r===e.INT&&(u=e.RG32I)),i===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(u=e.RGB8UI),r===e.UNSIGNED_SHORT&&(u=e.RGB16UI),r===e.UNSIGNED_INT&&(u=e.RGB32UI),r===e.BYTE&&(u=e.RGB8I),r===e.SHORT&&(u=e.RGB16I),r===e.INT&&(u=e.RGB32I)),i===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(u=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(u=e.RGBA16UI),r===e.UNSIGNED_INT&&(u=e.RGBA32UI),r===e.BYTE&&(u=e.RGBA8I),r===e.SHORT&&(u=e.RGBA16I),r===e.INT&&(u=e.RGBA32I)),i===e.RGB&&(r===e.UNSIGNED_SHORT&&l&&(u=l.RGB16_EXT),r===e.SHORT&&l&&(u=l.RGB16_SNORM_EXT),r===e.UNSIGNED_INT_5_9_9_9_REV&&(u=e.RGB9_E5),r===e.UNSIGNED_INT_10F_11F_11F_REV&&(u=e.R11F_G11F_B10F)),i===e.RGBA){const t=o?bt:Sn.getTransfer(a);r===e.FLOAT&&(u=e.RGBA32F),r===e.HALF_FLOAT&&(u=e.RGBA16F),r===e.UNSIGNED_BYTE&&(u=t===xt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT&&l&&(u=l.RGBA16_EXT),r===e.SHORT&&l&&(u=l.RGBA16_SNORM_EXT),r===e.UNSIGNED_SHORT_4_4_4_4&&(u=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(u=e.RGB5_A1)}return u!==e.R16F&&u!==e.R32F&&u!==e.RG16F&&u!==e.RG32F&&u!==e.RGBA16F&&u!==e.RGBA32F||t.get("EXT_color_buffer_float"),u}function x(t,n){let i;return t?null===n||n===ge||n===xe?i=e.DEPTH24_STENCIL8:n===_e?i=e.DEPTH32F_STENCIL8:n===fe&&(i=e.DEPTH24_STENCIL8,qt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===ge||n===xe?i=e.DEPTH_COMPONENT24:n===_e?i=e.DEPTH_COMPONENT32F:n===fe&&(i=e.DEPTH_COMPONENT16),i}function S(e,t){return!0===_(e)||e.isFramebufferTexture&&e.minFilter!==se&&e.minFilter!==le?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function T(e){const t=e.target;t.removeEventListener("dispose",T),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=p.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&w(e),0===Object.keys(r).length&&p.delete(n)}i.remove(e)}(t),t.isVideoTexture&&c.delete(t),t.isHTMLTexture&&h.delete(t)}function M(t){const n=t.target;n.removeEventListener("dispose",M),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let i=0;i0&&s.__version!==t.version){const e=t.image;if(null===e)qt("WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void I(s,t,r);qt("WebGLRenderer: Texture marked for update but image is incomplete")}}else t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const R={[ne]:e.REPEAT,[ie]:e.CLAMP_TO_EDGE,[re]:e.MIRRORED_REPEAT},C={[se]:e.NEAREST,[ae]:e.NEAREST_MIPMAP_NEAREST,[oe]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[ue]:e.LINEAR_MIPMAP_NEAREST,[ce]:e.LINEAR_MIPMAP_LINEAR},N={[Tt]:e.NEVER,[Nt]:e.ALWAYS,[Mt]:e.LESS,[Et]:e.LEQUAL,[wt]:e.EQUAL,[Ct]:e.GEQUAL,[At]:e.GREATER,[Rt]:e.NOTEQUAL};function P(n,s){if(s.type!==_e||!1!==t.has("OES_texture_float_linear")||s.magFilter!==le&&s.magFilter!==ue&&s.magFilter!==oe&&s.magFilter!==ce&&s.minFilter!==le&&s.minFilter!==ue&&s.minFilter!==oe&&s.minFilter!==ce||qt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(n,e.TEXTURE_WRAP_S,R[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,R[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,R[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,C[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,C[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,N[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===se)return;if(s.minFilter!==oe&&s.minFilter!==ce)return;if(s.type===_e&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function L(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",T));const r=n.source;let s=p.get(r);void 0===s&&(s={},p.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&w(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function D(e,t,n){return Math.floor(Math.floor(e/n)/t)}function I(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const u=L(t,a),c=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const d=i.get(c);if(c.version!==d.__version||!0===u){n.activeTexture(e.TEXTURE0+o);if(!1===("undefined"!=typeof ImageBitmap&&a.image instanceof ImageBitmap)){const t=Sn.getPrimaries(Sn.workingColorSpace),i=a.colorSpace===_t?null:Sn.getPrimaries(a.colorSpace),r=a.colorSpace===_t||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,r)}n.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment);let t=g(a.image,!1,r.maxTextureSize);t=H(a,t);const i=s.convert(a.format,a.colorSpace),p=s.convert(a.type);let f,m=b(a.internalFormat,i,p,a.normalized,a.colorSpace,a.isVideoTexture);P(l,a);const y=a.mipmaps,T=!0!==a.isVideoTexture,M=void 0===d.__version||!0===u,w=c.dataReady,E=S(a,t);if(a.isDepthTexture)m=x(a.format===Re,a.type),M&&(T?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,i,p,null));else if(a.isDataTexture)if(y.length>0){T&&M&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,r=y.length;te.start-t.start);let o=0;for(let e=1;e0){const t=qa(f.width,f.height,a.format,a.type);for(const s of a.layerUpdates){const a=f.data.subarray(s*t/f.data.BYTES_PER_ELEMENT,(s+1)*t/f.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,r,0,0,s,f.width,f.height,1,i,a)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,r,0,0,0,f.width,f.height,t.depth,i,f.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,r,m,f.width,f.height,t.depth,0,f.data,0,0);else qt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else T?w&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,r,0,0,0,f.width,f.height,t.depth,i,p,f.data):n.texImage3D(e.TEXTURE_2D_ARRAY,r,m,f.width,f.height,t.depth,0,i,p,f.data);a.layerUpdates.size>0&&a.clearLayerUpdates()}else{T&&M&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,r=y.length;t0){const r=qa(t.width,t.height,a.format,a.type);for(const s of a.layerUpdates){const a=t.data.subarray(s*r/t.data.BYTES_PER_ELEMENT,(s+1)*r/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,s,t.width,t.height,1,i,p,a)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,i,p,t.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,i,p,t.data);else if(a.isData3DTexture)T?(M&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),w&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,i,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,i,p,t.data);else if(a.isFramebufferTexture){if(M)if(T)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let r=t.width,s=t.height;for(let t=0;t>=1,s>>=1}}else if(a.isHTMLTexture){if("texElementImage2D"in e){const n=e.canvas;if(n.hasAttribute("layoutsubtree")||n.setAttribute("layoutsubtree","true"),t.parentNode!==n)return n.appendChild(t),h.add(a),n.onpaint=e=>{const t=e.changedElements;for(const e of h)t.includes(e.image)&&(e.needsUpdate=!0)},void n.requestPaint();if(3===e.texElementImage2D.length)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{const n=0,i=e.RGBA,r=e.RGBA,s=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,n,i,r,s,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(T&&M){const t=W(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,r=y.length;t>c),i=Math.max(1,r.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?n.texImage3D(u,c,p,t,i,r.depth,0,h,d,null):n.texImage2D(u,c,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),G(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,V(r)):(u===e.TEXTURE_2D||u>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&u<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,u,m.__webglTexture,c),n.bindFramebuffer(e.FRAMEBUFFER,null)}function F(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=x(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;G(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,V(n),a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,V(n),a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer)if(s)for(let e=0;e<6;e++)O(r.__webglFramebuffer[e],t,e);else{const e=t.texture.mipmaps;e&&e.length>0?O(r.__webglFramebuffer[0],t,0):O(r.__webglFramebuffer,t,0)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=e.createRenderbuffer(),F(r.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else{const i=t.texture.mipmaps;if(i&&i.length>0?n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),F(r.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}const k=[],z=[];function V(e){return Math.min(r.maxSamples,e.samples)}function G(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function H(e,t){const n=e.colorSpace,i=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==yt&&n!==_t&&(Sn.getTransfer(n)===xt?i===Ee&&r===he||qt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Yt("WebGLTextures: Unsupported texture color space:",n)),t}function W(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=E;return e>=r.maxTextures&&qt("WebGLTextures: Trying to use "+(e+1)+" texture units while this GPU supports only "+r.maxTextures),E+=1,e},this.resetTextureUnits=function(){E=0},this.getTextureUnits=function(){return E},this.setTextureUnits=function(e){E=e},this.setTexture2D=A,this.setTexture2DArray=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?I(s,t,r):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r))},this.setTexture3D=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?I(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=i.get(t);!0!==t.isCubeDepthTexture&&t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=L(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=i.get(u);if(u.version!==c.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=Sn.getPrimaries(Sn.workingColorSpace),i=a.colorSpace===_t?null:Sn.getPrimaries(a.colorSpace),h=a.colorSpace===_t||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,h);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:g(a.image[e],!0,r.maxCubemapSize),f[e]=H(a,f[e]);const m=f[0],y=s.convert(a.format,a.colorSpace),x=s.convert(a.type),T=b(a.internalFormat,y,x,a.normalized,a.colorSpace),M=!0!==a.isVideoTexture,w=void 0===c.__version||!0===l,E=u.dataReady;let A,R=S(a,m);if(P(e.TEXTURE_CUBE_MAP,a),d){M&&w&&n.texStorage2D(e.TEXTURE_CUBE_MAP,R,T,m.width,m.height);for(let t=0;t<6;t++){A=f[t].mipmaps;for(let i=0;i0&&R++;const t=W(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,R,T,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,y,x,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,T,f[t].width,f[t].height,0,y,x,f[t].data);for(let i=0;i1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let t=0;t0&&!1===G(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===G(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=i.get(t),h=r.length>1;if(h)for(let t=0;t0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let n=0;n= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new qr(new Fs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Uu extends Jt{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,u=null,c=null,h=null,d=null,p=null;const f="undefined"!=typeof XRWebGLBinding,m=new Iu,g={},_=t.getContextAttributes();let v=null,y=null;const b=[],x=[],S=new dn;let T=null,M=null;const w=new Ta;w.viewport=new Dn;const E=new Ta;E.viewport=new Dn;const A=[w,E],R=new Oa;let C=null,N=null;function P(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=b[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function L(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",L),i.removeEventListener("inputsourceschange",D);for(let e=0;e=0&&(x[i]=null,b[i].disconnect(n))}for(let t=0;t=x.length){x.push(n),i=e;break}if(null===x[e]){x[e]=n,i=e;break}}if(-1===i)break}const r=b[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return void 0===t&&(t=new fi,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return void 0===t&&(t=new fi,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return void 0===t&&(t=new fi,b[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&qt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&qt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return null===c&&f&&(c=new XRWebGLBinding(i,t)),c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(u){if(i=u,null!==i){v=e.getRenderTarget(),i.addEventListener("select",P),i.addEventListener("selectstart",P),i.addEventListener("selectend",P),i.addEventListener("squeeze",P),i.addEventListener("squeezestart",P),i.addEventListener("squeezeend",P),i.addEventListener("end",L),i.addEventListener("inputsourceschange",D),!0!==_.xrCompatible&&await t.makeXRCompatible(),T=e.getPixelRatio(),e.getSize(S);if(f&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;_.depth&&(a=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Re:Ae,s=_.stencil?xe:ge);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};c=this.getBinding(),h=c.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new Un(h.textureWidth,h.textureHeight,{format:Ee,type:he,depthTexture:new gs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues,storeMultisampledDepthBuffer:!1===h.ignoreDepthValues,storeMultisampledStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),y=new Un(d.framebufferWidth,d.framebufferHeight,{format:Ee,type:he,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues,storeMultisampledDepthBuffer:!1===d.ignoreDepthValues,storeMultisampledStencilBuffer:!1===d.ignoreDepthValues})}y.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),B.setContext(i),B.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const I=new fn,U=new fn;function F(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;let t=e.near,n=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(n=m.depthFar)),R.near=E.near=w.near=t,R.far=E.far=w.far=n,C===R.near&&N===R.far||(i.updateRenderState({depthNear:R.near,depthFar:R.far}),C=R.near,N=R.far),R.layers.mask=6|e.layers.mask,w.layers.mask=-5&R.layers.mask,E.layers.mask=-3&R.layers.mask;const r=e.parent,s=R.cameras;F(R,r);for(let e=0;e0&&(e.alphaTest.value=i.alphaTest);const r=t.get(i),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,e.envMapRotation.value.setFromMatrix4(Fu.makeRotationFromEuler(a)).transpose(),s.isCubeTexture&&!1===s.isRenderTargetTexture&&e.envMapRotation.value.premultiply(Ou),e.reflectivity.value=i.reflectivity,e.ior.value=i.ior,e.refractionRatio.value=i.refractionRatio),i.lightMap&&(e.lightMap.value=i.lightMap,e.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,e.lightMapTransform)),i.aoMap&&(e.aoMap.value=i.aoMap,e.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,Hs(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isNodeMaterial?r.uniformsNeedUpdate=!1:r.isMeshBasicMaterial?i(e,r):r.isMeshLambertMaterial?(i(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshStandardMaterial?(i(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function ku(e,t,n,i){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(t,n,i,r){if(!0===function(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return"number"==typeof r||"boolean"==typeof r?i[s]=r:ArrayBuffer.isView(r)?i[s]=r.slice():i[s]=r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else{if(ArrayBuffer.isView(r))return!0;if(!1===e.equals(r))return e.copy(r),!0}}return!1}(t,n,i,r)){const n=t.__offset,i=t.value;if(Array.isArray(i)){let e=0;for(let n=0;n0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0){const e=ec[0].object;Gu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Gu.normal),qu.setFromMatrixPosition(e.matrixWorld)),Ju!==e&&null!==Ju&&(this.dispatchEvent({type:"hoveroff",object:Ju}),n.style.cursor="auto",Ju=null),Ju!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",Ju=e)}else null!==Ju&&(this.dispatchEvent({type:"hoveroff",object:Ju}),n.style.cursor="auto",Ju=null);$u.copy(Hu)}}function ac(e){const t=this.object,n=this.domElement,i=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),ec.length=0,i.setFromCamera(Hu,t),i.intersectObjects(this.objects,this.recursive,ec),ec.length>0&&(Qu=!0===this.transformGroup?uc(ec[0].object):ec[0].object,Gu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Gu.normal),qu.setFromMatrixPosition(Qu.matrixWorld)),i.ray.intersectPlane(Gu,Xu)&&(this.state===nc?(Yu.copy(Qu.parent.matrixWorld).invert(),Wu.copy(Xu).sub(qu.setFromMatrixPosition(Qu.matrixWorld)),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Qu})):this.state===ic&&(Ku.set(0,1,0).applyQuaternion(t.quaternion).normalize(),Zu.set(1,0,0).applyQuaternion(t.quaternion).normalize(),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Qu})))),$u.copy(Hu))}function oc(){!1!==this.enabled&&(Qu&&(this.dispatchEvent({type:"dragend",object:Qu}),Qu=null),this.domElement.style.cursor=Ju?"pointer":"auto",this.state=tc)}function lc(e){!1!==this.enabled&&e.preventDefault()}function uc(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:uc(e.parent,t)}function cc(e,t,n){var i,r=1;function s(){var s,a,o=i.length,l=0,u=0,c=0;for(s=0;s=(r=(h+d)/2))?h=r:d=r,i=u,!(u=u[o=+a]))return i[o]=c,e;if(t===(s=+e._x.call(null,u.data)))return c.next=u,i?i[o]=c:e._root=c,e;do{i=i?i[o]=new Array(2):e._root=new Array(2),(a=t>=(r=(h+d)/2))?h=r:d=r}while((o=+a)===(l=+(s>=r)));return i[l]=u,i[o]=c,e}function dc(e,t,n){this.node=e,this.x0=t,this.x1=n}function pc(e){return e[0]}function fc(e,t){var n=new mc(null==t?pc:t,NaN,NaN);return null==e?n:n.addAll(e)}function mc(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function gc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var _c=fc.prototype=mc.prototype;function vc(e,t,n,i){if(isNaN(t)||isNaN(n))return e;var r,s,a,o,l,u,c,h,d,p=e._root,f={data:i},m=e._x0,g=e._y0,_=e._x1,v=e._y1;if(!p)return e._root=f,e;for(;p.length;)if((u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a,r=p,!(p=p[h=c<<1|u]))return r[h]=f,e;if(o=+e._x.call(null,p.data),l=+e._y.call(null,p.data),t===o&&n===l)return f.next=p,r?r[h]=f:e._root=f,e;do{r=r?r[h]=new Array(4):e._root=new Array(4),(u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a}while((h=c<<1|u)==(d=(l>=a)<<1|o>=s));return r[d]=p,r[h]=f,e}function yc(e,t,n,i,r){this.node=e,this.x0=t,this.y0=n,this.x1=i,this.y1=r}function bc(e){return e[0]}function xc(e){return e[1]}function Sc(e,t,n){var i=new Tc(null==t?bc:t,null==n?xc:n,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function Tc(e,t,n,i,r,s){this._x=e,this._y=t,this._x0=n,this._y0=i,this._x1=r,this._y1=s,this._root=void 0}function Mc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}_c.copy=function(){var e,t,n=new mc(this._x,this._x0,this._x1),i=this._root;if(!i)return n;if(!i.length)return n._root=gc(i),n;for(e=[{source:i,target:n._root=new Array(2)}];i=e.pop();)for(var r=0;r<2;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(2)}):i.target[r]=gc(t));return n},_c.add=function(e){const t=+this._x.call(null,e);return hc(this.cover(t),t,e)},_c.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t);let i=1/0,r=-1/0;for(let s,a=0;ar&&(r=s));if(i>r)return this;this.cover(i).cover(r);for(let i=0;ie||e>=n;)switch(r=+(el||(r=s.x1)=h))&&(s=u[u.length-1],u[u.length-1]=u[u.length-1-a],u[u.length-1-a]=s)}else{var d=Math.abs(e-+this._x.call(null,c.data));d=(a=(h+d)/2))?h=a:d=a,t=c,!(c=c[l=+o]))return this;if(!c.length)break;t[l+1&1]&&(n=t,u=l)}for(;c.data!==e;)if(i=c,!(c=c.next))return this;return(r=c.next)&&delete c.next,i?(r?i.next=r:delete i.next,this):t?(r?t[l]=r:delete t[l],(c=t[0]||t[1])&&c===(t[1]||t[0])&&!c.length&&(n?n[u]=c:this._root=c),this):(this._root=r,this)},_c.removeAll=function(e){for(var t=0,n=e.length;t=(a=(y+S)/2))?y=a:S=a,(p=n>=(o=(b+T)/2))?b=o:T=o,(f=i>=(l=(x+M)/2))?x=l:M=l,s=_,!(_=_[m=f<<2|p<<1|d]))return s[m]=v,e;if(u=+e._x.call(null,_.data),c=+e._y.call(null,_.data),h=+e._z.call(null,_.data),t===u&&n===c&&i===h)return v.next=_,s?s[m]=v:e._root=v,e;do{s=s?s[m]=new Array(8):e._root=new Array(8),(d=t>=(a=(y+S)/2))?y=a:S=a,(p=n>=(o=(b+T)/2))?b=o:T=o,(f=i>=(l=(x+M)/2))?x=l:M=l}while((m=f<<2|p<<1|d)==(g=(h>=l)<<2|(c>=o)<<1|u>=a));return s[g]=_,s[m]=v,e}function Ac(e,t,n,i,r,s,a){this.node=e,this.x0=t,this.y0=n,this.z0=i,this.x1=r,this.y1=s,this.z1=a}wc.copy=function(){var e,t,n=new Tc(this._x,this._y,this._x0,this._y0,this._x1,this._y1),i=this._root;if(!i)return n;if(!i.length)return n._root=Mc(i),n;for(e=[{source:i,target:n._root=new Array(4)}];i=e.pop();)for(var r=0;r<4;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(4)}):i.target[r]=Mc(t));return n},wc.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return vc(this.cover(t,n),t,n,e)},wc.addAll=function(e){var t,n,i,r,s=e.length,a=new Array(s),o=new Array(s),l=1/0,u=1/0,c=-1/0,h=-1/0;for(n=0;nc&&(c=i),rh&&(h=r));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;ne||e>=r||i>t||t>=s;)switch(o=(td||(s=l.y0)>p||(a=l.x1)=_)<<1|e>=g)&&(l=f[f.length-1],f[f.length-1]=f[f.length-1-u],f[f.length-1-u]=l)}else{var v=e-+this._x.call(null,m.data),y=t-+this._y.call(null,m.data),b=v*v+y*y;if(b=(o=(f+g)/2))?f=o:g=o,(c=a>=(l=(m+_)/2))?m=l:_=l,t=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(t[h+1&3]||t[h+2&3]||t[h+3&3])&&(n=t,d=h)}for(;p.data!==e;)if(i=p,!(p=p.next))return this;return(r=p.next)&&delete p.next,i?(r?i.next=r:delete i.next,this):t?(r?t[h]=r:delete t[h],(p=t[0]||t[1]||t[2]||t[3])&&p===(t[3]||t[2]||t[1]||t[0])&&!p.length&&(n?n[d]=p:this._root=p),this):(this._root=r,this)},wc.removeAll=function(e){for(var t=0,n=e.length;tMath.sqrt((e-i)**2+(t-r)**2+(n-s)**2);function Cc(e){return e[0]}function Nc(e){return e[1]}function Pc(e){return e[2]}function Lc(e,t,n,i){var r=new Dc(null==t?Cc:t,null==n?Nc:n,null==i?Pc:i,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Dc(e,t,n,i,r,s,a,o,l){this._x=e,this._y=t,this._z=n,this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this._root=void 0}function Ic(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Uc=Lc.prototype=Dc.prototype;function Fc(e){return function(){return e}}function Oc(e){return 1e-6*(e()-.5)}function Bc(e){return e.index}function kc(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function zc(e){var t,n,i,r,s,a,o,l=Bc,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=Fc(30),h=1;function d(i){for(var s=0,l=e.length;s1&&(_=d.y+d.vy-c.y-c.vy||Oc(o)),r>2&&(v=d.z+d.vz-c.z-c.vz||Oc(o)),g*=p=((p=Math.sqrt(g*g+_*_+v*v))-n[m])/p*i*t[m],_*=p,v*=p,d.vx-=g*(f=a[m]),r>1&&(d.vy-=_*f),r>2&&(d.vz-=v*f),c.vx+=g*(f=1-f),r>1&&(c.vy+=_*f),r>2&&(c.vz+=v*f)}function p(){if(i){var r,o,u=i.length,c=e.length,h=new Map(i.map((e,t)=>[l(e,t,i),e]));for(r=0,s=new Array(u);r"function"==typeof e)||Math.random,r=t.find(e=>[1,2,3].includes(e))||2,p()},d.links=function(t){return arguments.length?(e=t,p(),d):e},d.id=function(e){return arguments.length?(l=e,d):l},d.iterations=function(e){return arguments.length?(h=+e,d):h},d.strength=function(e){return arguments.length?(u="function"==typeof e?e:Fc(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:Fc(+e),m(),d):c},d}Uc.copy=function(){var e,t,n=new Dc(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ic(i),n;for(e=[{source:i,target:n._root=new Array(8)}];i=e.pop();)for(var r=0;r<8;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(8)}):i.target[r]=Ic(t));return n},Uc.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),i=+this._z.call(null,e);return Ec(this.cover(t,n,i),t,n,i,e)},Uc.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t),i=new Float64Array(t),r=new Float64Array(t);let s=1/0,a=1/0,o=1/0,l=-1/0,u=-1/0,c=-1/0;for(let h,d,p,f,m=0;ml&&(l=d),pu&&(u=p),fc&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;se||e>=a||r>t||t>=o||s>n||n>=l;)switch(c=(ng||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)=T)<<2|(t>=S)<<1|e>=x)&&(h=y[y.length-1],y[y.length-1]=y[y.length-1-d],y[y.length-1-d]=h)}else{var M=e-+this._x.call(null,b.data),w=t-+this._y.call(null,b.data),E=n-+this._z.call(null,b.data),A=M*M+w*w+E*E;if(A{if(!h.length)do{const s=h.data;Rc(e,t,n,this._x(s),this._y(s),this._z(s))<=i&&r.push(s)}while(h=h.next);return d>l||p>u||f>c||m=(l=(_+b)/2))?_=l:b=l,(d=a>=(u=(v+x)/2))?v=u:x=u,(p=o>=(c=(y+S)/2))?y=c:S=c,t=g,!(g=g[f=p<<2|d<<1|h]))return this;if(!g.length)break;(t[f+1&7]||t[f+2&7]||t[f+3&7]||t[f+4&7]||t[f+5&7]||t[f+6&7]||t[f+7&7])&&(n=t,m=f)}for(;g.data!==e;)if(i=g,!(g=g.next))return this;return(r=g.next)&&delete g.next,i?(r?i.next=r:delete i.next,this):t?(r?t[f]=r:delete t[f],(g=t[0]||t[1]||t[2]||t[3]||t[4]||t[5]||t[6]||t[7])&&g===(t[7]||t[6]||t[5]||t[4]||t[3]||t[2]||t[1]||t[0])&&!g.length&&(n?n[m]=g:this._root=g),this):(this._root=r,this)},Uc.removeAll=function(e){for(var t=0,n=e.length;t{}};function Gc(){for(var e,t=0,n=arguments.length,i={};t=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!i.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}})),a=-1,o=s.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++a0)for(var n,i,r=new Array(n),s=0;s=0&&t._call.call(void 0,e),t=t._next;--qc}()}finally{qc=0,function(){var e,t,n=$c,i=1/0;for(;n;)n._call?(i>n._time&&(i=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:$c=t);Xc=e,lh(i)}(),Qc=0}}function oh(){var e=eh.now(),t=e-Zc;t>1e3&&(Jc-=t,Zc=e)}function lh(e){qc||(Yc&&(Yc=clearTimeout(Yc)),e-Qc>24?(e<1/0&&(Yc=setTimeout(ah,e-eh.now()-Jc)),Kc&&(Kc=clearInterval(Kc))):(Kc||(Zc=eh.now(),Kc=setInterval(oh,1e3)),qc=1,th(ah)))}rh.prototype=sh.prototype={constructor:rh,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?nh():+n)+(null==t?0:+t),this._next||Xc===this||(Xc?Xc._next=this:$c=this,Xc=this),this._call=e,this._time=n,lh()},stop:function(){this._call&&(this._call=null,this._time=1/0,lh())}};const uh=4294967296;function ch(e){return e.x}function hh(e){return e.y}function dh(e){return e.z}var ph=Math.PI*(3-Math.sqrt(5)),fh=20*Math.PI/(9+Math.sqrt(221));function mh(e,t){t=t||2;var n,i=Math.min(3,Math.max(1,Math.round(t))),r=1,s=.001,a=1-Math.pow(s,1/300),o=0,l=.6,u=new Map,c=sh(p),h=Gc("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%uh)/uh}();function p(){f(),h.call("tick",n),r1&&(null==c.fy?c.y+=c.vy*=l:(c.y=c.fy,c.vy=0)),i>2&&(null==c.fz?c.z+=c.vz*=l:(c.z=c.fz,c.vz=0));return n}function m(){for(var t,n=0,r=e.length;n1&&isNaN(t.y)||i>2&&isNaN(t.z)){var s=10*(i>2?Math.cbrt(.5+n):i>1?Math.sqrt(.5+n):n),a=n*ph,o=n*fh;1===i?t.x=s:2===i?(t.x=s*Math.cos(a),t.y=s*Math.sin(a)):(t.x=s*Math.sin(a)*Math.cos(o),t.y=s*Math.cos(a),t.z=s*Math.sin(a)*Math.sin(o))}(isNaN(t.vx)||i>1&&isNaN(t.vy)||i>2&&isNaN(t.vz))&&(t.vx=0,i>1&&(t.vy=0),i>2&&(t.vz=0))}}function g(t){return t.initialize&&t.initialize(e,d,i),t}return null==e&&(e=[]),m(),n={tick:f,restart:function(){return c.restart(p),n},stop:function(){return c.stop(),n},numDimensions:function(e){return arguments.length?(i=Math.min(3,Math.max(1,Math.round(e))),u.forEach(g),n):i},nodes:function(t){return arguments.length?(e=t,m(),u.forEach(g),n):e},alpha:function(e){return arguments.length?(r=+e,n):r},alphaMin:function(e){return arguments.length?(s=+e,n):s},alphaDecay:function(e){return arguments.length?(a=+e,n):+a},alphaTarget:function(e){return arguments.length?(o=+e,n):o},velocityDecay:function(e){return arguments.length?(l=1-e,n):1-l},randomSource:function(e){return arguments.length?(d=e,u.forEach(g),n):d},force:function(e,t){return arguments.length>1?(null==t?u.delete(e):u.set(e,g(t)),n):u.get(e)},find:function(){var t,n,r,s,a,o,l=Array.prototype.slice.call(arguments),u=l.shift()||0,c=(i>1?l.shift():null)||0,h=(i>2?l.shift():null)||0,d=l.shift()||1/0,p=0,f=e.length;for(d*=d,p=0;p1?(h.on(e,t),n):h.on(e)}}}function gh(){var e,t,n,i,r,s,a=Fc(-30),o=1,l=1/0,u=.81;function c(i){var s,a=e.length,o=(1===t?fc(e,ch):2===t?Sc(e,ch,hh):3===t?Lc(e,ch,hh,dh):null).visitAfter(d);for(r=i,s=0;s1&&(e.y=a/c),t>2&&(e.z=o/c)}else{(n=e).x=n.data.x,t>1&&(n.y=n.data.y),t>2&&(n.z=n.data.z);do{u+=s[n.data.index]}while(n=n.next)}e.value=u}function p(e,a,c,h,d){if(!e.value)return!0;var p=[c,h,d][t-1],f=e.x-n.x,m=t>1?e.y-n.y:0,g=t>2?e.z-n.z:0,_=p-a,v=f*f+m*m+g*g;if(_*_/u1&&0===m&&(v+=(m=Oc(i))*m),t>2&&0===g&&(v+=(g=Oc(i))*g),v1&&(n.vy+=m*e.value*r/v),t>2&&(n.vz+=g*e.value*r/v)),!0;if(!(e.length||v>=l)){(e.data!==n||e.next)&&(0===f&&(v+=(f=Oc(i))*f),t>1&&0===m&&(v+=(m=Oc(i))*m),t>2&&0===g&&(v+=(g=Oc(i))*g),v1&&(n.vy+=m*_),t>2&&(n.vz+=g*_))}while(e=e.next)}}return c.initialize=function(n,...r){e=n,i=r.find(e=>"function"==typeof e)||Math.random,t=r.find(e=>[1,2,3].includes(e))||2,h()},c.strength=function(e){return arguments.length?(a="function"==typeof e?e:Fc(+e),h(),c):a},c.distanceMin=function(e){return arguments.length?(o=e*e,c):Math.sqrt(o)},c.distanceMax=function(e){return arguments.length?(l=e*e,c):Math.sqrt(l)},c.theta=function(e){return arguments.length?(u=e*e,c):Math.sqrt(u)},c}function _h(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");const t=["on","fire","off"];for(let n=0;n1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e"u")return t=Object.create(null),e;if(t[n])if("function"!=typeof i)delete t[n];else{const e=t[n];for(let t=0;t1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return Yh=1,Jh.exports=e,Jh.exports.random=e,Jh.exports.randomIterator=function(t,n){var i=n||e();if("function"!=typeof i.next)throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:function(e){var n,r,s;for(n=t.length-1;n>0;--n)r=i.next(n+1),s=t[r],t[r]=t[n],t[n]=s,e(s);t.length&&e(t[0])},shuffle:function(){var e,n,r;for(e=t.length-1;e>0;--e)n=i.next(e+1),r=t[n],t[n]=t[e],t[e]=r;return t}}},t.prototype.next=function(e){return Math.floor(this.nextDouble()*e)},t.prototype.nextDouble=i,t.prototype.uniform=i,t.prototype.gaussian=function(){var e,t,n;do{e=(t=2*this.nextDouble()-1)*t+(n=2*this.nextDouble()-1)*n}while(e>=1||0===e);return t*Math.sqrt(-2*Math.log(e)/e)},t.prototype.random=i,t.prototype.levy=function(){var e=1.5,t=Math.pow(n(2.5)*Math.sin(Math.PI*e/2)/(n(1.25)*e*Math.pow(2,.25)),1/e);return this.gaussian()*t/Math.pow(Math.abs(this.gaussian()),1/e)},Jh.exports}().random(42),x=[],S=[],T=m(l,b),M=g(x,l,b),w=v(l,b),E=_(l),A=[],R=new Map,C=0;L("nbody",function(){if(0===x.length)return;T.insertBodies(x);var e=x.length;for(;e--;){var t=x[e];t.isPinned||(t.reset(),T.updateBodyForce(t),E.update(t))}}),L("spring",function(){var e=S.length;for(;e--;)w.update(S[e])});var N={bodies:x,quadTree:T,springs:S,settings:l,addForce:L,removeForce:function(e){var t=A.indexOf(R.get(e));if(t<0)return;A.splice(t,1),R.delete(e)},getForces:function(){return R},step:function(){for(var e=0;enew f(e))(e);return x.push(t),t},removeBody:function(e){if(e){var t=x.indexOf(e);if(!(t<0))return x.splice(t,1),0===x.length&&M.reset(),!0}},addSpring:function(e,t,n,i){if(!e||!t)throw new Error("Cannot add null spring to force simulator");"number"!=typeof n&&(n=-1);var r=new u(e,t,n,i>=0?i:-1);return S.push(r),r},getTotalMovement:function(){return 0},removeSpring:function(e){if(e){var t=S.indexOf(e);return t>-1?(S.splice(t,1),!0):void 0}},getBestNewBodyPosition:function(e){return M.getBestNewPosition(e)},getBBox:P,getBoundingBox:P,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(e){return void 0!==e?(l.gravity=e,T.options({gravity:e}),this):l.gravity},theta:function(e){return void 0!==e?(l.theta=e,T.options({theta:e}),this):l.theta},random:b};return function(e,t){for(var n in e)o(e,t,n)}(l,N),h(N),N;function P(){return M.update(),M.box}function L(e,t){if(R.has(e))throw new Error("Force "+e+" is already added");R.set(e,t),A.push(t)}};var e=function(){if(Ah)return Ch.exports;Ah=1;const e=Ph();function t(e,t){return`\n${i(e,t)}\n${n(e)}\nreturn {Body: Body, Vector: Vector};\n`}function n(t){let n=e(t),i=n("{var}",{join:", "});return`\nfunction Body(${i}) {\n this.isPinned = false;\n this.pos = new Vector(${i});\n this.force = new Vector();\n this.velocity = new Vector();\n this.mass = 1;\n\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.reset = function() {\n this.force.reset();\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.setPosition = function (${i}) {\n ${n("this.pos.{var} = {var} || 0;",{indent:2})}\n};`}function i(t,n){let i=e(t),r="";return n&&(r=`${i("\n\t var v{var};\n\tObject.defineProperty(this, '{var}', {\n\t set: function(v) { \n\t if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\t v{var} = v; \n\t },\n\t get: function() { return v{var}; }\n\t});")}`),`function Vector(${i("{var}",{join:", "})}) {\n ${r}\n if (typeof arguments[0] === 'object') {\n // could be another vector\n let v = arguments[0];\n ${i('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}\n ${i("this.{var} = v.{var};",{indent:4})}\n } else {\n ${i('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}\n }\n }\n \n Vector.prototype.reset = function () {\n ${i("this.{var} = ",{join:""})}0;\n };`}return Ch.exports=function(e,n){let i=t(e,n),{Body:r}=new Function(i)();return r},Ch.exports.generateCreateBodyFunctionBody=t,Ch.exports.getVectorCode=i,Ch.exports.getBodyCode=n,Ch.exports}(),t=function(){if(Lh)return Dh.exports;Lh=1;const e=Ph(),t=Nh();function n(n){let l=e(n),u=Math.pow(2,n),c=`\n${o()}\n${a(n)}\n${i(n)}\n${s(n)}\n${r(n)}\n\nfunction createQuadTree(options, random) {\n options = options || {};\n options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;\n options.theta = typeof options.theta === 'number' ? options.theta : 0.8;\n\n var gravity = options.gravity;\n var updateQueue = [];\n var insertStack = new InsertStack();\n var theta = options.theta;\n\n var nodesCache = [];\n var currentInCache = 0;\n var root = newNode();\n\n return {\n insertBodies: insertBodies,\n\n /**\n * Gets root node if it is present\n */\n getRoot: function() {\n return root;\n },\n\n updateBodyForce: update,\n\n options: function(newOptions) {\n if (newOptions) {\n if (typeof newOptions.gravity === 'number') {\n gravity = newOptions.gravity;\n }\n if (typeof newOptions.theta === 'number') {\n theta = newOptions.theta;\n }\n\n return this;\n }\n\n return {\n gravity: gravity,\n theta: theta\n };\n }\n };\n\n function newNode() {\n // To avoid pressure on GC we reuse nodes.\n var node = nodesCache[currentInCache];\n if (node) {\n${function(e){let t=[];for(let n=0;n {var}max) {var}max = pos.{var};",{indent:6})}\n }\n\n // Makes the bounds square.\n var maxSideLength = -Infinity;\n ${l("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}\n\n currentInCache = 0;\n root = newNode();\n ${l("root.min_{var} = {var}min;",{indent:4})}\n ${l("root.max_{var} = {var}min + maxSideLength;",{indent:4})}\n\n i = bodies.length - 1;\n if (i >= 0) {\n root.body = bodies[i];\n }\n while (i--) {\n insert(bodies[i], root);\n }\n }\n\n function insert(newBody) {\n insertStack.reset();\n insertStack.push(root, newBody);\n\n while (!insertStack.isEmpty()) {\n var stackItem = insertStack.pop();\n var node = stackItem.node;\n var body = stackItem.body;\n\n if (!node.body) {\n // This is internal node. Update the total mass of the node and center-of-mass.\n ${l("var {var} = body.pos.{var};",{indent:8})}\n node.mass += body.mass;\n ${l("node.mass_{var} += body.mass * {var};",{indent:8})}\n\n // Recursively insert the body in the appropriate quadrant.\n // But first find the appropriate quadrant.\n var quadIdx = 0; // Assume we are in the 0's quad.\n ${l("var min_{var} = node.min_{var};",{indent:8})}\n ${l("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}\n\n${function(){let e=[],i=Array(8+1).join(" ");for(let r=0;r max_${t(r)}) {`),e.push(i+` quadIdx = quadIdx + ${Math.pow(2,r)};`),e.push(i+` min_${t(r)} = max_${t(r)};`),e.push(i+` max_${t(r)} = node.max_${t(r)};`),e.push(i+"}");return e.join("\n")}()}\n\n var child = getChild(node, quadIdx);\n\n if (!child) {\n // The node is internal but this quadrant is not taken. Add\n // subnode to it.\n child = newNode();\n ${l("child.min_{var} = min_{var};",{indent:10})}\n ${l("child.max_{var} = max_{var};",{indent:10})}\n child.body = body;\n\n setChild(node, quadIdx, child);\n } else {\n // continue searching in this quadrant.\n insertStack.push(child, body);\n }\n } else {\n // We are trying to add to the leaf node.\n // We have to convert current leaf into internal node\n // and continue adding two nodes.\n var oldBody = node.body;\n node.body = null; // internal nodes do not cary bodies\n\n if (isSamePosition(oldBody.pos, body.pos)) {\n // Prevent infinite subdivision by bumping one node\n // anywhere in this quadrant\n var retriesCount = 3;\n do {\n var offset = random.nextDouble();\n ${l("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}\n\n ${l("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}\n retriesCount -= 1;\n // Make sure we don't bump it out of the box. If we do, next iteration should fix it\n } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));\n\n if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {\n // This is very bad, we ran out of precision.\n // if we do not return from the method we'll get into\n // infinite loop here. So we sacrifice correctness of layout, and keep the app running\n // Next layout iteration should get larger bounding box in the first step and fix this\n return;\n }\n }\n // Next iteration should subdivide node further.\n insertStack.push(node, oldBody);\n insertStack.push(node, body);\n }\n }\n }\n}\nreturn createQuadTree;\n\n`;return c}function i(t){let n=e(t);return`\n function isSamePosition(point1, point2) {\n ${n("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}\n \n return ${n("d{var} < 1e-8",{join:" && "})};\n } \n`}function r(e){var t=Math.pow(2,e);return`\nfunction setChild(node, idx, child) {\n ${function(){let e=[];for(let n=0;n 0) {\n return this.stack[--this.popIdx];\n }\n },\n reset: function () {\n this.popIdx = 0;\n }\n};\n\nfunction InsertStackElement(node, body) {\n this.node = node; // QuadTree node\n this.body = body; // physical body which needs to be inserted to node\n}\n"}return Dh.exports=function(e){let t=n(e);return new Function(t)()},Dh.exports.generateQuadTreeFunctionBody=n,Dh.exports.getInsertStackCode=o,Dh.exports.getQuadNodeCode=a,Dh.exports.isSamePosition=i,Dh.exports.getChildBodyCode=s,Dh.exports.setChildBodyCode=r,Dh.exports}(),n=function(){if(Ih)return Uh.exports;Ih=1,Uh.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Uh.exports.generateFunctionBody=t;const e=Ph();function t(t){let n=e(t);return`\n var boundingBox = {\n ${n("min_{var}: 0, max_{var}: 0,",{indent:4})}\n };\n\n return {\n box: boundingBox,\n\n update: updateBoundingBox,\n\n reset: resetBoundingBox,\n\n getBestNewPosition: function (neighbors) {\n var ${n("base_{var} = 0",{join:", "})};\n\n if (neighbors.length) {\n for (var i = 0; i < neighbors.length; ++i) {\n let neighborPos = neighbors[i].pos;\n ${n("base_{var} += neighborPos.{var};",{indent:10})}\n }\n\n ${n("base_{var} /= neighbors.length;",{indent:8})}\n } else {\n ${n("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}\n }\n\n var springLength = settings.springLength;\n return {\n ${n("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}\n };\n }\n };\n\n function updateBoundingBox() {\n var i = bodies.length;\n if (i === 0) return; // No bodies - no borders.\n\n ${n("var max_{var} = -Infinity;",{indent:4})}\n ${n("var min_{var} = Infinity;",{indent:4})}\n\n while(i--) {\n // this is O(n), it could be done faster with quadtree, if we check the root node bounds\n var bodyPos = bodies[i].pos;\n ${n("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}\n ${n("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}\n }\n\n ${n("boundingBox.min_{var} = min_{var};",{indent:4})}\n ${n("boundingBox.max_{var} = max_{var};",{indent:4})}\n }\n\n function resetBoundingBox() {\n ${n("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}\n }\n`}return Uh.exports}(),i=function(){if(Fh)return Oh.exports;Fh=1;const e=Ph();function t(t){return`\n if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');\n\n return {\n update: function(body) {\n ${e(t)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}\n }\n };\n`}return Oh.exports=function(e){let n=t(e);return new Function("options",n)},Oh.exports.generateCreateDragForceFunctionBody=t,Oh.exports}(),r=function(){if(Bh)return kh.exports;Bh=1;const e=Ph();function t(t){let n=e(t);return`\n if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');\n if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');\n\n return {\n /**\n * Updates forces acting on a spring\n */\n update: function (spring) {\n var body1 = spring.from;\n var body2 = spring.to;\n var length = spring.length < 0 ? options.springLength : spring.length;\n ${n("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}\n var r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n ${n("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}\n r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n }\n\n var d = r - length;\n var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;\n\n ${n("body1.force.{var} += coefficient * d{var}",{indent:6})};\n body1.springCount += 1;\n body1.springLength += r;\n\n ${n("body2.force.{var} -= coefficient * d{var}",{indent:6})};\n body2.springCount += 1;\n body2.springLength += r;\n }\n };\n`}return kh.exports=function(e){let n=t(e);return new Function("options","random",n)},kh.exports.generateCreateSpringForceFunctionBody=t,kh.exports}(),s=function(){if(zh)return Xh.exports;zh=1;const e=Ph();function t(t){let n=e(t);return`\n var length = bodies.length;\n if (length === 0) return 0;\n\n ${n("var d{var} = 0, t{var} = 0;",{indent:2})}\n\n for (var i = 0; i < length; ++i) {\n var body = bodies[i];\n if (body.isPinned) continue;\n\n if (adaptiveTimeStepWeight && body.springCount) {\n timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);\n }\n\n var coeff = timeStep / body.mass;\n\n ${n("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}\n ${n("var v{var} = body.velocity.{var};",{indent:4})}\n var v = Math.sqrt(${n("v{var} * v{var}",{join:" + "})});\n\n if (v > 1) {\n // We normalize it so that we move within timeStep range. \n // for the case when v <= 1 - we let velocity to fade out.\n ${n("body.velocity.{var} = v{var} / v;",{indent:6})}\n }\n\n ${n("d{var} = timeStep * body.velocity.{var};",{indent:4})}\n\n ${n("body.pos.{var} += d{var};",{indent:4})}\n\n ${n("t{var} += Math.abs(d{var});",{indent:4})}\n }\n\n return (${n("t{var} * t{var}",{join:" + "})})/length;\n`}return Xh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},Xh.exports.generateIntegratorFunctionBody=t,Xh.exports}(),a={};function o(e,t,n){if(e.hasOwnProperty(n)&&"function"!=typeof t[n]){var i=Number.isFinite(e[n]);t[n]=i?function(i){if(void 0!==i){if(!Number.isFinite(i))throw new Error("Value of "+n+" should be a valid number.");return e[n]=i,t}return e[n]}:function(i){return void 0!==i?(e[n]=i,t):e[n]}}}return Kh}var td=function(){if(Qh)return Rh.exports;Qh=1,Rh.exports=function(n,i){if(!n)throw new Error("Graph structure cannot be undefined");var r=(i&&i.createSimulator||ed())(i);if(Array.isArray(i))throw new Error("Physics settings is expected to be an object");var s=n.version>19?function(e){var t=n.getLinks(e);return t?1+t.size/3:1}:function(e){var t=n.getLinks(e);return t?1+t.length/3:1};i&&"function"==typeof i.nodeMass&&(s=i.nodeMass);var a=new Map,o={},l=0,u=r.settings.springTransform||t;l=0,n.forEachNode(function(e){m(e.id),l+=1}),n.forEachLink(_),n.on("changed",f);var c=!1,h={step:function(){if(0===l)return d(!0),!0;var e=r.step();h.lastMove=e,h.fire("step");var t=e/l<=.01;return d(t),t},getNodePosition:function(e){return b(e).pos},setNodePosition:function(e){var t=b(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=o[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return r.getBBox()},forEachBody:p,pinNode:function(e,t){b(e.id).isPinned=!!t},isNodePinned:function(e){return b(e.id).isPinned},dispose:function(){n.off("changed",f),h.fire("disposed")},getBody:function(e){return a.get(e)},getSpring:function(e,t){var i;if(void 0===t)i="object"!=typeof e?e:e.id;else{var r=n.hasLink(e,t);if(!r)return;i=r.id}return o[i]},getForceVectorLength:function(){var e=0,t=0;return p(function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)}),Math.sqrt(e*e+t*t)},simulator:r,graph:n,lastMove:0};return e(h),h;function d(e){var t;c!==e&&(c=e,t=e,h.fire("stable",t))}function p(e){a.forEach(e)}function f(e){for(var t=0;t=t||n<0||h&&e-u>=s}function m(){var e=od();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?wd(n,s-(e-u)):n}(e))}function g(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function _(){var e=od(),n=f(e);if(i=arguments,r=this,l=e,n){if(void 0===o)return function(e){return u=e,o=setTimeout(m,t),c?p(e):a}(l);if(h)return clearTimeout(o),o=setTimeout(m,t),p(l)}return void 0===o&&(o=setTimeout(m,t)),a}return t=Td(t)||0,id(n)&&(c=!!n.leading,s=(h="maxWait"in n)?Md(Td(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),_.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=l=r=o=void 0},_.flush=function(){return void 0===o?a:g(od())},_}function Ad(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n=r)&&(n=r)}return n}function Od(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function Bd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=Ap(e,360),t=Ap(t,100),n=Ap(n,100),0===t)i=r=s=n;else{var o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;i=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*i,g:255*r,b:255*s}}(e.h,i,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(n=e.a));return n=Ep(n),{ok:a,format:e.format||o,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}function lp(e,t,n){e=Ap(e,255),t=Ap(t,255),n=Ap(n,255);var i,r,s=Math.max(e,t,n),a=Math.min(e,t,n),o=(s+a)/2;if(s==a)i=r=0;else{var l=s-a;switch(r=o>.5?l/(2-s-a):l/(s+a),s){case e:i=(t-n)/l+(t>1)+720)%360;--t;)i.h=(i.h+r)%360,s.push(op(i));return s}function Tp(e,t){t=t||6;for(var n=op(e).toHsv(),i=n.h,r=n.s,s=n.v,a=[],o=1/t;t--;)a.push(op({h:i,s:r,v:s})),s=(s+o)%1;return a}op.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,n,i=this.toRgb();return e=i.r/255,t=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=Ep(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=up(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=up(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+i+"%)":"hsva("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var e=lp(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=lp(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+i+"%)":"hsla("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHex:function(e){return cp(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,i,r){var s=[Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16)),Np(Lp(i))];if(r&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*Ap(this._r,255))+"%",g:Math.round(100*Ap(this._g,255))+"%",b:Math.round(100*Ap(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Ap(this._r,255))+"%, "+Math.round(100*Ap(this._g,255))+"%, "+Math.round(100*Ap(this._b,255))+"%)":"rgba("+Math.round(100*Ap(this._r,255))+"%, "+Math.round(100*Ap(this._g,255))+"%, "+Math.round(100*Ap(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(wp[cp(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+hp(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?"GradientType = 1, ":"";if(e){var r=op(e);n="#"+hp(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,i=this._a<1&&this._a>=0;return t||!i||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return op(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(mp,arguments)},brighten:function(){return this._applyModification(gp,arguments)},darken:function(){return this._applyModification(_p,arguments)},desaturate:function(){return this._applyModification(dp,arguments)},saturate:function(){return this._applyModification(pp,arguments)},greyscale:function(){return this._applyModification(fp,arguments)},spin:function(){return this._applyModification(vp,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Sp,arguments)},complement:function(){return this._applyCombination(yp,arguments)},monochromatic:function(){return this._applyCombination(Tp,arguments)},splitcomplement:function(){return this._applyCombination(xp,arguments)},triad:function(){return this._applyCombination(bp,[3])},tetrad:function(){return this._applyCombination(bp,[4])}},op.fromRatio=function(e,t){if("object"==rp(e)){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[i]="a"===i?e[i]:Pp(e[i]));e=n}return op(e,t)},op.equals=function(e,t){return!(!e||!t)&&op(e).toRgbString()==op(t).toRgbString()},op.random=function(){return op.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},op.mix=function(e,t,n){n=0===n?0:n||50;var i=op(e).toRgb(),r=op(t).toRgb(),s=n/100;return op({r:(r.r-i.r)*s+i.r,g:(r.g-i.g)*s+i.g,b:(r.b-i.b)*s+i.b,a:(r.a-i.a)*s+i.a})}, // =4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},op.mostReadable=function(e,t,n){var i,r,s,a,o=null,l=0;r=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;ul&&(l=i,o=op(t[u]));return op.isReadable(e,o,{level:s,size:a})||!r?o:(n.includeFallbackColors=!1,op.mostReadable(e,["#fff","#000"],n))};var Mp=op.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",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:"f0f",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:"663399",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"},wp=op.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Mp);function Ep(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Ap(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Rp(e){return Math.min(1,Math.max(0,e))}function Cp(e){return parseInt(e,16)}function Np(e){return 1==e.length?"0"+e:""+e}function Pp(e){return e<=1&&(e=100*e+"%"),e}function Lp(e){return Math.round(255*parseFloat(e)).toString(16)}function Dp(e){return Cp(e)/255}var Ip,Up,Fp,Op=(Up="[\\s|\\(]+("+(Ip="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")\\s*\\)?",Fp="[\\s|\\(]+("+Ip+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")\\s*\\)?",{CSS_UNIT:new RegExp(Ip),rgb:new RegExp("rgb"+Up),rgba:new RegExp("rgba"+Fp),hsl:new RegExp("hsl"+Up),hsla:new RegExp("hsla"+Fp),hsv:new RegExp("hsv"+Up),hsva:new RegExp("hsva"+Fp),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Bp(e){return!!Op.CSS_UNIT.exec(e)}const kp=e=>{e instanceof Array?e.forEach(kp):(e.map&&e.map.dispose(),e.dispose())},zp=e=>{e.geometry&&e.geometry.dispose(),e.material&&kp(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(zp)},Vp=e=>{for(;e.children.length;){const t=e.children[0];e.remove(t),zp(t)}};class Gp extends ep{constructor(e,{dataBindAttr:t="__data",objBindAttr:n="__threeObj"}={}){super(),this.scene=e,this.#e=t,this.#t=n,this.onRemoveObj(()=>{})}onCreateObj(e){return super.onCreateObj(t=>{const n=e(t);return t[this.#t]=n,n[this.#e]=t,this.scene.add(n),n}),this}onRemoveObj(e){return super.onRemoveObj((t,n)=>{const i=super.getData(t);e(t,n),this.scene.remove(t),zp(t),delete i[this.#t]}),this}scene;#e;#t}const Hp=e=>isNaN(e)?parseInt(op(e).toHex(),16):e,Wp=e=>isNaN(e)?op(e).getAlpha():1,jp=function e(){var t=new Dd,n=[],i=[],r=np;function s(e){let s=t.get(e);if(void 0===s){if(r!==np)return r;t.set(e,s=n.push(e)-1)}return i[s%i.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new Dd;for(const i of e)t.has(i)||t.set(i,n.push(i)-1);return s},s.range=function(e){return arguments.length?(i=Array.from(e),s):i.slice()},s.unknown=function(e){return arguments.length?(r=e,s):r},s.copy=function(){return e(n,i).unknown(r)},tp.apply(s,arguments),s}(ip);function $p(e,t,n){t&&"string"==typeof n&&e.filter(e=>!e[n]).forEach(e=>{e[n]=jp(t(e))})}const Xp=window.THREE?window.THREE:{Group:di,Mesh:qr,MeshLambertMaterial:Qs,Color:yi,BufferGeometry:br,BufferAttribute:rr,Matrix4:Bn,Vector3:fn,SphereGeometry:Os,CylinderGeometry:bs,TubeGeometry:Bs,ConeGeometry:xs,Line:class extends hi{constructor(e=new br,t=new rs){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,i=t.count;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e0&&(d.fire("changed",o),o.length=0)}function w(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=n.values(),i=t.next();!i.done;){if(e(i.value))return!0;i=t.next()}}},forcelayout:nd},Yp=(new Xp.BufferGeometry).setAttribute?"setAttribute":"addAttribute",Kp=(new Xp.BufferGeometry).applyMatrix4?"applyMatrix4":"applyMatrix";var Zp=Pd({props:{jsonUrl:{onChange:function(e,t){e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(e=>e.json()).then(e=>{t.fetchingJson=!1,t.onFinishLoading(e),this.graphData(e)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange(e,t){const n=t.d3ForceLayout.force("charge");function i(e,t){e.forEach(e=>{delete e[t],delete e[`v${t}`]})}n&&n.strength(e>2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y")}},dagMode:{onChange(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach(e=>e.fx=e.fy=e.fz=void 0)}},dagLevelDistance:{},dagNodeFilter:{default:e=>!0},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:()=>{},triggerUpdate:!1},onFinishLoading:{default:()=>{},triggerUpdate:!1},onUpdate:{default:()=>{},triggerUpdate:!1},onFinishUpdate:{default:()=>{},triggerUpdate:!1},onEngineTick:{default:()=>{},triggerUpdate:!1},onEngineStop:{default:()=>{},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){const t="ngraph"!==e.forceEngine;return e.engineRunning&&e.layout&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||t&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha(){if(!r)return;const s=t?i:e.layout.getNodePosition(i[e.nodeId]),a=n(i);e.nodePositionUpdate&&e.nodePositionUpdate(a?r.children[0]:r,{x:s.x,y:s.y,z:s.z},i)&&!a||(r.position.x=s.x,r.position.y=s.y||0,r.position.z=s.z||0)});const i=Ld(e.linkWidth),r=Ld(e.linkCurvature),s=Ld(e.linkCurveRotation),a=Ld(e.linkThreeObjectExtend);function o(n){const i=t?n:e.layout.getLinkPosition(e.layout.graph.getLink(n.source,n.target).id),a=i[t?"source":"from"],o=i[t?"target":"to"];if(!(a&&o&&a.hasOwnProperty("x")&&o.hasOwnProperty("x")))return;const l=r(n);if(l){const e=new Xp.Vector3(a.x,a.y||0,a.z||0),t=new Xp.Vector3(o.x,o.y||0,o.z||0),i=e.distanceTo(t);let r;const u=s(n);if(i>0){const n=o.x-a.x,i=o.y-a.y||0,s=(new Xp.Vector3).subVectors(t,e),c=s.clone().multiplyScalar(l).cross(0!==n||0!==i?new Xp.Vector3(0,0,1):new Xp.Vector3(0,1,0)).applyAxisAngle(s.normalize(),u).add((new Xp.Vector3).addVectors(e,t).divideScalar(2));r=new Xp.QuadraticBezierCurve3(e,c,t)}else{const n=70*l,i=-u,s=i+Math.PI/2;r=new Xp.CubicBezierCurve3(e,new Xp.Vector3(n*Math.cos(s),n*Math.sin(s),0).add(e),new Xp.Vector3(n*Math.cos(i),n*Math.sin(i),0).add(e),t)}n.__curve=r}else n.__curve=null}e.linkDataMapper.entries().forEach(([n,r])=>{if(!r)return;const s=t?n:e.layout.getLinkPosition(e.layout.graph.getLink(n.source,n.target).id),l=s[t?"source":"from"],u=s[t?"target":"to"];if(!(l&&u&&l.hasOwnProperty("x")&&u.hasOwnProperty("x")))return;o(n);const c=a(n);if(e.linkPositionUpdate&&e.linkPositionUpdate(c?r.children[1]:r,{start:{x:l.x,y:l.y,z:l.z},end:{x:u.x,y:u.y,z:u.z}},n)&&!c)return;const h=30,d=n.__curve,p=r.children.length?r.children[0]:r;if("Line"===p.type){if(d){const e=d.getPoints(h);p.geometry.getAttribute("position").array.length!==3*e.length&&p.geometry[Yp]("position",new Xp.BufferAttribute(new Float32Array(3*e.length),3)),p.geometry.setFromPoints(e)}else{let e=p.geometry.getAttribute("position");e&&e.array&&6===e.array.length||p.geometry[Yp]("position",e=new Xp.BufferAttribute(new Float32Array(6),3)),e.array[0]=l.x,e.array[1]=l.y||0,e.array[2]=l.z||0,e.array[3]=u.x,e.array[4]=u.y||0,e.array[5]=u.z||0,e.needsUpdate=!0}p.geometry.computeBoundingSphere()}else if("Mesh"===p.type)if(d){p.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(p.position.set(0,0,0),p.rotation.set(0,0,0),p.scale.set(1,1,1));const t=Math.ceil(10*i(n))/10/2,r=new Xp.TubeGeometry(d,h,t,e.linkResolution,!1);p.geometry.dispose(),p.geometry=r}else{if(!p.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){const t=Math.ceil(10*i(n))/10/2,r=new Xp.CylinderGeometry(t,t,1,e.linkResolution,1,!1);r[Kp]((new Xp.Matrix4).makeTranslation(0,.5,0)),r[Kp]((new Xp.Matrix4).makeRotationX(Math.PI/2)),p.geometry.dispose(),p.geometry=r}const t=new Xp.Vector3(l.x,l.y||0,l.z||0),r=new Xp.Vector3(u.x,u.y||0,u.z||0),s=t.distanceTo(r);p.position.x=t.x,p.position.y=t.y,p.position.z=t.z,p.scale.z=s,p.parent.localToWorld(r),p.lookAt(r)}})}(),function(){const n=Ld(e.linkDirectionalArrowRelPos),i=Ld(e.linkDirectionalArrowLength),r=Ld(e.nodeVal);e.arrowDataMapper.entries().forEach(([s,a])=>{if(!a)return;const o=t?s:e.layout.getLinkPosition(e.layout.graph.getLink(s.source,s.target).id),l=o[t?"source":"from"],u=o[t?"target":"to"];if(!(l&&u&&l.hasOwnProperty("x")&&u.hasOwnProperty("x")))return;const c=Math.cbrt(Math.max(0,r(l)||1))*e.nodeRelSize,h=Math.cbrt(Math.max(0,r(u)||1))*e.nodeRelSize,d=i(s),p=n(s),f=s.__curve?e=>s.__curve.getPoint(e):e=>{const t=(e,t,n,i)=>t[e]+(n[e]-t[e])*i||0;return{x:t("x",l,u,e),y:t("y",l,u,e),z:t("z",l,u,e)}},m=s.__curve?s.__curve.getLength():Math.sqrt(["x","y","z"].map(e=>Math.pow((u[e]||0)-(l[e]||0),2)).reduce((e,t)=>e+t,0)),g=c+d+(m-c-h-d)*p,_=f(g/m),v=f((g-d)/m);["x","y","z"].forEach(e=>a.position[e]=v[e]);const y=new Xp.Vector3(...["x","y","z"].map(e=>_[e]));a.parent.localToWorld(y),a.lookAt(y)})}(),function(){const n=Ld(e.linkDirectionalParticleSpeed),i=Ld(e.linkDirectionalParticleOffset);e.graphData.links.forEach(r=>{const s=e.particlesDataMapper.getObj(r),a=s&&s.children,o=r.__singleHopPhotonsObj&&r.__singleHopPhotonsObj.children;if(!(o&&o.length||a&&a.length))return;const l=t?r:e.layout.getLinkPosition(e.layout.graph.getLink(r.source,r.target).id),u=l[t?"source":"from"],c=l[t?"target":"to"];if(!(u&&c&&u.hasOwnProperty("x")&&c.hasOwnProperty("x")))return;const h=n(r),d=Math.abs(i(r)),p=r.__curve?e=>r.__curve.getPoint(e):e=>{const t=(e,t,n,i)=>t[e]+(n[e]-t[e])*i||0;return{x:t("x",u,c,e),y:t("y",u,c,e),z:t("z",u,c,e)}};[...a||[],...o||[]].forEach((e,t)=>{const n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?h<0?1:0:(t+d)/a.length),e.__progressRatio+=h,e.__progressRatio>=1||e.__progressRatio<0){if(n)return e.parent.remove(e),void Vp(e);e.__progressRatio=e.__progressRatio%1,e.__progressRatio<0&&e.__progressRatio++}const i=e.__progressRatio,r=p(i);"SphereGeometry"!==e.geometry.type&&e.lookAt(r.x,r.y,r.z),["x","y","z"].forEach(t=>e.position[t]=r[t])})})}(),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){const n=new Xp.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}let n=Ld(e.linkDirectionalParticleThreeObject)(t);if(n&&e.linkDirectionalParticleThreeObject===n&&(n=n.clone()),!n){const i=Ld(e.linkDirectionalParticleWidth),r=Math.ceil(10*i(t))/10/2,s=e.linkDirectionalParticleResolution,a=new Xp.SphereGeometry(r,s,s),o=Ld(e.linkColor),l=Ld(e.linkDirectionalParticleColor)(t)||o(t)||"#f0f0f0",u=new Xp.Color(Hp(l)),c=3*e.linkOpacity,h=new Xp.MeshLambertMaterial({color:u,transparent:!0,opacity:c});n=new Xp.Mesh(a,h)}t.__singleHopPhotonsObj.add(n)}return this},getGraphBbox:function(e,t=()=>!0){if(!e.initialised)return null;const n=function e(n){const i=[];if(n.geometry){n.geometry.computeBoundingBox();const e=new Xp.Box3;e.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),i.push(e)}return i.concat(...(n.children||[]).filter(e=>!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)).map(e))}(e.graphScene);return n.length?Object.assign(...["x","y","z"].map(e=>({[e]:[Od(n,t=>t.min[e]),Fd(n,t=>t.max[e])]}))):null}},stateInit:()=>({d3ForceLayout:mh().force("link",zc()).force("charge",gh()).force("center",cc()).force("dagRadial",null).stop(),engineRunning:!1}),init(e,t){t.graphScene=e,t.nodeDataMapper=new Gp(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Gp(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Gp(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Gp(e,{objBindAttr:"__photonsObj"})},update(e,t){const n=e=>e.some(e=>t.hasOwnProperty(e));if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&$p(e.graphData.nodes,Ld(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&$p(e.graphData.links,Ld(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){const t=Ld(e.nodeThreeObject),i=Ld(e.nodeThreeObjectExtend),r=Ld(e.nodeVal),s=Ld(e.nodeColor),a=Ld(e.nodeVisibility),o={},l={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(n=>{let r=t(n);const s=i(n);let a;return r&&e.nodeThreeObject===r&&(r=r.clone()),r&&!s?a=r:(a=new Xp.Mesh,a.__graphDefaultObj=!0,r&&s&&a.add(r)),a.__graphObjType="node",a}).onUpdateObj((t,n)=>{if(t.__graphDefaultObj){const i=r(n)||1,a=Math.cbrt(i)*e.nodeRelSize,u=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===a&&t.geometry.parameters.widthSegments===u||(o.hasOwnProperty(i)||(o[i]=new Xp.SphereGeometry(a,u,u)),t.geometry.dispose(),t.geometry=o[i]);const c=s(n),h=new Xp.Color(Hp(c||"#ffffaa")),d=e.nodeOpacity*Wp(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(l.hasOwnProperty(c)||(l[c]=new Xp.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=l[c])}}).digest(e.graphData.nodes.filter(a))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){const i=Ld(e.linkThreeObject),r=Ld(e.linkThreeObjectExtend),s=Ld(e.linkMaterial),a=Ld(e.linkVisibility),o=Ld(e.linkColor),l=Ld(e.linkWidth),u={},c={},h={},d=e.graphData.links.filter(a);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(e=>{const t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),Vp(t),delete e.__data.__singleHopPhotonsObj)}).onCreateObj(t=>{let n=i(t);const s=r(t);let a,o;if(n&&e.linkThreeObject===n&&(n=n.clone()),!n||s){if(!!l(t))a=new Xp.Mesh;else{const e=new Xp.BufferGeometry;e[Yp]("position",new Xp.BufferAttribute(new Float32Array(6),3)),a=new Xp.Line(e)}}return n?s?(o=new Xp.Group,o.__graphDefaultObj=!0,o.add(a),o.add(n)):o=n:(o=a,o.__graphDefaultObj=!0),o.renderOrder=10,o.__graphObjType="link",o}).onUpdateObj((t,n)=>{if(t.__graphDefaultObj){const i=t.children.length?t.children[0]:t,r=Math.ceil(10*l(n))/10,a=!!r;if(a){const t=r/2,n=e.linkResolution;if(!i.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||i.geometry.parameters.radiusTop!==t||i.geometry.parameters.radialSegments!==n){if(!u.hasOwnProperty(r)){const e=new Xp.CylinderGeometry(t,t,1,n,1,!1);e[Kp]((new Xp.Matrix4).makeTranslation(0,.5,0)),e[Kp]((new Xp.Matrix4).makeRotationX(Math.PI/2)),u[r]=e}i.geometry.dispose(),i.geometry=u[r]}}const d=s(n);if(d)i.material=d;else{const t=o(n),r=new Xp.Color(Hp(t||"#f0f0f0")),s=e.linkOpacity*Wp(t),l=a?"MeshLambertMaterial":"LineBasicMaterial";if(i.material.type!==l||!i.material.color.equals(r)||i.material.opacity!==s){const e=a?c:h;e.hasOwnProperty(t)||(e[t]=new Xp[l]({color:r,transparent:s<1,opacity:s,depthWrite:s>=1})),i.material.dispose(),i.material=e[t]}}}}).digest(d),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){const t=Ld(e.linkDirectionalArrowLength),n=Ld(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(()=>{const e=new Xp.Mesh(void 0,new Xp.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e}).onUpdateObj((i,r)=>{const s=t(r),a=e.linkDirectionalArrowResolution;if(!i.geometry.type.match(/^Cone(Buffer)?Geometry$/)||i.geometry.parameters.height!==s||i.geometry.parameters.radialSegments!==a){const e=new Xp.ConeGeometry(.25*s,s,a);e.translate(0,s/2,0),e.rotateX(Math.PI/2),i.geometry.dispose(),i.geometry=e}const l=n(r)||o(r)||"#f0f0f0";i.material.color=new Xp.Color(Hp(l)),i.material.opacity=3*e.linkOpacity*Wp(l)}).digest(d.filter(t))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){const t=Ld(e.linkDirectionalParticles),n=Ld(e.linkDirectionalParticleWidth),i=Ld(e.linkDirectionalParticleColor),r=Ld(e.linkDirectionalParticleThreeObject),s={},a={};e.particlesDataMapper.onCreateObj(()=>{const e=new Xp.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new Gp(e),e}).onUpdateObj((l,u)=>{const c=!!l.children.length&&l.children[0],h=r(u);let d,p;if(h)d=h.geometry,p=h.material;else{const t=Math.ceil(10*n(u))/10/2,r=e.linkDirectionalParticleResolution;c&&c.geometry.parameters.radius===t&&c.geometry.parameters.widthSegments===r?d=c.geometry:(a.hasOwnProperty(t)||(a[t]=new Xp.SphereGeometry(t,r,r)),d=a[t]);const l=i(u)||o(u)||"#f0f0f0",h=new Xp.Color(Hp(l)),f=3*e.linkOpacity;c&&c.material.color.equals(h)&&c.material.opacity===f?p=c.material:(s.hasOwnProperty(l)||(s[l]=new Xp.MeshLambertMaterial({color:h,transparent:!0,opacity:f})),p=s[l])}c&&(c.geometry!==d&&c.geometry.dispose(),c.material!==p&&c.material.dispose());const f=Math.round(Math.abs(t(u)));l.__photonDataMapper.id(e=>e.idx).onCreateObj(()=>new Xp.Mesh(d,p)).onUpdateObj(e=>{e.geometry=d,e.material=p}).digest([...new Array(f)].map((e,t)=>({idx:t})))}).digest(d.filter(t))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(t=>{t.source=t[e.linkSource],t.target=t[e.linkTarget]});const n="ngraph"!==e.forceEngine;let i;if(n){(i=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);const n=e.d3ForceLayout.force("link");n&&n.id(t=>t[e.nodeId]).links(e.graphData.links);const r=e.dagMode&&function({nodes:e,links:t},n,{nodeFilter:i=()=>!0,onLoopError:r=e=>{throw`Invalid DAG structure! Found cycle in node path: ${e.join(" -> ")}.`}}={}){const s={};e.forEach(e=>s[n(e)]={data:e,out:[],depth:-1,skip:!i(e)}),t.forEach(({source:e,target:t})=>{const i=l(e),r=l(t);if(!s.hasOwnProperty(i))throw`Missing source node with id: ${i}`;if(!s.hasOwnProperty(r))throw`Missing target node with id: ${r}`;const a=s[i],o=s[r];function l(e){return"object"==typeof e?n(e):e}a.out.push(o)});const a=[];return function e(t,i=[],s=0){for(let o=0,l=t.length;on(e.data));a.some(t=>t.length===e.length&&t.every((t,n)=>t===e[n]))||(a.push(e),r(e));continue}s>l.depth&&(l.depth=s,e(l.out,[...i,l],s+(l.skip?0:1)))}}(Object.values(s)),Object.assign({},...Object.entries(s).filter(([,e])=>!e.skip).map(([e,t])=>({[e]:t.depth})))}(e.graphData,t=>t[e.nodeId],{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),s=Math.max(...Object.values(r||[])),a=e.dagLevelDistance||e.graphData.nodes.length/(s||1)*2*(-1!==["radialin","radialout"].indexOf(e.dagMode)?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){const n=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(e=>delete e[n])}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){const t=["rl","td","zout"].includes(e.dagMode),n=n=>(r[n[e.nodeId]]-s/2)*a*(t?-1:1),i=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(e=>e[i]=n(e))}e.d3ForceLayout.force("dagRadial",-1!==["radialin","radialout"].indexOf(e.dagMode)?function(e,t,n,i){var r,s,a,o,l=Fc(.1);function u(e){for(var l=0,u=r.length;l1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(r){var t,n=r.length;for(a=new Array(n),o=new Array(n),t=0;t[1,2,3].includes(e))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:Fc(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:Fc(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(i=+e,u):i},u}(t=>{const n=r[t[e.nodeId]]||-1;return("radialin"===e.dagMode?s-n:n)*a}).strength(t=>e.dagNodeFilter(t)?1:0):null)}else{const t=qp.graph();e.graphData.nodes.forEach(n=>{t.addNode(n[e.nodeId])}),e.graphData.links.forEach(e=>{t.addLink(e.source,e.target)}),i=qp.forcelayout(t,{dimensions:e.numDimensions,...e.ngraphPhysics}),i.graph=t}for(let t=0;t0&&e.d3ForceLayout.alpha()i.prototype[e]=function(...t){const n=this.__kapsuleInstance[e](...t);return n===this.__kapsuleInstance?this:n}),i}(Zp,(window.THREE?window.THREE:{Group:di}).Group,!0);const Jp=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","bumpScale","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dashOffset","dashSize","dispersion","displacementBias","displacementMap","displacementScale","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","envMapRotation","gapSize","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThickness","iridescenceThicknessMap","lightMap","lightMapIntensity","linewidth","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","reflectivity","retroreflectivity","rotation","roughness","roughnessMap","scale","sheen","sheenColor","sheenColorMap","sheenRoughness","sheenRoughnessMap","shininess","size","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","steps","thickness","transmission","transmissionMap","wireframe"],ef=new WeakMap,tf=new WeakMap,nf=new WeakMap,rf=new WeakMap;class sf{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Jp,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}hasDynamicInstancing(e){return!0===e.isInstancedMesh&&(e.instanceMatrix.usage===Lt||null!==e.instanceColor&&e.instanceColor.usage===Lt)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:n,object:i}=e;t={geometryId:n.id,geometryVersion:this.getGeometryData(n)._version,materialVersion:this.getMaterialData(e.material)._version,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),!0===i.isInstancedMesh&&(t.instanceMatrixVersion=i.instanceMatrix.version,t.instanceColorVersion=null!==i.instanceColor?i.instanceColor.version:null,t.morphTextureVersion=null!==i.morphTexture?i.morphTexture.version:null),!0===i.isBatchedMesh&&(t.matricesTextureVersion=i._matricesTexture.version,t.colorsTextureVersion=null!==i._colorsTexture?i._colorsTexture.version:null,t.indirectTextureVersion=i._indirectTexture.version),null!==e.bundle&&(t.version=e.bundle.version);const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s;const{environmentIntensity:a,environmentRotation:o}=e.scene;t.environmentIntensity=a,t.environmentRotation=o.clone(),t.lights=this.getLightsData(e.lightsNode.getBuiltinLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={id:i.isInterleavedBufferAttribute?i.data.uuid:i.id,version:i.isInterleavedBufferAttribute?i.data.version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=nf.get(e);return void 0===t&&(t={_renderId:-1,_version:0,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},e.addEventListener("dispose",()=>{t._version++}),nf.set(e,t)),t}getTextureData(e){let t=rf.get(e);if(void 0===t){t={_version:0};const n=()=>{t._version++};null!==e.renderTarget?e.renderTarget.addEventListener("dispose",n):e.addEventListener("dispose",n),rf.set(e,t)}return t}getMaterialData(e){let t=tf.get(e);if(void 0===t){t={_renderId:-1,_version:0};for(const n of this.refreshUniforms){const i=e[n];void 0!==i&&(null===i?t[n]=null:"object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[n]={id:i.id,version:0,cacheVersion:this.getTextureData(i)._version}:t[n]=i.clone():t[n]=i)}tf.set(e,t)}return t}equals(e,t,n){const{object:i,material:r,geometry:s}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(i.matrixWorld))return a.worldMatrix.copy(i.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==n){o._renderId=n;let e=!1;for(const t in o){const n=o[t],i=r[t];if("_renderId"!==t&&"_version"!==t)if(null===n||null==i)n!==(void 0===i?null:i)&&(null==i?o[t]=null:!0===i.isTexture?o[t]={id:i.id,version:i.version,cacheVersion:this.getTextureData(i)._version}:"object"==typeof i&&void 0!==i.clone?o[t]=i.clone():o[t]=i,e=!0);else if(void 0!==n.equals)!1===n.equals(i)&&(n.copy(i),e=!0);else if(!0===i.isTexture){const t=this.getTextureData(i);n.id===i.id&&n.version===i.version&&n.cacheVersion===t._version||(n.id=i.id,n.version=i.version,n.cacheVersion=t._version,e=!0)}else n!==i&&(o[t]=i,e=!0)}!0===e&&o._version++}if(a.materialVersion!==o._version)return a.materialVersion=o._version,!1;const{width:l,height:u}=e.context;if(a.bufferWidth!==l||a.bufferHeight!==u)return a.bufferWidth=l,a.bufferHeight=u,!1;if(a.geometryId!==s.id)return a.geometryId=s.id,a.geometryVersion=this.getGeometryData(s)._version,!1;const c=this.getGeometryData(e.geometry);if(c._renderId!==n){c._renderId=n;let e=!1;const t=s.attributes,i=c.attributes;let r=0,a=0;for(const e in t)r++;for(const n in i){a++;const r=i[n],s=t[n];if(void 0===s){delete i[n],e=!0;continue}const o=s.isInterleavedBufferAttribute?s.data.uuid:s.id,l=s.isInterleavedBufferAttribute?s.data.version:s.version;r.id===o&&r.version===l||(r.id=o,r.version=l,e=!0)}a!==r&&(c.attributes=this.getAttributesData(t),e=!0);const o=s.index,l=o?o.id:null,u=o?o.version:null;c.indexId===l&&c.indexVersion===u||(c.indexId=l,c.indexVersion=u,e=!0),c.drawRange.start===s.drawRange.start&&c.drawRange.count===s.drawRange.count||(c.drawRange.start=s.drawRange.start,c.drawRange.count=s.drawRange.count,e=!0),!0===e&&c._version++}if(a.geometryVersion!==c._version)return a.geometryVersion=c._version,!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t{const n=e.match(t);if(!n)return null;const i=n[1]||n[2]||"",r=n[3].split("?")[0],s=parseInt(n[4],10),a=parseInt(n[5],10);return{fn:i,file:r.split("/").pop(),line:s,column:a}}).filter(e=>e&&!af.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;const t=this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n");return`${e}\n${t}`}}function lf(e,t=0){let n=3735928559^t,i=1103547991^t;if(Array.isArray(e))for(let t,r=0;r>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&i)+(n>>>0)}const uf=e=>lf(e),cf=e=>lf(e),hf=(...e)=>lf(e),df=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),pf=new WeakMap;function ff(e){return df.get(e)}function mf(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function gf(e){if(!0===e.isDepthTexture)return"float";const t=e.format;let n,i;if(n=t===Ce||t===Ne||t===Ae||t===Re||t===Me?1:t===Pe||t===Le?2:t===we||t===De?3:4,i=e.type===ge?"uint":e.type===me?"int":"float",1===n)return i;let r=ff(n);return"float"!==i&&(r=i[0]+r),r}function _f(e,...t){const n=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===n?t=[t[0],t[0]]:"vec3"===n?t=[t[0],t[0],t[0]]:"vec4"===n&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new yi(...t):"vec2"===n?new dn(...t):"vec3"===n?new fn(...t):"vec4"===n?new Dn(...t):"mat2"===n?new $a(...t):"mat3"===n?new _n(...t):"mat4"===n?new Bn(...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 vf(e){let t=pf.get(e);return void 0===t&&(t={},pf.set(e,t)),t}function yf(e){return void 0!==e[0]&&null!==e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}const bf="vertex",xf="none",Sf="frame",Tf="render",Mf="object",wf="readOnly",Ef="writeOnly",Af="readWrite",Rf=["setup","analyze","generate"],Cf=["fragment","vertex","compute"],Nf=["x","y","z","w"],Pf={analyze:"setup",generate:"analyze"};let Lf=0;class Df extends Jt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=xf,this.updateBeforeType=xf,this.updateAfterType=xf,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=Lf++,this.stackTrace=null,!0===Df.captureStackTrace&&(this.stackTrace=new of)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=hn.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,Sf)}onRenderUpdate(e){return this.onUpdate(e,Tf)}onObjectUpdate(e){return this.onUpdate(e,Mf)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const i=this[n];if(!0!==n.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}Df.captureStackTrace=!1;class If extends Df{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Uf extends Df{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}class Ff extends Df{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 n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}class Of extends Ff{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),i=e.getTypeLength(n),r=this.nodes,s=e.getComponentType(n),a=[];let o=0;for(const t of r){if(o>=i){Yt(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let r,l=t.getNodeType(e),u=e.getTypeLength(l);o+u>i&&(Yt(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),u=i-o,l=e.getTypeFromLength(u)),o+=u,r=t.build(e,l);if(e.getComponentType(l)!==s){const t=e.getTypeFromLength(u,s);r=e.format(r,l,t)}a.push(r)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const Bf=Nf.join("");class kf extends Df{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(Nf.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===Bf.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class zf extends Ff{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=i.build(e,a),l=t.build(e,r),u=e.getTypeLength(r),c=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Df.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==$f?$f.assign(this,...e):Yt("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new of),this;{const t=Xf.get("assign");return this.addToStack(t(...e))}},Df.prototype.toVarIntent=function(){return this},Df.prototype.get=function(e){return new jf(this,e)};const Kf={};function Zf(e,t,n){Kf[e]=Kf[t]=Kf[n]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new kf(this,e),this._cache[e]=t),t},set(t){this[e].assign(xm(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),s=n.toUpperCase();Df.prototype["set"+i]=Df.prototype["set"+r]=Df.prototype["set"+s]=function(t){const n=Yf(e);return new zf(this,n,xm(t))},Df.prototype["flip"+i]=Df.prototype["flip"+r]=Df.prototype["flip"+s]=function(){const t=Yf(e);return new Vf(this,t)}}const Qf=["x","y","z","w"],Jf=["r","g","b","a"],em=["s","t","p","q"];for(let e=0;e<4;e++){let t=Qf[e],n=Jf[e],i=em[e];Zf(t,n,i);for(let r=0;r<4;r++){t=Qf[e]+Qf[r],n=Jf[e]+Jf[r],i=em[e]+em[r],Zf(t,n,i);for(let s=0;s<4;s++){t=Qf[e]+Qf[r]+Qf[s],n=Jf[e]+Jf[r]+Jf[s],i=em[e]+em[r]+em[s],Zf(t,n,i);for(let a=0;a<4;a++)t=Qf[e]+Qf[r]+Qf[s]+Qf[a],n=Jf[e]+Jf[r]+Jf[s]+Jf[a],i=em[e]+em[r]+em[s]+em[a],Zf(t,n,i)}}}for(let e=0;e<32;e++)Kf[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new If(this,new Wf(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(xm(t))}};Object.defineProperties(Df.prototype,Kf);const tm=function(e,t=null){for(const n in e)e[n]=xm(e[n],t);return e},nm=function(e,t=null){const n=e.length;for(let i=0;io?(Yt(`TSL: "${n}" parameter length exceeds limit.`,new of),t.slice(0,o)):t}return null===t?s=(...t)=>r(new e(...Mm(u(t)))):null!==n?(n=xm(n),s=(...i)=>r(new e(t,...Mm(u(i)),n))):s=(...n)=>r(new e(t,...Mm(u(n)))),s.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),s),s.setName=e=>(l=e,s),s},rm=function(e,...t){return new e(...Mm(t))};class sm extends Df{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",s=r||"default";if(i[s])return i[s];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){if(n){const i=t.layout.inputs;if(yf(n)){const t=n;for(let n=0;n{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,n),i}}),r=n?function(e){let t=0;return Tm(e),new Proxy(e,{get:(n,i,r)=>{let s;if("length"===i)return s=e.length,s;if(Symbol.iterator===i)s=function*(){for(const t of e)yield xm(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const n=e[0];s=void 0===n[i]?n[t++]:Reflect.get(n,i,r)}else e[0]instanceof Df&&(s=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else s=Reflect.get(n,i,r);s=xm(s)}return s}})}(n):null,s=Array.isArray(n)?n.length>0:null!==n,a=t.jsFunc,o=s||a.length>1?a(r,i):a(i);l=xm(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(i[s]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),s=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[s]=this.getOutputNode(e),r[s].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const n=e.getDataFromNode(t,"any");n.subBuilds=n.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=r[s]}else"analyze"===i?a.build(e,t):"generate"===i&&(n=a.build(e,t)||"");return e.fnCall=o,n}}class am extends Df{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new sm(this,e)}setup(){return this.call()}}const om=[!1,!0],lm=[0,1,2,3],um=[-1,-2],cm=[.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],hm=new Map;for(const e of om)hm.set(e,new Wf(e));const dm=new Map;for(const e of lm)dm.set(e,new Wf(e,"uint"));const pm=new Map([...dm].map(e=>new Wf(e.value,"int")));for(const e of um)pm.set(e,new Wf(e,"int"));const fm=new Map([...pm].map(e=>new Wf(e.value)));for(const e of cm)fm.set(e,new Wf(e));for(const e of cm)fm.set(-e,new Wf(-e));const mm={bool:hm,uint:dm,ints:pm,float:fm},gm=new Map([...hm,...fm]),_m=(e,t)=>gm.has(e)?gm.get(e):!0===e.isNode?e:new Wf(e,t),vm=function(e,t=null){return(...n)=>{for(const t of n)if(void 0===t)return Yt(`TSL: Invalid parameter for the type "${e}".`,new of),new Wf(0,e);if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(n=[_f(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Sm(t.get(n[0]));if(1===n.length){const t=_m(n[0],e);return t.nodeType===e?Sm(t):Sm(new Uf(t,e))}const i=n.map(e=>_m(e));return Sm(new Of(i,e))}};function ym(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}function bm(e,t){return new am(e,t)}const xm=(e,t=null)=>function(e,t=null){const n=mf(e);return"node"===n?e:null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?xm(_m(e,t)):"shader"===n?e.isFn?e:Nm(e):e}(e,t),Sm=(e,t=null)=>xm(e,t).toVarIntent(),Tm=(e,t=null)=>new tm(e,t),Mm=(e,t=null)=>new nm(e,t),wm=(e,t=null,n=null,i=null)=>new im(e,t,n,i),Em=(e,...t)=>new rm(e,...t),Am=(e,t=null,n=null,i={})=>new im(e,t,n,{...i,intent:!0});let Rm=0;class Cm extends Df{constructor(e,t=null){super();let n=null;null!==t&&("object"==typeof t?n=t.return:("string"==typeof t?n=t:Yt("TSL: Invalid layout type.",new of),t=null)),this.shaderNode=new bm(e,n),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const n={name:"fn"+Rm++,type:t,inputs:[]};for(const t in e)"return"!==t&&n.inputs.push({name:t,type:e[t]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return Yt('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function Nm(e,t=null){const n=new Cm(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>n.call(...i),get:(e,t,i)=>Reflect.get(n,t,i),set:(e,t,i,r)=>Reflect.set(n,t,i,r)})}const Pm=e=>{$f=e},Lm=()=>$f,Dm=(...e)=>$f.If(...e);qf("toStack",function(e){return $f&&$f.addToStack(e),e});const Im=new vm("color"),Um=new vm("float",mm.float),Fm=new vm("int",mm.ints),Om=new vm("uint",mm.uint),Bm=new vm("bool",mm.bool),km=new vm("vec2"),zm=new vm("ivec2"),Vm=new vm("uvec2"),Gm=new vm("bvec2"),Hm=new vm("vec3"),Wm=new vm("ivec3"),jm=new vm("uvec3"),$m=new vm("bvec3"),Xm=new vm("vec4"),qm=new vm("ivec4"),Ym=new vm("uvec4"),Km=new vm("bvec4"),Zm=new vm("mat2"),Qm=new vm("mat3"),Jm=new vm("mat4");qf("toColor",Im),qf("toFloat",Um),qf("toInt",Fm),qf("toUint",Om),qf("toBool",Bm),qf("toVec2",km),qf("toIVec2",zm),qf("toUVec2",Vm),qf("toBVec2",Gm),qf("toVec3",Hm),qf("toIVec3",Wm),qf("toUVec3",jm),qf("toBVec3",$m),qf("toVec4",Xm),qf("toIVec4",qm),qf("toUVec4",Ym),qf("toBVec4",Km),qf("toMat2",Zm),qf("toMat3",Qm),qf("toMat4",Jm);qf("element",wm(If).setParameterLength(2)),qf("convert",(e,t)=>new Uf(xm(e),t));class eg extends Df{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1,i=null){super(e),this.name=t,this.varying=n,this.placeholderNode=xm(i),this.isPropertyNode=!0,this.global=!0}getNodeType(e){const t=super.getNodeType(e);return"output"===t?e.getOutputType():t}customCacheKey(){return uf(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(!0===this.varying)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),null!==this.placeholderNode&&!1===e.hasWriteUsage(this)){const n=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${n}`,this)}return e.getPropertyName(t)}}const tg=(e,t,n=null)=>new eg(e,t,!1,n),ng=(e,t,n=null)=>new eg(e,t,!0,n),ig=Em(eg,"vec4","DiffuseColor"),rg=Em(eg,"vec3","DiffuseContribution"),sg=Em(eg,"vec3","EmissiveColor"),ag=Em(eg,"float","Roughness"),og=Em(eg,"float","Metalness"),lg=Em(eg,"float","Clearcoat"),ug=Em(eg,"float","ClearcoatRoughness"),cg=Em(eg,"vec3","Sheen"),hg=Em(eg,"float","SheenRoughness"),dg=Em(eg,"float","Iridescence"),pg=Em(eg,"float","IridescenceIOR"),fg=Em(eg,"float","IridescenceThickness"),mg=Em(eg,"float","AlphaT"),gg=Em(eg,"float","Anisotropy"),_g=Em(eg,"vec3","AnisotropyT"),vg=Em(eg,"vec3","AnisotropyB"),yg=Em(eg,"color","SpecularColor"),bg=Em(eg,"color","SpecularColorBlended"),xg=Em(eg,"float","SpecularF90"),Sg=Em(eg,"float","Shininess"),Tg=Em(eg,"output","Output"),Mg=Em(eg,"float","dashSize"),wg=Em(eg,"float","gapSize"),Eg=Em(eg,"float","IOR"),Ag=Em(eg,"float","Transmission"),Rg=Em(eg,"float","Thickness"),Cg=Em(eg,"float","AttenuationDistance"),Ng=Em(eg,"color","AttenuationColor"),Pg=Em(eg,"float","Dispersion"),Lg=Em(eg,"float","Retroreflectivity"),Dg=Em(eg,"float","AmbientOcclusion",!1,1);class Ig extends Df{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1,i=null){super("string"),this.name=e,this.shared=t,this.order=n,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const Ug=(e,t=1,n=null)=>new Ig(e,!1,t,n),Fg=(e,t=0,n=null)=>new Ig(e,!0,t,n),Og=Fg("render",0,Tf),Bg=Ug("object",1,Mf);class kg extends Gf{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Bg}setName(e){return this.name=e,this}label(e){return qt('TSL: "label()" has been deprecated. Use "setName()" instead.',new of),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}getSharedNode(e){const t=this.getUniformHash(e);let n=e.getNodeFromHash(t);return void 0===n&&(e.setHashNode(this,t),n=this),n}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const n=e(t,this);void 0!==n&&(this.value=n)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),i=this.getSharedNode(e),r=i.getInputType(e),s=e.getUniformFromNode(i,r,e.shaderStage,this.name||e.context.nodeName),a=e.getPropertyName(s);void 0!==e.context.nodeName&&delete e.context.nodeName;let o=a;if("bool"===n){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const s=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(s),t.propertyName=i,o=e.format(a,r,n),e.addLineFlowCode(`${i} = ${o}`,this)}o=i}return e.format(o,n,t)}}const zg=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(n===e&&(e=_f(n)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new kg(e,n)};class Vg extends Ff{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const Gg=(...e)=>{let t;if(1===e.length){const n=e[0].map(e=>xm(e));t=new Vg(null,n.length,n)}else{const n=e[0],i=e[1];t=new Vg(n,i)}return t};qf("toArray",(e,t)=>Gg(Array(t).fill(e)));class Hg extends Ff{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return Nf.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=n,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),s=n.build(e),a=n.getNodeType(e),o=i.build(e,a),l=i.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=s);else if(r){const i=e.getVarFromNode(this,null,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const l=n.node,u=l.node.context({assign:!0}).build(e);for(let t=0;t{const i=n.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)Yt("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length(t=t.length>1||t[0]&&!0===t[0].isNode?Mm(t):Tm(t[0]),new Wg(xm(e),t)));const jg={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class $g extends Ff{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let r=new $g(e,t,n);for(let t=0;t>"===n||"<<"===n)return e.getIntegerType(s);if("&&"===n||"||"===n||"^^"===n)return"bool";if("!"===n){const t=e.getTypeLength(s);return t>1?`bvec${t}`:"bool"}if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n){const t=Math.max(e.getTypeLength(s),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(s)){if("float"===a)return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if("float"===s)return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,{aNode:i,bNode:r}=this,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n||"!="===n?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):"%"===n?(a=s,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=i.build(e,a),u=r?r.build(e,o):null,c=e.getFunctionOperator(n);if("void"!==t){const i=e.renderer.coordinateSystem===It;if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t);if("%"===n)return e.isInteger(o)?e.format(`( ${l} % ${u} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${u} )`,s,t);if("!"===n)return i&&e.isVector(a)?e.format(`not( ${l} )`,t):e.format(`( ${n} ${l} )`,a,t);if("~"===n)return e.format(`( ${n} ${l} )`,a,t);if(c)return e.format(`${c}( ${l}, ${u} )`,s,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${u} ${n} ${l} )`,s,t);if("float"===a&&e.isMatrix(o))return e.format(`${l} ${n} ${u}`,s,t);{let r=`( ${l} ${n} ${u} )`;return!i&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,s,t)}}if("void"!==a)return c?e.format(`${c}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Xg=Am($g,"+").setParameterLength(2,1/0).setName("add"),qg=Am($g,"-").setParameterLength(2,1/0).setName("sub"),Yg=Am($g,"*").setParameterLength(2,1/0).setName("mul"),Kg=Am($g,"/").setParameterLength(2,1/0).setName("div"),Zg=Am($g,"%").setParameterLength(2).setName("mod"),Qg=Am($g,"==").setParameterLength(2).setName("equal"),Jg=Am($g,"!=").setParameterLength(2).setName("notEqual"),e_=Am($g,"<").setParameterLength(2).setName("lessThan"),t_=Am($g,">").setParameterLength(2).setName("greaterThan"),n_=Am($g,"<=").setParameterLength(2).setName("lessThanEqual"),i_=Am($g,">=").setParameterLength(2).setName("greaterThanEqual"),r_=Am($g,"&&").setParameterLength(2,1/0).setName("and"),s_=Am($g,"||").setParameterLength(2,1/0).setName("or"),a_=Am($g,"!").setParameterLength(1).setName("not"),o_=Am($g,"^^").setParameterLength(2).setName("xor"),l_=Am($g,"&").setParameterLength(2).setName("bitAnd"),u_=Am($g,"~").setParameterLength(1).setName("bitNot"),c_=Am($g,"|").setParameterLength(2).setName("bitOr"),h_=Am($g,"^").setParameterLength(2).setName("bitXor"),d_=Am($g,"<<").setParameterLength(2).setName("shiftLeft"),p_=Am($g,">>").setParameterLength(2).setName("shiftRight"),f_=Nm(([e])=>(e.addAssign(1),e)),m_=Nm(([e])=>(e.subAssign(1),e)),g_=Nm(([e])=>{const t=Fm(e).toConst();return e.addAssign(1),t}),__=Nm(([e])=>{const t=Fm(e).toConst();return e.subAssign(1),t});qf("add",Xg),qf("sub",qg),qf("mul",Yg),qf("div",Kg),qf("mod",Zg),qf("equal",Qg),qf("notEqual",Jg),qf("lessThan",e_),qf("greaterThan",t_),qf("lessThanEqual",n_),qf("greaterThanEqual",i_),qf("and",r_),qf("or",s_),qf("not",a_),qf("xor",o_),qf("bitAnd",l_),qf("bitNot",u_),qf("bitOr",c_),qf("bitXor",h_),qf("shiftLeft",d_),qf("shiftRight",p_),qf("incrementBefore",f_),qf("decrementBefore",m_),qf("increment",g_),qf("decrement",__);class v_ extends Ff{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){if(super(),(e===v_.MAX||e===v_.MIN)&&arguments.length>3){let r=new v_(e,t,n);for(let t=3;ts&&r>a?t:s>a?n:a>r?i:t}generateNodeType(e){const t=this.method;return t===v_.LENGTH||t===v_.DISTANCE||t===v_.DOT||t===v_.DETERMINANT?"float":t===v_.CROSS?"vec3":t===v_.ALL||t===v_.ANY?"bool":t===v_.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:i}=this;let r=null;if(i===v_.ONE_MINUS)r=qg(1,t);else if(i===v_.RECIPROCAL)r=Kg(1,t);else if(i===v_.DIFFERENCE)r=X_(qg(t,n));else if(i===v_.TRANSFORM_DIRECTION){let i,s;e.isMatrix(t.getNodeType(e))?(i=t,s=n):(i=n,s=t),r=D_(Yg(i,Xm(Hm(s),0)).xyz)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let n=this.method;const i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===v_.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);{const u=[];return n===v_.CROSS?u.push(s.build(e,i),a.build(e,i)):l===It&&n===v_.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l!==It||n!==v_.MIN&&n!==v_.MAX?n===v_.REFRACT?u.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===v_.MIX?u.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===Ut&&n===v_.ATAN&&null!==a&&(n="atan2"),"fragment"===e.shaderStage||n!==v_.DFDX&&n!==v_.DFDY||(Yt(`TSL: '${n}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),n="/*"+n+"*/"),u.push(s.build(e,r)),null!==a&&u.push(a.build(e,r)),null!==o&&u.push(o.build(e,r))):u.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?e.getComponentType(r):r)),e.format(`${e.getMethod(n,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}v_.ALL="all",v_.ANY="any",v_.RADIANS="radians",v_.DEGREES="degrees",v_.EXP="exp",v_.EXP2="exp2",v_.LOG="log",v_.LOG2="log2",v_.SQRT="sqrt",v_.INVERSE_SQRT="inversesqrt",v_.FLOOR="floor",v_.CEIL="ceil",v_.NORMALIZE="normalize",v_.FRACT="fract",v_.SIN="sin",v_.SINH="sinh",v_.COS="cos",v_.COSH="cosh",v_.TAN="tan",v_.TANH="tanh",v_.ASIN="asin",v_.ASINH="asinh",v_.ACOS="acos",v_.ACOSH="acosh",v_.ATAN="atan",v_.ATANH="atanh",v_.ABS="abs",v_.SIGN="sign",v_.LENGTH="length",v_.NEGATE="negate",v_.ONE_MINUS="oneMinus",v_.DFDX="dFdx",v_.DFDY="dFdy",v_.ROUND="round",v_.RECIPROCAL="reciprocal",v_.TRUNC="trunc",v_.FWIDTH="fwidth",v_.TRANSPOSE="transpose",v_.DETERMINANT="determinant",v_.INVERSE="inverse",v_.EQUALS="equals",v_.MIN="min",v_.MAX="max",v_.STEP="step",v_.REFLECT="reflect",v_.DISTANCE="distance",v_.DIFFERENCE="difference",v_.DOT="dot",v_.CROSS="cross",v_.POW="pow",v_.TRANSFORM_DIRECTION="transformDirection",v_.MIX="mix",v_.CLAMP="clamp",v_.REFRACT="refract",v_.SMOOTHSTEP="smoothstep",v_.FACEFORWARD="faceforward";const y_=Um(1e-6),b_=Um(Math.PI),x_=Am(v_,v_.ALL).setParameterLength(1),S_=Am(v_,v_.ANY).setParameterLength(1),T_=Am(v_,v_.RADIANS).setParameterLength(1),M_=Am(v_,v_.DEGREES).setParameterLength(1),w_=Am(v_,v_.EXP).setParameterLength(1),E_=Am(v_,v_.EXP2).setParameterLength(1),A_=Am(v_,v_.LOG).setParameterLength(1),R_=Am(v_,v_.LOG2).setParameterLength(1),C_=Am(v_,v_.SQRT).setParameterLength(1),N_=Am(v_,v_.INVERSE_SQRT).setParameterLength(1),P_=Am(v_,v_.FLOOR).setParameterLength(1),L_=Am(v_,v_.CEIL).setParameterLength(1),D_=Am(v_,v_.NORMALIZE).setParameterLength(1),I_=Am(v_,v_.FRACT).setParameterLength(1),U_=Am(v_,v_.SIN).setParameterLength(1),F_=Am(v_,v_.SINH).setParameterLength(1),O_=Am(v_,v_.COS).setParameterLength(1),B_=Am(v_,v_.COSH).setParameterLength(1),k_=Am(v_,v_.TAN).setParameterLength(1),z_=Am(v_,v_.TANH).setParameterLength(1),V_=Am(v_,v_.ASIN).setParameterLength(1),G_=Am(v_,v_.ASINH).setParameterLength(1),H_=Am(v_,v_.ACOS).setParameterLength(1),W_=Am(v_,v_.ACOSH).setParameterLength(1),j_=Am(v_,v_.ATAN).setParameterLength(1,2),$_=Am(v_,v_.ATANH).setParameterLength(1),X_=Am(v_,v_.ABS).setParameterLength(1),q_=Am(v_,v_.SIGN).setParameterLength(1),Y_=Am(v_,v_.LENGTH).setParameterLength(1),K_=Am(v_,v_.NEGATE).setParameterLength(1),Z_=Am(v_,v_.ONE_MINUS).setParameterLength(1),Q_=Am(v_,v_.DFDX).setParameterLength(1),J_=Am(v_,v_.DFDY).setParameterLength(1),ev=Am(v_,v_.ROUND).setParameterLength(1),tv=Am(v_,v_.RECIPROCAL).setParameterLength(1),nv=Am(v_,v_.TRUNC).setParameterLength(1),iv=Am(v_,v_.FWIDTH).setParameterLength(1),rv=Am(v_,v_.TRANSPOSE).setParameterLength(1),sv=Am(v_,v_.DETERMINANT).setParameterLength(1),av=Am(v_,v_.INVERSE).setParameterLength(1),ov=Am(v_,v_.MIN).setParameterLength(2,1/0),lv=Am(v_,v_.MAX).setParameterLength(2,1/0),uv=Am(v_,v_.STEP).setParameterLength(2),cv=Am(v_,v_.REFLECT).setParameterLength(2),hv=Am(v_,v_.DISTANCE).setParameterLength(2),dv=Am(v_,v_.DIFFERENCE).setParameterLength(2),pv=Am(v_,v_.DOT).setParameterLength(2),fv=Am(v_,v_.CROSS).setParameterLength(2),mv=Am(v_,v_.POW).setParameterLength(2),gv=e=>Yg(e,e),_v=e=>Yg(e,e,e,e),vv=Am(v_,v_.TRANSFORM_DIRECTION).setParameterLength(2),yv=Am(v_,v_.MIX).setParameterLength(3),bv=(e,t=0,n=1)=>new v_(v_.CLAMP,xm(e),xm(t),xm(n)),xv=e=>bv(e),Sv=Am(v_,v_.REFRACT).setParameterLength(3),Tv=Am(v_,v_.SMOOTHSTEP).setParameterLength(3),Mv=Am(v_,v_.FACEFORWARD).setParameterLength(3),wv=Nm(([e])=>{const t=pv(e.xy,km(12.9898,78.233)),n=Zg(t,b_);return I_(U_(n).mul(43758.5453))});qf("all",x_),qf("any",S_),qf("radians",T_),qf("degrees",M_),qf("exp",w_),qf("exp2",E_),qf("log",A_),qf("log2",R_),qf("sqrt",C_),qf("inverseSqrt",N_),qf("floor",P_),qf("ceil",L_),qf("normalize",D_),qf("fract",I_),qf("sin",U_),qf("sinh",F_),qf("cos",O_),qf("cosh",B_),qf("tan",k_),qf("tanh",z_),qf("asin",V_),qf("asinh",G_),qf("acos",H_),qf("acosh",W_),qf("atan",j_),qf("atanh",$_),qf("abs",X_),qf("sign",q_),qf("length",Y_),qf("lengthSq",e=>pv(e,e)),qf("negate",K_),qf("oneMinus",Z_),qf("dFdx",Q_),qf("dFdy",J_),qf("round",ev),qf("reciprocal",tv),qf("trunc",nv),qf("fwidth",iv),qf("min",ov),qf("max",lv),qf("step",(e,t)=>uv(t,e)),qf("reflect",cv),qf("distance",hv),qf("dot",pv),qf("cross",fv),qf("pow",mv),qf("pow2",gv),qf("pow3",e=>Yg(e,e,e)),qf("pow4",_v),qf("transformDirection",vv),qf("transformNormalByViewMatrix",(e,t)=>D_(Yg(t,Xm(Hm(e),0)).xyz)),qf("transformNormalByInverseViewMatrix",(e,t)=>D_(Xm(Hm(e),0).mul(t).xyz)),qf("mix",(e,t,n)=>yv(t,n,e)),qf("clamp",bv),qf("refract",Sv),qf("smoothstep",(e,t,n)=>Tv(t,n,e)),qf("faceForward",Mv),qf("difference",dv),qf("saturate",xv),qf("cbrt",e=>Yg(q_(e),mv(X_(e),1/3))),qf("transpose",rv),qf("determinant",sv),qf("inverse",av),qf("rand",wv);class Ev extends Df{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,n=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const s=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=s?n:n.context({nodeBlock:n}),a.elseNode=i?s?i:i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,u=l?tg(n).build(e):"";i.nodeProperty=u;const c=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=s.build(e,n),r=a.build(e,n),o=e.getTernary(c,i,r);return e.format(o,n,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=s.build(e,n);if(h&&(l?h=u+" = "+h+";":(h="return "+h+";",null===o&&(qt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(l?t=u+" = "+t+";":(t="return "+t+";",null===o&&(qt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,n,t)}}const Av=wm(Ev).setParameterLength(2,3);qf("select",Av);class Rv extends Df{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){if(1===e.increaseUsage(this)){const t=e.addContext(this.value);this.node.build(e,this),e.setContext(t)}}setup(e){const t=e.addContext(this.value),n=this.node.build(e);return e.setContext(t),n}generate(e,t){const n=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(n),i}}const Cv=(e=null,t={})=>{let n=e;return null!==n&&!0===n.isNode||(t=n||t,n=null),new Rv(n,t)},Nv=(e,t)=>Cv(e,{nodeName:t});qf("context",Cv),qf("label",function(e,t){return qt('TSL: "label()" has been deprecated. Use "setName()" instead.'),Nv(e,t)}),qf("uniformFlow",e=>Cv(e,{uniformFlow:!0})),qf("setName",Nv),qf("builtinShadowContext",(e,t,n)=>function(e,t,n=null){return Cv(n,{getShadow:({light:n,shadowColorNode:i})=>t===n?i.mul(e):i})}(t,n,e)),qf("builtinAOContext",(e,t)=>function(e,t=null){return Cv(t,{getAO:(t,{material:n})=>!0===n.transparent?t:null!==t?t.mul(e):e})}(t,e)),qf("builtinGIContext",(e,t,n)=>function(e,t,n=null){const i=e.max(.001);return Cv(n,{getAO:(e,{material:t})=>!0===t.transparent?e:null!==e?e.mul(i):i,getGI:(e,{material:n})=>{if(!0===n.transparent)return e;const r=t.div(i);return null!==e?e.add(r):r}})}(t,n,e));class Pv extends Df{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0],n=this.getShared(t);if(this!==n)return n.build(...e);if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const n=t.getBaseStack();e?n.addToStackBefore(this):n.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:r}=e,s=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=s?i:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&Yt('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const u=e.getVectorType(l),c=t.build(e,u),h=e.getVarFromNode(this,n,u,void 0,o),d=e.getPropertyName(h);let p=d;if(o)if(s)p=a?`const ${d}`:`let ${d}`;else{const n=t.getArrayCount(e);p=`const ${e.getVar(h.type,d,n)}`}return e.addLineFlowCode(`${p} = ${c}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Lv=wm(Pv);qf("toVar",(e,t=null)=>Lv(e,t).toStack()),qf("toConst",(e,t=null)=>Lv(e,t,!0).toStack()),qf("toVarIntent",e=>Lv(e).setIntent(!0).toStack());class Dv extends Df{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const Iv=(e,t,n=null)=>new Dv(xm(e),t,n);class Uv extends Df{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Iv(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const i=this.name,r=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,i,r,s,a),t.node=Iv(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(bf,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(bf,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===n[t]){const r=this.getNodeType(e),s=e.getPropertyName(i,bf);if(e.shaderStage===bf){const t=n.node.build(e,r);e.addLineFlowCode(`${s} = ${t}`,this)}else e.flowNodeFromShaderStage(bf,n.node,r,s);n[t]=s}return e.getPropertyName(i)}}const Fv=wm(Uv).setParameterLength(1,2);qf("toVarying",Fv),qf("toVertexStage",e=>Fv(e));const Ov=Nm(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),i=e.lessThanEqual(.04045);return yv(t,n,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Bv=Nm(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),i=e.lessThanEqual(.0031308);return yv(t,n,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),kv="WorkingColorSpace";class zv extends Ff{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===kv?Sn.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==Sn.enabled&&n!==i&&n&&i?(Sn.getTransfer(n)===xt&&(r=Xm(Ov(r.rgb),r.a)),Sn.getPrimaries(n)!==Sn.getPrimaries(i)&&(r=Xm(Qm(Sn._getMatrix(new _n,n,i)).mul(r.rgb),r.a)),Sn.getTransfer(i)===xt&&(r=Xm(Bv(r.rgb),r.a)),r):r}}const Vv=(e,t)=>new zv(xm(e),t,kv);qf("workingToColorSpace",(e,t)=>new zv(xm(e),kv,t)),qf("colorSpaceToWorking",Vv);class Gv extends If{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,n,i)}}class Hv extends Df{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Mf}setGroup(e){return this.group=e,this}element(e){return new Gv(this,xm(e))}setNodeType(e){const t=zg(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;enew Wv(e,t,n);class $v extends Ff{static get type(){return"ToneMappingNode"}constructor(e,t=Xv,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return hf(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,n=this._toneMapping;if(0===n)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(n);return null!==r?i=Xm(r(t.rgb,this.exposureNode),t.a):(Yt("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const Xv=jv("toneMappingExposure","float");qf("toneMapping",(e,t,n)=>((e,t,n)=>new $v(e,xm(t),xm(n)))(t,n,e));const qv=new WeakMap;function Yv(e,t){let n=qv.get(e);return void 0===n&&(n=new xr(e,t),qv.set(e,n)),n}class Kv extends Gf{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=Pt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(0===this.bufferStride&&0===this.bufferOffset){let n=e.globalCache.getData(this.value);void 0===n&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}generateNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=e.getTypeLength(t),i=this.value,r=this.bufferStride||n,s=this.bufferOffset;let a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?Yv(i.array,r):Yv(i,r);const o=new Tr(a,n,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.context.nodeName;void 0!==n&&delete e.context.nodeName;const i=e.getBufferAttributeFromNode(this,t,n),r=e.getPropertyName(i);let s=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=r,s=r;else{let i;n&&(i=n+"Varying");s=Fv(this,i).build(e,t)}return s}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function Zv(e,t=null,n=0,i=0,r=35044,s=!1){return"mat3"===t||null===t&&9===e.itemSize?Qm(new Kv(e,"vec3",9,0).setUsage(r).setInstanced(s),new Kv(e,"vec3",9,3).setUsage(r).setInstanced(s),new Kv(e,"vec3",9,6).setUsage(r).setInstanced(s)):"mat4"===t||null===t&&16===e.itemSize?Jm(new Kv(e,"vec4",16,0).setUsage(r).setInstanced(s),new Kv(e,"vec4",16,4).setUsage(r).setInstanced(s),new Kv(e,"vec4",16,8).setUsage(r).setInstanced(s),new Kv(e,"vec4",16,12).setUsage(r).setInstanced(s)):new Kv(e,t,n,i).setUsage(r)}const Qv=(e,t=null,n=0,i=0)=>Zv(e,t,n,i),Jv=(e,t=null,n=0,i=0)=>Zv(e,t,n,i,Pt,!0),ey=(e,t=null,n=0,i=0)=>Zv(e,t,n,i,Lt,!0);qf("toAttribute",e=>Qv(e.value,e.bufferType));class ty extends Df{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===ty.VERTEX)i=e.getVertexIndex();else if(n===ty.INSTANCE)i=e.getInstanceIndex();else if(n===ty.DRAW)i=e.getDrawIndex();else if(n===ty.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===ty.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(n!==ty.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Fv(this).build(e,t)}return r}}ty.VERTEX="vertex",ty.INSTANCE="instance",ty.SUBGROUP="subgroup",ty.INVOCATION_LOCAL="invocationLocal",ty.INVOCATION_SUBGROUP="invocationSubgroup",ty.DRAW="draw";const ny=Em(ty,ty.VERTEX),iy=Em(ty,ty.INSTANCE);ty.SUBGROUP,ty.INVOCATION_SUBGROUP,ty.INVOCATION_LOCAL;const ry=Em(ty,ty.DRAW);class sy extends Df{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.onInitFunction=null,this.countNode=null,this.updateBeforeType=Sf}setName(e){return this.name=e,this}label(e){return qt('TSL: "label()" has been deprecated. Use "setName()" instead.',new of),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute!==this?this.updateBeforeType:xf}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=zg(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if("compute"===n){const t=this.computeNode.build(e,"void");if(""!==t&&e.addLineFlowCode(t,this),null!==this.count&&!0===e.allowEarlyReturns){const t=this.countNode.build(e,"uint"),n=iy.build(e,"uint");e.flow.code=`${e.tab}if ( ${n} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}const ay=(e,t=[64])=>{(0===t.length||t.length>3)&&Yt("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new of);for(let e=0;e{const i=ay(e,n);return"number"==typeof t?i.count=t:i.dispatchSize=t,i}),qf("computeKernel",ay);class oy extends Df{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const ly=e=>new oy(xm(e));qf("cache",function(e,t=!0){return qt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),ly(e).setParent(t)}),qf("isolate",ly);class uy extends Df{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}qf("bypass",wm(uy).setParameterLength(2));const cy=Nm(([e,t,n,i=Um(0),r=Um(1),s=Bm(!1)])=>{let a=e.sub(t).div(n.sub(t));return ym(s)&&(a=a.clamp()),a.mul(r.sub(i)).add(i)});qf("remap",cy),qf("remapClamp",function(e,t,n,i=Um(0),r=Um(1)){return cy(e,t,n,i,r,!0)});class hy extends Df{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(i,n,t);e.addLineFlowCode(i,this)}}const dy=wm(hy).setParameterLength(1,2);qf("discard",e=>(e?Av(e,dy("discard")):dy("discard")).toStack());const py=Nm(([e])=>Xm(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),fy=Nm(([e])=>e.a.equal(0).select(Xm(0),Xm(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class my extends Ff{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;t=Xm(t.rgb,t.a.clamp(0,1)),t=fy(t);const n=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||_t;return 0!==n&&(t=t.toneMapping(n)),i!==_t&&i!==Sn.workingColorSpace&&(t=t.workingToColorSpace(i)),t=py(t),t}}const gy=(e,t=null,n=null)=>new my(xm(e),t,n);qf("renderOutput",gy);class _y extends Ff{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e);if(null!==t)t(e,n);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+n+" /* ... */\n",r+="// #"+i+"#\n",$t(r)}return n}}qf("debug",(e,t=null)=>new _y(xm(e),t).toStack());class vy extends Jt{constructor(){super(),this._renderer=null,this.currentFrame=null,this.isRunning=!1,this.enabled=!0}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}begin(){this.isRunning=!0}finish(){this.isRunning=!1}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}dispose(){!0===this.isRunning&&this.finish(),this.dispatchEvent({type:"dispose"})}}class yy extends Df{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=Sf,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==vy&&Kt('TSL: ".toInspector()" is only available with WebGPU.'),t}}qf("toInspector",function(e,t="",n=null){return(e=xm(e)).before(new yy(e,t,n))});class by extends Df{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);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),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,n);return Fv(this).build(e,n)}return qt(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}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 xy=(e,t=null)=>new by(e,t),Sy=(e=0)=>xy("uv"+(e>0?e:""),"vec2");class Ty extends Df{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e){const t=this.textureNode.build(e,"property"),n=null===this.levelNode?"0":this.levelNode.build(e,"int"),i=e.generateTextureSize(this.textureNode.value,t,n);return e.format(i,this.getNodeType(e))}}const My=wm(Ty).setParameterLength(1,2);class wy extends kg{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Sf}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Ey=wm(wy).setParameterLength(1);class Ay extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Ry=new Ln;class Cy extends kg{static get type(){return"TextureNode"}constructor(e=Ry,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=xf,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this._samplerComparison=!1,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return null!==this.gatherNode?"vec4":gf(this.value)}getInputType(){return"texture"}getDefaultUV(){return Sy(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=zg(this.value.matrix)),this._matrixUniform.mul(Hm(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=zg(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(Fm(My(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Ay("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=Nm(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?Mf:xf,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let s=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(Bt))s=this.compareNode;else{const e=n.compareFunction;null===e||e===Mt||e===Et||e===At||e===Ct?a=this.compareNode:(s=this.compareNode,Kt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=s,t.compareStepNode=a,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,i,r,s,a,o,l,u,c){const h=this.value;let d;return d=r?e.generateTextureBias(h,t,n,r,s,u):o?e.generateTextureGrad(h,t,n,o,s,u):l?a?e.generateTextureGatherCompare(h,t,n,a,s,u,c):e.generateTextureGather(h,t,n,l,s,u,c):a?e.generateTextureCompare(h,t,n,a,s,u):!1===this.sampler?e.generateTextureLoad(h,t,n,i,s,u):i?e.generateTextureLevel(h,t,n,i,s,u):e.generateTexture(h,t,n,s,u),d}generate(e,t){const n=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t)){if("samplerComparison"===t){this._samplerComparison=!0;this.getSharedNode(e)._samplerComparison=!0}return r+"_sampler"}if(e.isReference(t))return r;{const s=e.getDataFromNode(this),a=this.getNodeType(e);let o=s.propertyName;if(void 0===o){const{uvNode:t,levelNode:l,biasNode:u,compareNode:c,compareStepNode:h,depthNode:d,gradNode:p,gatherNode:f,offsetNode:m}=i,g=this.generateUV(e,t),_=l?l.build(e,"float"):null,v=u?u.build(e,"float"):null,y=d?d.build(e,"int"):null,b=c?c.build(e,"float"):null,x=h?h.build(e,"float"):null,S=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=f?f.build(e,"int"):null,M=m?this.generateOffset(e,m):null,w=this._flipYUniform?this._flipYUniform.build(e,"bool"):null;let E=y;null===E&&n.isArrayTexture&&!0!==this.isTexture3DNode&&(E="0");const A=e.getVarFromNode(this);o=e.getPropertyName(A);let R,C=this.generateSnippet(e,r,g,_,v,E,b,S,T,M,w);if(R=!0===n.isDepthTexture&&null===T?"float":n.type===ge?"uvec4":n.type===me?"ivec4":"vec4",C=e.format(C,R,a),null!==x){const t=n.compareFunction;C=t===At||t===Ct?uv(dy(C,a),dy(x,"float")).build(e,a):uv(dy(x,"float"),dy(C,a)).build(e,a)}e.addLineFlowCode(`${o} = ${C}`,this),s.snippet=C,s.propertyName=o}let l=o;return e.needsToWorkingColorSpace(n)&&(l=Vv(dy(l,a),n.colorSpace).setup(e).build(e,a)),e.format(l,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=xm(e),t.referenceNode=this.getBase(),xm(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=xm(e).mul(Ey(t)),t.referenceNode=this.getBase();const n=t.value;return!1===t.generateMipmaps&&(n&&!1===n.generateMipmaps||n.minFilter===se||n.magFilter===se)&&(qt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),xm(t)}level(e){const t=this.clone();return t.levelNode=xm(e),t.referenceNode=this.getBase(),xm(t)}size(e){return My(this,e)}bias(e){const t=this.clone();return t.biasNode=xm(e),t.referenceNode=this.getBase(),xm(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=xm(e),t.referenceNode=this.getBase(),xm(t)}grad(e,t){const n=this.clone();return n.gradNode=[xm(e),xm(t)],n.referenceNode=this.getBase(),xm(n)}gather(e=0){const t=this.clone();return t.gatherNode=xm(e),t.referenceNode=this.getBase(),xm(t)}isSampleCompare(){return null!==this.compareNode||!0===this._samplerComparison}depth(e){const t=this.clone();return t.depthNode=xm(e),t.referenceNode=this.getBase(),xm(t)}offset(e){const t=this.clone();return t.offsetNode=xm(e),t.referenceNode=this.getBase(),xm(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const n=this._flipYUniform;null!==n&&(n.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}}const Ny=wm(Cy).setParameterLength(1,4).setName("texture"),Py=(e=Ry,t=null,n=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=xm(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=xm(t)),null!==n&&(r.levelNode=xm(n)),null!==i&&(r.biasNode=xm(i))):r=Ny(e,t,n,i),r},Ly=(...e)=>Py(...e).setSampler(!1);class Dy extends kg{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Iy=(e,t,n)=>new Dy(e,t,n);class Uy extends If{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,n)}}class Fy extends Dy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?mf(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Tf,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){this.updateBuffer()}onUpdate(e,t){return e=e.bind(this),super.onUpdate((t,n)=>{e(t,n),this.updateBuffer()},t)}updateBuffer(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;nnew Fy(e,t);class By extends Df{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const ky=wm(By).setParameterLength(1);let zy,Vy;class Gy extends Df{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}generateNodeType(){return this.scope===Gy.VIEWPORT?"vec4":"vec2"}update({renderer:e}){const t=e.getRenderTarget();this.scope===Gy.VIEWPORT?null!==t?Vy.copy(t.viewport):(e.getViewport(Vy),Vy.multiplyScalar(e.getPixelRatio())):null!==t?(zy.width=t.width,zy.height=t.height):e.getDrawingBufferSize(zy)}setup(){const e=this.scope;let t=null;t=e===Gy.SIZE?zg(zy||(zy=new dn)).setGroup(Og):e===Gy.VIEWPORT?zg(Vy||(Vy=new Dn)).setGroup(Og):km($y.div(jy));let n=xf;return this.scope!==Gy.SIZE&&this.scope!==Gy.VIEWPORT||(n=Tf),this.updateType=n,t}generate(e){if(this.scope===Gy.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(jy).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Gy.COORDINATE="coordinate",Gy.VIEWPORT="viewport",Gy.SIZE="size",Gy.UV="uv";const Hy=zg(1).setGroup(Og).onRenderUpdate(({renderer:e})=>e.getPixelRatio()),Wy=Em(Gy,Gy.UV),jy=Em(Gy,Gy.SIZE),$y=Em(Gy,Gy.COORDINATE),Xy=Em(Gy,Gy.VIEWPORT),qy=Xy.zw;Xy.xy;let Yy=null,Ky=null,Zy=null,Qy=null,Jy=null,eb=null,tb=null,nb=null,ib=null,rb=null,sb=null,ab=null;const ob=zg(0,"uint").setName("u_cameraIndex").setGroup(Fg("cameraIndex")).toVarying("v_cameraIndex"),lb=zg("float").setName("cameraNear").setGroup(Og).onRenderUpdate(({camera:e})=>e.near),ub=zg("float").setName("cameraFar").setGroup(Og).onRenderUpdate(({camera:e})=>e.far),cb=Nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);null===Ky?Ky=Oy(n).setGroup(Og).setName("cameraProjectionMatrices"):Ky.array=n,t=Ky.element(e.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else null===Yy&&(Yy=zg(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(Og).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=Yy;return t}).once()(),hb=Nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrixInverse);null===Qy?Qy=Oy(n).setGroup(Og).setName("cameraProjectionMatricesInverse"):Qy.array=n,t=Qy.element(e.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else null===Zy&&(Zy=zg(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(Og).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=Zy;return t}).once()(),db=Nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);null===eb?eb=Oy(n).setGroup(Og).setName("cameraViewMatrices"):eb.array=n,t=eb.element(e.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else null===Jy&&(Jy=zg(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(Og).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=Jy;return t}).once()(),pb=Nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorld);null===nb?nb=Oy(n).setGroup(Og).setName("cameraWorldMatrices"):nb.array=n,t=nb.element(e.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else null===tb&&(tb=zg(e.matrixWorld).setName("cameraWorldMatrix").setGroup(Og).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=tb;return t}).once()(),fb=Nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(let t=0,i=e.cameras.length;t{const n=e.cameras,i=t.array;for(let e=0,t=n.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=ib;return t}).once()(),mb=Nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.viewport);null===ab?ab=Oy(n,"vec4").setGroup(Og).setName("cameraViewports"):ab.array=n,t=ab.element(ob)}else null===sb&&(sb=Xm(0,0,jy.x,jy.y).toConst("cameraViewport")),t=sb;return t}).once()(),gb=new dr;class _b extends Df{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Mf,this.uniformNode=new kg(null)}generateNodeType(){const e=this.scope;return e===_b.WORLD_MATRIX?"mat4":e===_b.POSITION||e===_b.VIEW_POSITION||e===_b.DIRECTION||e===_b.SCALE?"vec3":e===_b.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this.uniformNode,i=this.scope;if(i===_b.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===_b.POSITION)n.value=n.value||new fn,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===_b.SCALE)n.value=n.value||new fn,n.value.setFromMatrixScale(t.matrixWorld);else if(i===_b.DIRECTION)n.value=n.value||new fn,t.getWorldDirection(n.value);else if(i===_b.VIEW_POSITION){const i=e.camera;n.value=n.value||new fn,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}else if(i===_b.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),gb.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),n.value=gb.radius}}generate(e){const t=this.scope;return t===_b.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===_b.POSITION||t===_b.VIEW_POSITION||t===_b.DIRECTION||t===_b.SCALE?this.uniformNode.nodeType="vec3":t===_b.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}_b.WORLD_MATRIX="worldMatrix",_b.POSITION="position",_b.SCALE="scale",_b.VIEW_POSITION="viewPosition",_b.DIRECTION="direction",_b.RADIUS="radius";const vb=new Bn;class yb extends _b{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const bb=Em(yb,yb.WORLD_MATRIX),xb=zg(new _n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Sb=Nm(e=>e.context.modelViewMatrix||Tb).once()().toVar("modelViewMatrix"),Tb=db.mul(bb),Mb=Nm(e=>{e.context.isHighPrecisionModelViewMatrix=!0;const t=e.camera;let n;if(t.isArrayCamera&&t.cameras.length>0){const e=[];for(let n=0;n{const i=t.cameras,r=n.array;for(let t=0,n=i.length;te.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld));return n}).once()().toVar("highpModelViewMatrix"),wb=Nm(e=>{const t=e.context.isHighPrecisionModelViewMatrix,n=e.camera;let i;if(n.isArrayCamera&&n.cameras.length>0){const e=[];for(let t=0;t{const i=t.cameras,r=n.array;for(let t=0,n=i.length;t(!0!==t&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)));return i}).once()().toVar("highpModelNormalViewMatrix"),Eb=Nm(e=>"fragment"!==e.shaderStage?(Kt("TSL: `clipSpace` is only available in fragment stage."),Xm()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Ab=xy("position","vec3"),Rb=Ab.toVarying("positionLocal"),Cb=Ab.toVarying("positionPrevious"),Nb=Nm(e=>bb.mul(Rb).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Pb=Nm(()=>Rb.transformDirection(bb).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Lb=Nm(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=hb.mul(Eb);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Db=Nm(e=>{let t;return t=e.camera.isOrthographicCamera?Hm(0,0,1):Lb.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Ib extends Df{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const Ub=Um(Em(Ib)).mul(2).sub(1),Fb=Nm(([e],{material:t})=>{const n=t.side;return 1===n?e=e.mul(-1):2===n&&(e=e.mul(Ub)),e}),Ob=xy("normal","vec3"),Bb=Nm(e=>!1===e.geometry.hasAttribute("normal")?(qt('TSL: Vertex attribute "normal" not found on geometry.'),Hm(0,1,0)):Ob,"vec3").once()().toVar("normalLocal"),kb=Lb.dFdx().cross(Lb.dFdy()).normalize().toVar("normalFlat"),zb=Nm(e=>{let t;return t=e.isFlatShading()?kb:$b(Bb).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Vb=Nm(e=>{let t=zb.transformNormalByInverseViewMatrix(db);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Gb=Nm(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=zb,!0!==e.isFlatShading()&&(t=Fb(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Hb=Gb.transformNormalByInverseViewMatrix(db).toVar("normalWorld"),Wb=Nm(({subBuildFn:e,context:t})=>{let n;return n="NORMAL"===e||"VERTEX"===e?Gb:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),jb=Nm(([e,t=bb])=>Qm(t).inverse().transpose().mul(e).normalize());qf("transformNormal",jb);const $b=Nm(([e],t)=>{const n=t.context.modelNormalViewMatrix;if(n)return e.transformNormalByViewMatrix(n);return xb.mul(e).transformNormalByViewMatrix(db)});Nm(()=>(qt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Gb)).once(["NORMAL","VERTEX"])(),Nm(()=>(qt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Hb)).once(["NORMAL","VERTEX"])(),Nm(()=>(qt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Wb)).once(["NORMAL","VERTEX"])();const Xb=new Bn,qb=zg(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Yb=zg(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Kb=zg(new Bn).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const n=(null!==t.environment||t.environmentNode&&t.environmentNode.isNode)&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?Xb.makeRotationFromEuler(n).transpose():Xb.identity(),Xb}),Zb=Db.negate().reflect(Gb),Qb=Db.negate().refract(Gb,qb),Jb=Zb.transformDirection(pb).toVar("reflectVector"),ex=Qb.transformDirection(pb).toVar("refractVector"),tx=new ms;class nx extends Cy{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===Z?Jb:e.mapping===Q?ex:(Yt('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Hm(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return!0===n.isDepthTexture?e.renderer.coordinateSystem===Ut?Hm(t.x,t.y.negate(),t.z):t:(t=Kb.mul(t),e.renderer.coordinateSystem!==Ut&&n.isRenderTargetTexture||(t=Hm(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const ix=wm(nx).setParameterLength(1,4).setName("cubeTexture"),rx=(e=tx,t=null,n=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=xm(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=xm(t)),null!==n&&(r.levelNode=xm(n)),null!==i&&(r.biasNode=xm(i))):r=ix(e,t,n,i),r};class sx extends Df{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Mf}element(e){return new Gv(this,xm(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return qt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;null!==this.count?t=Iy(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=Oy(null,e),t.updateType=Mf):t="texture"===e?Py(null):"cubeTexture"===e?rx(null):zg(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;enew sx(e,t,n);class ox extends sx{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const lx=(e,t,n=null)=>new ox(e,t,n),ux=Sy(),cx=Lb.dFdx(),hx=Lb.dFdy(),dx=ux.dFdx(),px=ux.dFdy(),fx=Gb,mx=hx.cross(fx),gx=fx.cross(cx),_x=mx.mul(dx.x).add(gx.mul(px.x)),vx=mx.mul(dx.y).add(gx.mul(px.y)),yx=_x.dot(_x).max(vx.dot(vx)),bx=yx.equal(0).select(0,yx.inverseSqrt()),xx=_x.mul(bx).toVar("tangentViewFrame"),Sx=vx.mul(bx).toVar("bitangentViewFrame"),Tx=xy("tangent","vec4"),Mx=Tx.xyz.toVar("tangentLocal"),wx=Nm(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Sb.mul(Xm(Mx,0)).xyz.toVarying("v_tangentView").normalize():xx,!0!==e.isFlatShading()&&(t=Fb(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Ex=Nm(([e,t],n)=>{let i=e.mul(Tx.w).xyz;return"NORMAL"===n.subBuildFn&&!0!==n.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),Ax=Qm(wx,Nm(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Ex(Gb.cross(wx),"v_bitangentView").normalize():Sx,!0!==e.isFlatShading()&&(t=Fb(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Gb).toVar("TBNViewMatrix"),Rx=Nm(()=>{let e=vg.cross(Db);return e=e.cross(vg).normalize(),e=yv(e,Gb,gg.mul(ag.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Cx=e=>Hm(e,C_(xv(Um(1).sub(pv(e,e)))));class Nx extends Ff{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:n,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=Cx(r.xy):"ga"===i?r=Cx(r.yw):""!==i&&Yt(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&Yt(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==n){let t=n;!0===e.isFlatShading()&&(t=Fb(t)),r=Hm(r.xy.mul(t),r.z)}let s=null;return 1===t?s=$b(r):0===t?s=Ax.mul(r).normalize():(Yt(`NodeMaterial: Unsupported normal map type: ${t}`),s=Gb),s}}const Px=wm(Nx).setParameterLength(1,2),Lx=Nm(({textureNode:e,bumpScale:t})=>{const n=t=>e.isolate().context({getUV:e=>t(e.uvNode||Sy()),forceUVContext:!0}),i=Um(n(e=>e));return km(Um(n(e=>e.add(e.dFdx()))).sub(i),Um(n(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),Dx=Nm(e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(Ub),u=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(u).normalize()});class Ix extends Ff{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(e){if(!0===e.material.wireframe)return Gb;const t=null!==this.scaleNode?this.scaleNode:1,n=Lx({textureNode:this.textureNode,bumpScale:t});return Dx({surf_pos:Lb,surf_norm:Gb,dHdxy:n})}}const Ux=wm(Ix).setParameterLength(1,2),Fx=new Map;class Ox extends Df{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=Fx.get(e);return void 0===n&&(n=lx(e,t),Fx.set(e,n)),n}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,n=this.scope;let i=null;if(n===Ox.COLOR){const e=void 0!==t.color?this.getColor(n):Hm();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===Ox.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===Ox.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Um(1);else if(n===Ox.SPECULAR_INTENSITY){const e=this.getFloat(n);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===Ox.SPECULAR_COLOR){const e=this.getColor(n);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===Ox.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===Ox.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===Ox.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(n).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(n)):r}else if(n===Ox.NORMAL)t.normalMap?(i=Px(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=Pe&&t.normalMap.format!=mt&&t.normalMap.format!=qe||(i.unpackNormalMode="rg")):i=t.bumpMap?Ux(this.getTexture("bump").r,this.getFloat("bumpScale")):Gb;else if(n===Ox.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Ox.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Ox.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Px(this.getTexture(n),this.getCache(n+"Scale","vec2")):Gb;else if(n===Ox.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(n===Ox.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(1e-4,1)}else if(n===Ox.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);i=Zm(SS.x,SS.y,SS.y.negate(),SS.x).mul(e.rg.mul(2).sub(km(1)).normalize().mul(e.b))}else i=SS;else if(n===Ox.IRIDESCENCE_THICKNESS){const e=ax("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=ax("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else if(n===Ox.TRANSMISSION){const e=this.getFloat(n);i=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===Ox.THICKNESS){const e=this.getFloat(n);i=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===Ox.IOR)i=this.getFloat(n);else if(n===Ox.LIGHT_MAP)i=t.lightMap?this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity")):Hm(0);else if(n===Ox.AO)i=t.aoMap?this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):Um(1);else if(n===Ox.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(n):Um(0);else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}Ox.ALPHA_TEST="alphaTest",Ox.COLOR="color",Ox.OPACITY="opacity",Ox.SHININESS="shininess",Ox.SPECULAR="specular",Ox.SPECULAR_STRENGTH="specularStrength",Ox.SPECULAR_INTENSITY="specularIntensity",Ox.SPECULAR_COLOR="specularColor",Ox.REFLECTIVITY="reflectivity",Ox.ROUGHNESS="roughness",Ox.METALNESS="metalness",Ox.NORMAL="normal",Ox.CLEARCOAT="clearcoat",Ox.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Ox.CLEARCOAT_NORMAL="clearcoatNormal",Ox.EMISSIVE="emissive",Ox.ROTATION="rotation",Ox.SHEEN="sheen",Ox.SHEEN_ROUGHNESS="sheenRoughness",Ox.ANISOTROPY="anisotropy",Ox.IRIDESCENCE="iridescence",Ox.IRIDESCENCE_IOR="iridescenceIOR",Ox.IRIDESCENCE_THICKNESS="iridescenceThickness",Ox.IOR="ior",Ox.TRANSMISSION="transmission",Ox.THICKNESS="thickness",Ox.ATTENUATION_DISTANCE="attenuationDistance",Ox.ATTENUATION_COLOR="attenuationColor",Ox.LINE_SCALE="scale",Ox.LINE_DASH_SIZE="dashSize",Ox.LINE_GAP_SIZE="gapSize",Ox.LINE_WIDTH="linewidth",Ox.LINE_DASH_OFFSET="dashOffset",Ox.POINT_SIZE="size",Ox.DISPERSION="dispersion",Ox.RETROREFLECTIVITY="retroreflectivity",Ox.LIGHT_MAP="light",Ox.AO="ao";const Bx=Em(Ox,Ox.ALPHA_TEST),kx=Em(Ox,Ox.COLOR),zx=Em(Ox,Ox.SHININESS),Vx=Em(Ox,Ox.EMISSIVE),Gx=Em(Ox,Ox.OPACITY),Hx=Em(Ox,Ox.SPECULAR),Wx=Em(Ox,Ox.SPECULAR_INTENSITY),jx=Em(Ox,Ox.SPECULAR_COLOR),$x=Em(Ox,Ox.SPECULAR_STRENGTH),Xx=Em(Ox,Ox.REFLECTIVITY),qx=Em(Ox,Ox.ROUGHNESS),Yx=Em(Ox,Ox.METALNESS),Kx=Em(Ox,Ox.NORMAL),Zx=Em(Ox,Ox.CLEARCOAT),Qx=Em(Ox,Ox.CLEARCOAT_ROUGHNESS),Jx=Em(Ox,Ox.CLEARCOAT_NORMAL),eS=Em(Ox,Ox.ROTATION),tS=Em(Ox,Ox.SHEEN),nS=Em(Ox,Ox.SHEEN_ROUGHNESS),iS=Em(Ox,Ox.ANISOTROPY),rS=Em(Ox,Ox.IRIDESCENCE),sS=Em(Ox,Ox.IRIDESCENCE_IOR),aS=Em(Ox,Ox.IRIDESCENCE_THICKNESS),oS=Em(Ox,Ox.TRANSMISSION),lS=Em(Ox,Ox.THICKNESS),uS=Em(Ox,Ox.IOR),cS=Em(Ox,Ox.ATTENUATION_DISTANCE),hS=Em(Ox,Ox.ATTENUATION_COLOR),dS=Em(Ox,Ox.LINE_SCALE),pS=Em(Ox,Ox.LINE_DASH_SIZE),fS=Em(Ox,Ox.LINE_GAP_SIZE),mS=Em(Ox,Ox.LINE_WIDTH),gS=Em(Ox,Ox.LINE_DASH_OFFSET),_S=Em(Ox,Ox.POINT_SIZE),vS=Em(Ox,Ox.DISPERSION),yS=Em(Ox,Ox.RETROREFLECTIVITY),bS=Em(Ox,Ox.LIGHT_MAP),xS=Em(Ox,Ox.AO),SS=zg(new dn).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))}),TS=Nm(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class MS extends Df{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===MS.OBJECT?this.updateType=Mf:e===MS.MATERIAL?this.updateType=Tf:e===MS.FRAME?this.updateType=Sf:e===MS.AFTER_OBJECT?this.updateAfterType=Mf:e===MS.BEFORE_OBJECT?this.updateBeforeType=Mf:e===MS.BEFORE_MATERIAL?this.updateBeforeType=Tf:e===MS.BEFORE_FRAME&&(this.updateBeforeType=Sf)}setup(e){const{eventType:t,callback:n}=this;if(t===MS.BEFORE_RENDER_PIPELINE){const t=e.context.onBeforePipelineCallbacks;t&&t.push(n)}else if(t===MS.AFTER_RENDER_PIPELINE){const t=e.context.onAfterPipelineCallbacks;t&&t.push(n)}return super.setup(e)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}updateAfter(e){this.callback(e)}}MS.OBJECT="object",MS.MATERIAL="material",MS.FRAME="frame",MS.AFTER_OBJECT="afterObject",MS.BEFORE_OBJECT="beforeObject",MS.BEFORE_MATERIAL="beforeMaterial",MS.BEFORE_FRAME="beforeFrame",MS.BEFORE_RENDER_PIPELINE="beforeRenderPipeline",MS.AFTER_RENDER_PIPELINE="afterRenderPipeline";const wS=(e,t)=>new MS(e,t).toStack(),ES=e=>wS(MS.OBJECT,e),AS=e=>wS(MS.AFTER_OBJECT,e);class RS extends If{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const i=e.isContextAssign();if(n=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);n=e.format(n,i,t)}return n}}const CS=wm(RS).setParameterLength(2);class NS extends Dy{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let i,r=null;t&&t.isStructTypeNode?(i="struct",r=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=ff(e.itemSize),n=e.count):i=t,super(e,i,n),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=Af,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(0===this.bufferCount){let n=e.globalCache.getData(this.value);void 0===n&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return CS(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(wf)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=Qv(this.value),this._varying=Fv(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),i=n.build(e);return e.registerTransform(i,t),i}}const PS=(e,t=null,n=0)=>new NS(e,t,n),LS=new WeakMap,DS=new WeakMap,IS=new WeakMap;function US(e,t){let n;const i=Math.max(t.count,1);if(!0===t.isStorageInstancedBufferAttribute)n=PS(t,"mat4",i).element(iy);else{if(16*i*4<=e.getUniformBufferLimit())n=Iy(t.array,"mat4",i).element(iy);else{let e=LS.get(t);e||(e=new za(t.array,16,1),LS.set(t,e));const i=t.usage===Lt?ey:Jv,r=[i(e,"vec4",16,0),i(e,"vec4",16,4),i(e,"vec4",16,8),i(e,"vec4",16,12)];n=Jm(...r)}}return n}const FS=ng("vec3","vInstanceColor"),OS=Nm(([e,t=null],n)=>{const i=!0===e.isStorageInstancedBufferAttribute,r=t&&!0===t.isStorageInstancedBufferAttribute,s=US(n,e);let a=null;if(!i){16*Math.max(e.count,1)*4>n.getUniformBufferLimit()&&(a=LS.get(e))}let o=null,l=null;if(t)if(r)o=PS(t,"vec3",Math.max(t.count,1)).element(iy);else{let e=DS.get(t);e||(e=new Zr(t.array,3),DS.set(t,e)),l=e;const n=t.usage===Lt?ey:Jv;o=Hm(n(e,"vec3",3,0))}var u;null===a&&null===l||(u=()=>{null!==a&&a.version!==e.version&&(a.clearUpdateRanges(),a.updateRanges.push(...e.updateRanges),e.clearUpdateRanges(),a.version=e.version),t&&null!==l&&l.version!==t.version&&(l.clearUpdateRanges(),l.updateRanges.push(...t.updateRanges),t.clearUpdateRanges(),l.version=t.version)},wS(MS.BEFORE_FRAME,u));const c=s.mul(Rb).xyz;if(Rb.assign(c),n.needsPreviousData()){const t=n.object;AS(({object:t})=>{const{previousInstanceMatrix:n}=IS.get(t);n.array.set(e.array),n.version=e.version;const i=LS.get(n);void 0!==i&&(i.version=e.version)});const i=function(e,t,n){let i=IS.get(e);if(void 0===i){const r=t.clone();i={previousInstanceMatrix:r,node:US(n,r)},IS.set(e,i)}return i.node}(t,e,n);Cb.assign(i.mul(Cb).xyz)}if(n.hasGeometryAttribute("normal")){const e=jb(Bb,s);Bb.assign(e)}null!==o&&FS.assign(o)},"void"),BS=Nm(([e])=>{const{instanceMatrix:t,instanceColor:n}=e;OS(t,n)},"void"),kS=new WeakMap,zS=Nm(([e,t])=>{const n=Fm(My(Ly(e),0).x).toConst(),i=Fm(t),r=i.mod(n).toConst(),s=i.div(n).toConst();return Ly(e,zm(r,s))}),VS=Nm(([e,t])=>{const n=Fm(My(Ly(e),0).x).toConst(),i=Fm(t).mod(n).toConst(),r=Fm(t).div(n).toConst();return Ly(e,zm(i,r)).x});function GS(e,t){const n=Fm(My(Ly(e),0).x).toConst(),i=Um(t).mul(4).toInt().toConst(),r=i.mod(n).toConst(),s=i.div(n).toConst();return Jm(Ly(e,zm(r,s)),Ly(e,zm(r.add(1),s)),Ly(e,zm(r.add(2),s)),Ly(e,zm(r.add(3),s)))}const HS=ng("vec4","vBatchColor"),WS=ng("uint","vBatchIndirectId"),jS=Nm(([e],t)=>{const n=null===t.getDrawIndex()?iy:ry,i=VS(e._indirectTexture,Fm(n));WS.assign(i);const r=GS(e._matricesTexture,i),s=e._colorsTexture;if(null!==s){const e=zS(s,i);HS.assign(e)}const a=Qm(r);if(Rb.assign(r.mul(Rb)),t.needsPreviousData()){AS(({object:e})=>{const t=kS.get(e);t.previousMatricesTexture.image.data.set(e._matricesTexture.image.data),t.previousMatricesTexture.needsUpdate=!0});const t=function(e,t){let n=kS.get(e);if(void 0===n){const{image:i,format:r,type:s}=e._matricesTexture,a=new Kr(i.data.slice(),i.width,i.height,r,s);n={previousMatricesTexture:a,node:GS(a,t)},kS.set(e,n)}return n.node}(e,i);Cb.assign(t.mul(Cb).xyz)}const o=Bb.div(Hm(a[0].dot(a[0]),a[1].dot(a[1]),a[2].dot(a[2]))),l=a.mul(o).xyz;Bb.assign(l),t.hasGeometryAttribute("tangent")&&Mx.mulAssign(a)},"void"),$S=new WeakMap,XS=new WeakMap;function qS(e){return{element:t=>{const n=Fm(My(e).x).toConst(),i=Fm(t).mul(4).toConst(),r=i.div(n).toConst(),s=i.sub(r.mul(n)).toConst();return Jm(e.load(zm(s,r)),e.load(zm(s.add(1),r)),e.load(zm(s.add(2),r)),e.load(zm(s.add(3),r)))}}}function YS(e,t){let n;if(16*t.bones.length*4<=e.getUniformBufferLimit())i="skeleton.boneMatrices",r="mat4",s=t.bones.length,n=new sx(i,r,a,s);else{null===t.boneTexture&&t.computeBoneTexture();const e=Py(t.boneTexture);ES(({object:t})=>{const n=t.skeleton;null===n.boneTexture&&n.computeBoneTexture(),e.value=n.boneTexture}),n=qS(e)}var i,r,s,a;return n}function KS(e,t,n,i,r,s){const a=e.element(r.x),o=e.element(r.y),l=e.element(r.z),u=e.element(r.w),c=n.mul(t),h=Xg(a.mul(s.x).mul(c),o.mul(s.y).mul(c),l.mul(s.z).mul(c),u.mul(s.w).mul(c));return i.mul(h).xyz}const ZS=Nm(([e],t)=>{const n=xy("skinIndex","uvec4"),i=xy("skinWeight","vec4"),r=ax("bindMatrix","mat4"),s=ax("bindMatrixInverse","mat4"),a=YS(t,e.skeleton);if(ES(({object:e,frameId:t})=>{const n=e.skeleton;if($S.get(n)!==t){$S.set(n,t);const e=XS.get(n);void 0!==e&&(e.previousBoneMatrices.set(n.boneMatrices),null!==e.previousBoneTexture&&(e.previousBoneTexture.needsUpdate=!0)),n.update()}}),t.needsPreviousData()){const a=function(e,t,n,i,r,s){const a=t.skeleton;let o=XS.get(a);if(void 0===o){if(a.update(),16*a.bones.length*4<=e.getUniformBufferLimit()){const e=new Float32Array(a.boneMatrices);o={previousBoneMatrices:e,previousBoneTexture:null,node:Iy(e,"mat4",a.bones.length)}}else{null===a.boneTexture&&a.computeBoneTexture();const{width:e,height:t}=a.boneTexture.image,n=new Float32Array(a.boneMatrices),i=new Kr(n,e,t,Ee,_e);i.needsUpdate=!0,o={previousBoneMatrices:n,previousBoneTexture:i,node:qS(Py(i))}}XS.set(a,o)}return KS(o.node,Cb,n,i,r,s)}(t,e,r,s,n,i);Cb.assign(a)}const o=KS(a,Rb,r,s,n,i);if(Rb.assign(o),t.hasGeometryAttribute("normal")){const{skinNormal:e,skinTangent:o}=function(e,t,n,i,r,s,a){const o=e.element(s.x),l=e.element(s.y),u=e.element(s.z),c=e.element(s.w);let h=Xg(a.x.mul(o),a.y.mul(l),a.z.mul(u),a.w.mul(c));h=r.mul(h).mul(i);const d=Qm(h);return{skinNormal:d.mul(t),skinTangent:d.mul(n)}}(a,Bb,Mx,r,s,n,i);Bb.assign(e),t.hasGeometryAttribute("tangent")&&Mx.assign(o)}},"void");class QS extends Df{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={},i=this._getInternalParams();for(let e=0,t=i.length-1;eNumber(l)?">=":"<")),a)s=`while ( ${l} )`;else{const n={start:o,end:l},i=n.start,r=n.end;let a;const p=()=>h.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=u+" "+p()+" "+e.generateConst(c,d);break;case"string":a=u+" "+d;break;default:d.isNode?a=u+" "+p()+" "+d.build(e):(Yt("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===c||"uint"===c?h.includes("<")?"++":"--":p()+" 1.",a=u+" "+d;s=`for ( ${e.getVar(c,u)+" = "+i}; ${u+" "+h+" "+r}; ${a} )`}e.addFlowCode((0===i?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,i=n.length-1;tnew QS(Mm(e,"int")).toStack(),eT=new WeakMap,tT=new Dn,nT=new WeakMap,iT=Nm(({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=Fm(ny).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return Ly(e,zm(l,o)).depth(r).xyz.mul(t)});const rT=Nm(([e])=>{const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0;if(0===s)return;let a=nT.get(e);void 0!==a&&a.count===s||(a={base:zg(1),influences:e.morphTargetInfluences?Oy(e.morphTargetInfluences,"float"):null,count:s},nT.set(e,a));const{base:o,influences:l}=a,{texture:u,stride:c,size:h}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=eT.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new Fn(f,h,d,s);m.type=_e,m.needsUpdate=!0;const g=4*c;for(let v=0;v{const r=Um(0).toVar();e.count>1&&null!==e.morphTexture&&void 0!==e.morphTexture?r.assign(Ly(e.morphTexture,zm(Fm(t).add(1),Fm(iy))).r):r.assign(l.element(t).toVar()),Dm(r.notEqual(0),()=>{!0===n&&Rb.addAssign(iT({bufferMap:u,influence:r,stride:c,width:d,depth:t,offset:Fm(0)})),!0===i&&Bb.addAssign(iT({bufferMap:u,influence:r,stride:c,width:d,depth:t,offset:Fm(1)}))})}),ES(({object:e})=>{const{base:t,influences:n}=a;e.geometry.morphTargetsRelative?t.value=1:t.value=1-e.morphTargetInfluences.reduce((e,t)=>e+t,0),n&&(n.array=e.morphTargetInfluences,n.update())})},"void");class sT extends Df{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class aT extends sT{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class oT extends Rv{static get type(){return"LightingContextNode"}constructor(e,t=null,n=[],i=null,r=null){super(e),this.lightingModel=t,this.materialLightings=n,this.backdropNode=i,this.backdropAlphaNode=r,this._value=null}getContext(){const{materialLightings:e,backdropNode:t,backdropAlphaNode:n}=this,i={directDiffuse:Hm().toVar("directDiffuse"),directSpecular:Hm().toVar("directSpecular"),indirectDiffuse:Hm().toVar("indirectDiffuse"),indirectSpecular:Hm().toVar("indirectSpecular")};return{radiance:Hm().toVar("radiance"),irradiance:Hm().toVar("irradiance"),iblIrradiance:Hm().toVar("iblIrradiance"),ambientOcclusion:Um(1).toVar("ambientOcclusion"),reflectedLight:i,materialLightings:e,backdrop:t,backdropAlpha:n}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const lT=wm(oT);class uT extends sT{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const cT=new dn;class hT extends Cy{static get type(){return"ViewportTextureNode"}constructor(e=Wy,t=null,n=null){let i=null;null===n?(i=new fs,i.minFilter=ce,n=i):i=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Tf,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),null===e)return t;if(!1===n.has(e)){const i=t.clone();n.set(e,i)}return n.get(e)}updateReference(e){const t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),r=n||i;return this.value=this.getTextureForReference(r),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),r=n||i;null===r?t.getDrawingBufferSize(cT):r.getDrawingBufferSize?r.getDrawingBufferSize(cT):cT.set(r.width,r.height);const s=this.getTextureForReference(r);s.image.width===cT.width&&s.image.height===cT.height||(s.image.width=cT.width,s.image.height=cT.height,s.needsUpdate=!0);const a=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const dT=wm(hT,null,null,{generateMipmaps:!0}).setParameterLength(0,3),pT=dT(),fT=(e=Wy,t=null)=>pT.sample(e,t);let mT=null;class gT extends hT{static get type(){return"ViewportDepthTextureNode"}constructor(e=Wy,t=null,n=null){null===n&&(null===mT&&(mT=new gs),n=mT),super(e,t,n)}}const _T=wm(gT).setParameterLength(0,3);class vT extends Df{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===vT.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===vT.DEPTH_BASE)null!==n&&(i=MT().assign(n));else if(t===vT.DEPTH)i=e.isPerspectiveCamera?xT(Lb.z,lb,ub):yT(Lb.z,lb,ub);else if(t===vT.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=ST(n,lb,ub);i=yT(e,lb,ub)}else i=n;else i=yT(Lb.z,lb,ub);return i}}vT.DEPTH_BASE="depthBase",vT.DEPTH="depth",vT.LINEAR_DEPTH="linearDepth";const yT=(e,t,n)=>e.add(t).div(t.sub(n)),bT=Nm(([e,t,n],i)=>!0===i.renderer.reversedDepthBuffer?n.sub(t).mul(e).sub(n):t.sub(n).mul(e).sub(t)),xT=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),ST=Nm(([e,t,n],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(n).div(t.sub(n).mul(e).sub(t)):t.mul(n).div(n.sub(t).mul(e).sub(n))),TT=(e,t,n)=>{t=t.max(1e-6).toVar();const i=R_(e.negate().div(t)),r=R_(n.div(t));return i.div(r)},MT=wm(vT,vT.DEPTH_BASE),wT=Em(vT,vT.DEPTH);_T(),wT.assign=e=>MT(e);class ET extends Df{static get type(){return"ClippingNode"}constructor(e=ET.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.hardwareClipping,this.scope===ET.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===ET.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return Nm(()=>{const n=Um().toVar("distanceToPlane"),i=Um().toVar("distanceToGradient"),r=Um(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Oy(t).setGroup(Og);JS(s,({i:t})=>{const s=e.element(t);n.assign(Lb.dot(s.xyz).negate().add(s.w)),i.assign(n.fwidth().div(2)),r.mulAssign(Tv(i.negate(),i,n))})}const a=e.length;if(a>0){const t=Oy(e).setGroup(Og),s=Um(1).toVar("intersectionClipOpacity");JS(a,({i:e})=>{const r=t.element(e);n.assign(Lb.dot(r.xyz).negate().add(r.w)),i.assign(n.fwidth().div(2)),s.mulAssign(Tv(i.negate(),i,n).oneMinus())}),r.mulAssign(s.oneMinus())}ig.a.mulAssign(r),ig.a.equal(0).discard()})()}setupDefault(e,t){return Nm(()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Oy(t).setGroup(Og);JS(n,({i:t})=>{const n=e.element(t);Lb.dot(n.xyz).greaterThan(n.w).discard()})}const i=e.length;if(i>0){const t=Oy(e).setGroup(Og),n=Bm(!0).toVar("clipped");JS(i,({i:e})=>{const i=t.element(e);n.assign(Lb.dot(i.xyz).greaterThan(i.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Nm(()=>{const i=Oy(e).setGroup(Og),r=ky(t.getClipDistance());JS(n,({i:e})=>{const t=i.element(e),n=Lb.dot(t.xyz).sub(t.w).negate();r.element(e).assign(n)})})()}}ET.ALPHA_TO_COVERAGE="alphaToCoverage",ET.DEFAULT="default",ET.HARDWARE="hardware";const AT=Nm(([e])=>I_(Yg(1e4,U_(Yg(17,e.x).add(Yg(.1,e.y)))).mul(Xg(.1,X_(U_(Yg(13,e.y).add(e.x))))))),RT=Nm(([e])=>AT(km(AT(e.xy),e.z))),CT=Nm(([e])=>{const t=lv(Y_(Q_(e.xyz)),Y_(J_(e.xyz))),n=Um(1).div(Um(.05).mul(t)).toVar("pixScale"),i=km(E_(P_(R_(n))),E_(L_(R_(n)))),r=km(RT(P_(i.x.mul(e.xyz))),RT(P_(i.y.mul(e.xyz)))),s=I_(R_(n)),a=Xg(Yg(s.oneMinus(),r.x),Yg(s,r.y)),o=ov(s,s.oneMinus()),l=Hm(a.mul(a).div(Yg(2,o).mul(qg(1,o))),a.sub(Yg(.5,o)).div(qg(1,o)),qg(1,qg(1,a).mul(qg(1,a)).div(Yg(2,o).mul(qg(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return bv(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class NT extends by{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Dn(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}class PT extends Cr{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.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const n=this[t];n&&!0===n.isNode&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(uf(t.slice(0,-4)),n.getCacheKey());return this.type+cf(e)}build(e){this.setup(e)}setupObserver(e){return new sf(e)}setup(e){e.context.setupNormal=()=>Iv(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),r=Iv(this.vertexNode||i,"VERTEX");let s;e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);const i=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=Xm(i,ig.a).max(0);s=this.setupOutput(e,r),Tg.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),e.context.getOutput&&(s=e.context.getOutput(s,e)),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(o&&Tg.assign(s),s=e,null!==n&&(s=e.merge(n))):null!==n&&(s=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=t.convert(e.getOutputType())),s=this.setupOutput(e,t)}e.stack.outputNode=s,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new ET(ET.ALPHA_TO_COVERAGE):e.stack.addToStack(new ET)}return i}setupHardwareClipping(e){if(e.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new ET(ET.HARDWARE)),e.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=n.isPerspectiveCamera?TT(Lb.z,lb,ub):yT(Lb.z,lb,ub))}null!==i&&wT.assign(i).toStack()}setupPositionView(){return Sb.mul(Rb).xyz}setupModelViewProjection(){return cb.mul(Lb)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),TS}setupPosition(e){const{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&rT(t),!0===t.isSkinnedMesh&&ZS(t),this.displacementMap){const e=lx("displacementMap","texture"),t=lx("displacementScale","float"),n=lx("displacementBias","float");Rb.addAssign(Bb.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&jS(t),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&BS(t),null!==this.positionNode&&Rb.assign(Iv(this.positionNode,"POSITION","vec3")),Rb}setupDiffuseColor(e){const{object:t,geometry:n}=e;null!==this.maskNode&&Bm(this.maskNode).not().discard();let i=this.colorNode?Xm(this.colorNode):kx;!0===this.vertexColors&&n.hasAttribute("color")&&(i=i.mul(((e=0)=>new NT(e))())),t.instanceColor&&(i=FS.mul(i)),t.isBatchedMesh&&t._colorsTexture&&(i=HS.mul(i)),ig.assign(i);const r=this.opacityNode?Um(this.opacityNode):Gx;ig.a.assign(ig.a.mul(r));let s=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(s=null!==this.alphaTestNode?Um(this.alphaTestNode):Bx,!0===this.alphaToCoverage?(ig.a=Tv(s,s.add(iv(ig.a)),ig.a),ig.a.lessThanEqual(0).discard()):ig.a.lessThanEqual(s).discard()),!0===this.alphaHash&&ig.a.lessThan(CT(Rb)).discard(),e.isOpaque()&&ig.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Hm(0):ig.rgb}setupNormal(){return this.normalNode?Hm(this.normalNode):Kx}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?lx("envMap","cubeTexture"):lx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new uT(bS)),t}setupMaterialLightings(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),e.context.ambientOcclusion&&t.push(new aT(e.context.ambientOcclusion)),e.context.getGI){const n=e.context.getGI(null,e);null!==n&&t.push(new uT(n))}return t}setupAmbientOcclusion(e){let t=this.aoNode;null===t&&e.material.aoMap&&(t=xS),e.context.getAO&&(t=e.context.getAO(t,e)),null!==t&&(Dg.assign(t),e.context.ambientOcclusion=Dg)}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights&&e.renderer.lighting.enabled,a=s||null!==this.lightsNode,o=s?this.setupMaterialLightings(e):[],l=a?this.lightsNode||e.lightsNode:null;let u=this.setupOutgoingLight(e);if(l&&(o.length>0||l.getScope().hasLights)){const t=this.setupLightingModel(e)||null;u=lT(l,t,o,n,i)}else null!==n&&(u=Hm(null!==i?yv(u,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(sg.assign(Hm(r||Vx)),u=u.add(sg)),u}setupFog(e,t){const n=e.fogNode;return n&&(Tg.assign(t),t=Xm(n.toVar())),t}setupPremultipliedAlpha(e,t){return py(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.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 n=Cr.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())n.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),s=i(e.nodes);t.length>0&&(n.textures=t),r.length>0&&(n.images=r),s.length>0&&(n.nodes=s)}return n}copy(e){const t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(const n in t)if(void 0!==t[n].set&&void 0!==e[n]){const t=e[n];this[n]&&void 0!==this[n].copy?this[n].copy(t):this[n]=t}for(const t in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(t)&&void 0!==this[t]&&void 0!==e[t]){const n=e[t];this[t]&&void 0!==this[t].copy?this[t].copy(n):this[t]=n}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(e=>e.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}}const LT=new rs;class DT extends PT{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(LT),this.setValues(e)}}const IT=new na;class UT extends PT{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(IT),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Um(this.offsetNode):gS,t=this.dashScaleNode?Um(this.dashScaleNode):dS,n=this.dashSizeNode?Um(this.dashSizeNode):pS,i=this.gapSizeNode?Um(this.gapSizeNode):fS;Mg.assign(n),wg.assign(i);const r=Fv(xy("lineDistance").mul(t));(e?r.add(e):r).mod(Mg.add(wg)).greaterThan(Mg).discard()}}const FT=ng("vec3","worldStart"),OT=ng("vec3","worldEnd"),BT=ng("float","lineDistance"),kT=ng("vec4","worldPos"),zT=Nm(({start:e,end:t})=>{const n=cb.element(2).element(2),i=cb.element(3).element(2);return n.greaterThan(0).select(i.negate().div(n.add(1)),i.mul(-.5).div(n)).sub(e.z).div(t.z.sub(e.z))},{start:"vec4",end:"vec4",return:"float"}),VT=Nm(({p1:e,p2:t,p3:n,p4:i})=>{const r=e.sub(n),s=i.sub(n),a=t.sub(e),o=r.dot(s),l=s.dot(a),u=r.dot(a),c=s.dot(s),h=a.dot(a).mul(c).sub(l.mul(l)),d=o.mul(l).sub(u.mul(c)).div(h).clamp(),p=o.add(l.mul(d)).div(c).clamp();return km(d,p)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"});Nm(({material:e})=>{const t=e._useDash,n=e._useWorldUnits,i=xy("instanceStart"),r=xy("instanceEnd"),s=Xm(Sb.mul(Xm(i,1))).toVar("start"),a=Xm(Sb.mul(Xm(r,1))).toVar("end");let o,l;t&&(o=Um(xy("instanceDistanceStart")).toVar("distanceStart"),l=Um(xy("instanceDistanceEnd")).toVar("distanceEnd")),n&&(FT.assign(s.xyz),OT.assign(a.xyz));const u=Xy.z.div(Xy.w),c=cb.element(2).element(3).equal(-1);if(Dm(c,()=>{Dm(s.z.lessThan(0).and(a.z.greaterThan(0)),()=>{const e=zT({start:s,end:a});a.assign(Xm(yv(s.xyz,a.xyz,e),a.w)),t&&l.assign(yv(o,l,e))}).ElseIf(a.z.lessThan(0).and(s.z.greaterThanEqual(0)),()=>{const e=zT({start:a,end:s});s.assign(Xm(yv(a.xyz,s.xyz,e),s.w)),t&&o.assign(yv(l,o,e))})}),t){const t=e.dashScaleNode?Um(e.dashScaleNode):dS,n=e.offsetNode?Um(e.offsetNode):gS;let i=Ab.y.lessThan(.5).select(t.mul(o),t.mul(l));i=i.add(n),BT.assign(i)}const h=cb.mul(s),d=cb.mul(a),p=h.xyz.div(h.w),f=d.xyz.div(d.w),m=f.xy.sub(p.xy).toVar();m.x.assign(m.x.mul(u)),m.assign(m.normalize());const g=Xm().toVar();if(n){const e=a.xyz.sub(s.xyz).normalize(),n=yv(s.xyz,a.xyz,.5).normalize(),i=e.cross(n).normalize(),r=e.cross(i);kT.assign(Ab.y.lessThan(.5).select(s,a));const o=mS.mul(.5);kT.addAssign(Xm(Ab.x.lessThan(0).select(i.mul(o),i.mul(o).negate()),0)),t||(kT.addAssign(Xm(Ab.y.lessThan(.5).select(e.mul(o).negate(),e.mul(o)),0)),kT.addAssign(Xm(r.mul(o),0)),Dm(Ab.y.greaterThan(1).or(Ab.y.lessThan(0)),()=>{kT.subAssign(Xm(r.mul(2).mul(o),0))})),g.assign(cb.mul(kT));const l=Hm().toVar();l.assign(Ab.y.lessThan(.5).select(p,f)),g.z.assign(l.z.mul(g.w))}else{const e=km(m.y,m.x.negate()).toVar("offset");m.x.assign(m.x.div(u)),e.x.assign(e.x.div(u)),e.assign(Ab.x.lessThan(0).select(e.negate(),e)),Dm(Ab.y.lessThan(0),()=>{e.assign(e.sub(m))}).ElseIf(Ab.y.greaterThan(1),()=>{e.assign(e.add(m))}),e.assign(e.mul(mS)),e.assign(e.div(Xy.w.div(Hy))),g.assign(Ab.y.lessThan(.5).select(h,d)),e.assign(e.mul(g.w)),g.assign(g.add(Xm(e,0,0)))}return g})(),Nm(({material:e,renderer:t})=>{const n=e._useAlphaToCoverage,i=e._useDash,r=e._useWorldUnits,s=Sy();if(i){const t=e.dashSizeNode?Um(e.dashSizeNode):pS,n=e.gapSizeNode?Um(e.gapSizeNode):fS;Mg.assign(t),wg.assign(n),s.y.lessThan(-1).or(s.y.greaterThan(1)).discard(),BT.mod(Mg.add(wg)).greaterThan(Mg).discard()}const a=Um(1).toVar("alpha");if(r){const e=kT.xyz.normalize().mul(1e5),r=OT.sub(FT),s=VT({p1:FT,p2:OT,p3:Hm(0,0,0),p4:e}),o=FT.add(r.mul(s.x)),l=e.mul(s.y),u=o.sub(l).length().div(mS);if(!i)if(n&&t.currentSamples>0){const e=u.fwidth();a.assign(Tv(e.negate().add(.5),e.add(.5),u).oneMinus())}else u.greaterThan(.5).discard()}else if(n&&t.currentSamples>0){const e=s.x,t=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1)),n=e.mul(e).add(t.mul(t)),i=Um(n.fwidth()).toVar("dlen");Dm(s.y.abs().greaterThan(1),()=>{a.assign(Tv(i.oneMinus(),i.add(1),n).oneMinus())})}else Dm(s.y.abs().greaterThan(1),()=>{const e=s.x,t=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()});return a})();const GT=new Zs;class HT extends PT{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(GT),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Um(this.opacityNode):Gx;ig.assign(Vv(Xm(xm(Gb).mul(.5).add(.5),e),vt))}}const WT=Nm(([e=Pb])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return km(t,n)}),jT=Nm(([e=Sy()])=>{const t=e.x.sub(.5).mul(2*Math.PI),n=e.y.sub(.5).mul(Math.PI),i=n.cos(),r=i.mul(t.cos()),s=n.sin(),a=i.mul(t.sin());return Hm(r,s,a)});class $T extends In{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new ms(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const n=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 ys(5,5,5),s=WT(Pb),a=new PT;a.colorNode=Py(t,s,0),a.side=1,a.blending=0;const o=new qr(r,a),l=new xi;l.add(o),t.minFilter===ce&&(t.minFilter=le);const u=new Fa(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.generateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}const XT=new WeakMap;class qT extends Ff{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=rx(null);const t=new ms;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Tf}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:n[i.property];if(e&&e.isTexture){const n=e.mapping;if(n===J||n===ee){if(XT.has(e)){const t=XT.get(e);KT(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const i=new $T(n.height);i.fromEquirectangularTexture(t,e),KT(i.texture,e.mapping),this._cubeTexture=i.texture,XT.set(e,i.texture),e.addEventListener("dispose",YT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function YT(e){const t=e.target;t.removeEventListener("dispose",YT);const n=XT.get(t);void 0!==n&&(XT.delete(t),n.dispose())}function KT(e,t){t===J?e.mapping=Z:t===ee&&(e.mapping=Q)}const ZT=wm(qT).setParameterLength(1);class QT extends sT{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=ZT(this.envNode)}}class JT extends sT{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Um(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class eM{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class tM extends eM{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(Xm(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(Xm(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(ig.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(yv(i.rgb,i.rgb.mul(r.rgb),$x.mul(Xx)));break;case 1:i.rgb.assign(yv(i.rgb,r.rgb,$x.mul(Xx)));break;case 2:i.rgb.addAssign(r.rgb.mul($x.mul(Xx)));break;default:qt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const nM=new Fr;class iM extends PT{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(nM),this.setValues(e)}setupNormal(){return Fb(zb)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new QT(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new JT(bS)),t}setupOutgoingLight(){return ig.rgb}setupLightingModel(){return new tM}}const rM=Nm(({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),sM=Nm(e=>e.diffuseColor.mul(1/Math.PI)),aM=Nm(({dotNH:e})=>Sg.mul(Um(.5)).add(1).mul(Um(1/Math.PI)).mul(e.pow(Sg))),oM=Nm(({lightDirection:e})=>{const t=e.add(Db).normalize(),n=Gb.dot(t).clamp(),i=Db.dot(t).clamp(),r=rM({f0:yg,f90:1,dotVH:i}),s=Um(.25),a=aM({dotNH:n});return r.mul(s).mul(a)});class lM extends tM{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Gb.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(sM({diffuseColor:ig.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(oM({lightDirection:e})).mul($x))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(sM({diffuseColor:ig}))),i.indirectDiffuse.mulAssign(t)}}const uM=new Qs;class cM extends PT{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(uM),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new QT(t):null}setupLightingModel(){return new lM(!1)}}const hM=new Ys;class dM extends PT{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(hM),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new QT(t):null}setupLightingModel(){return new lM}setupVariants(){const e=(this.shininessNode?Um(this.shininessNode):zx).max(1e-4);Sg.assign(e);const t=this.specularNode||Hx;yg.assign(t)}}const pM=Nm(e=>{if(!1===e.geometry.hasAttribute("normal"))return Um(0);const t=zb.dFdx().abs().max(zb.dFdy().abs());return t.x.max(t.y).max(t.z)}),fM=Nm(e=>{const{roughness:t}=e,n=pM();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i}),mM=Nm(({alpha:e,dotNL:t,dotNV:n})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Kg(.5,r.add(s).max(y_))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),gM=Nm(({alphaT:e,alphaB:t,dotTV:n,dotBV:i,dotTL:r,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(Hm(e.mul(n),t.mul(i),a).length()),u=a.mul(Hm(e.mul(r),t.mul(s),o).length());return Kg(.5,l.add(u).max(y_))}).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"}]}),_M=Nm(({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),vM=Um(1/Math.PI),yM=Nm(({alphaT:e,alphaB:t,dotNH:n,dotTH:i,dotBH:r})=>{const s=e.mul(t),a=Hm(t.mul(i),e.mul(r),s.mul(n)),o=a.dot(a),l=s.div(o);return vM.mul(s.mul(l.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"}]}),bM=Nm(({lightDirection:e,f0:t,f90:n,roughness:i,f:r,normalView:s=Gb,viewDirection:a=Db,USE_IRIDESCENCE:o,USE_ANISOTROPY:l})=>{const u=i.pow2(),c=e.add(a).normalize(),h=s.dot(e).clamp(),d=s.dot(a).clamp(),p=s.dot(c).clamp(),f=a.dot(c).clamp();let m,g,_=rM({f0:t,f90:n,dotVH:f});if(ym(o)&&(_=dg.mix(_,r)),ym(l)){const t=_g.dot(e),n=_g.dot(a),i=_g.dot(c),r=vg.dot(e),s=vg.dot(a),o=vg.dot(c);m=gM({alphaT:mg,alphaB:u,dotTV:n,dotBV:s,dotTL:t,dotBL:r,dotNV:d,dotNL:h}),g=yM({alphaT:mg,alphaB:u,dotNH:p,dotTH:i,dotBH:o})}else m=mM({alpha:u,dotNL:h,dotNV:d}),g=_M({alpha:u,dotNH:p});return _.mul(m).mul(g)}),xM=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let SM=null;const TM=Nm(({roughness:e,dotNV:t})=>{null===SM&&(SM=new Kr(xM,16,16,Pe,ve),SM.name="DFG_LUT",SM.minFilter=le,SM.magFilter=le,SM.wrapS=ie,SM.wrapT=ie,SM.generateMipmaps=!1,SM.needsUpdate=!0);const n=km(e,t);return Py(SM,n).rg}),MM=Nm(e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=TM({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))}),wM=Nm(({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub(Hm(t).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),EM=Nm(({roughness:e,dotNH:t})=>{const n=e.pow2(),i=Um(1).div(n),r=t.pow2().oneMinus().max(.0078125);return Um(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"}]}),AM=Nm(({dotNV:e,dotNL:t})=>Um(1).div(Um(4).mul(t.add(e).sub(t.mul(e)))).clamp()).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),RM=Nm(({lightDirection:e})=>{const t=e.add(Db).normalize(),n=Gb.dot(e).clamp(),i=Gb.dot(Db).clamp(),r=Gb.dot(t).clamp(),s=EM({roughness:hg,dotNH:r}),a=AM({dotNV:i,dotNL:n});return cg.mul(s).mul(a)}),CM=Nm(({N:e,V:t,roughness:n})=>{const i=e.dot(t).saturate(),r=km(n,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"}]}),NM=Nm(({f:e})=>{const t=e.length();return lv(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),PM=Nm(({v1:e,v2:t})=>{const n=e.dot(t),i=n.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),s=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(s),o=n.greaterThan(0).select(a,lv(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),LM=Nm(({N:e,V:t,P:n,mInv:i,p0:r,p1:s,p2:a,p3:o})=>{const l=s.sub(r).toVar(),u=o.sub(r).toVar(),c=l.cross(u),h=Hm().toVar();return Dm(c.dot(n.sub(r)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=i.mul(Qm(l,u,e).transpose()).toVar(),d=c.mul(r.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=Hm(0).toVar();g.addAssign(PM({v1:d,v2:p})),g.addAssign(PM({v1:p,v2:f})),g.addAssign(PM({v1:f,v2:m})),g.addAssign(PM({v1:m,v2:d})),h.assign(Hm(NM({f:g})))}),h}).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"}]}),DM=1/6,IM=e=>Yg(DM,Yg(e,Yg(e,e.negate().add(3)).sub(3)).add(1)),UM=e=>Yg(DM,Yg(e,Yg(e,Yg(3,e).sub(6))).add(4)),FM=e=>Yg(DM,Yg(e,Yg(e,Yg(-3,e).add(3)).add(3)).add(1)),OM=e=>Yg(DM,mv(e,3)),BM=e=>IM(e).add(UM(e)),kM=e=>FM(e).add(OM(e)),zM=e=>Xg(-1,UM(e).div(IM(e).add(UM(e)))),VM=e=>Xg(1,OM(e).div(FM(e).add(OM(e)))),GM=(e,t,n)=>{const i=e.uvNode,r=Yg(i,t.zw).add(.5),s=P_(r),a=I_(r),o=BM(a.x),l=kM(a.x),u=zM(a.x),c=VM(a.x),h=zM(a.y),d=VM(a.y),p=km(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=km(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=km(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=km(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=BM(a.y).mul(Xg(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=kM(a.y).mul(Xg(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},HM=Nm(([e,t])=>{const n=km(e.size(Fm(t))),i=km(e.size(Fm(t.add(1)))),r=Kg(1,n),s=Kg(1,i),a=GM(e,Xm(r,n),P_(t)),o=GM(e,Xm(s,i),L_(t));return I_(t).mix(a,o)}),WM=Nm(([e,t,n,i,r])=>{const s=Hm(Sv(t.negate(),D_(e),Kg(1,i))),a=Hm(Y_(r[0].xyz),Y_(r[1].xyz),Y_(r[2].xyz));return D_(s).mul(n.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),jM=Nm(([e,t])=>e.mul(bv(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),$M=dT(),XM=fT(),qM=Nm(([e,t,n],{material:i})=>{const r=(1===i.side?$M:XM).sample(e.mul(mb.zw).add(mb.xy).div(jy)),s=R_(mb.z).mul(jM(t,n));return HM(r,s)}),YM=Nm(([e,t,n])=>(Dm(n.notEqual(0),()=>{const i=A_(t).negate().div(n);return w_(i.negate().mul(e))}),Hm(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),KM=Nm(([e,t,n,i,r,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=Xm().toVar(),g=Hm().toVar();const r=c.sub(1).mul(f.mul(.025)),s=Hm(c.sub(r),c,c.add(r));JS({start:0,end:3},({i:r})=>{const c=s.element(r),f=WM(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(Xm(_,1))),y=km(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(km(y.x,y.y.oneMinus()));const b=qM(y,n,c);m.element(r).assign(b.element(r)),m.a.addAssign(b.a),g.element(r).assign(i.element(r).mul(YM(Y_(f),d,p).element(r)))}),m.a.divAssign(3)}else{const r=WM(e,t,h,c,o),s=a.add(r),f=u.mul(l.mul(Xm(s,1))),_=km(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(km(_.x,_.y.oneMinus())),m=qM(_,n,c),g=i.mul(YM(Y_(r),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=Hm(MM({dotNV:v,specularColor:r,specularF90:s,roughness:n})),b=g.r.add(g.g,g.b).div(3);return Xm(y.oneMinus().mul(_),m.a.oneMinus().mul(b).oneMinus())}),ZM=Qm(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),QM=(e,t)=>e.sub(t).div(e.add(t)).pow2(),JM=Nm(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=yv(e,t,Tv(0,.03,i)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();Dm(a.lessThan(0),()=>Hm(1));const o=a.sqrt(),l=QM(s,e),u=rM({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=Um(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return Hm(1).add(t).div(Hm(1).sub(t))})(r.clamp(0,.9999)),f=QM(p,s.toVec3()),m=rM({f0:f,f90:1,dotVH:o}),g=Hm(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(i,o,2),v=Hm(d).add(g),y=u.mul(m).clamp(1e-5,.9999),b=y.sqrt(),x=c.pow2().mul(m).div(Hm(1).sub(y)),S=u.add(x).toVar(),T=x.sub(c).toVar();return JS({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{T.mulAssign(b);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=Hm(54856e-17,44201e-17,52481e-17),r=Hm(1681e3,1795300,2208400),s=Hm(43278e5,93046e5,66121e5),a=Um(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=Hm(o.x.add(a),o.y,o.z).div(1.0685e-7),ZM.mul(o)})(Um(e).mul(_),Um(e).mul(v)).mul(2);S.addAssign(T.mul(t))}),S.max(Hm(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"}]}),ew=Nm(({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.mul(n),s=n.add(.1).reciprocal(),a=Um(-1.9362).add(n.mul(1.0678)).add(r.mul(.4573)).sub(s.mul(.8469)),o=Um(-.6014).add(n.mul(.5538)).sub(r.mul(.467)).sub(s.mul(.1255));return a.mul(i).add(o).exp().saturate()}),tw=Hm(.04),nw=Um(1);class iw extends eM{constructor(e=!1,t=!1,n=!1,i=!1,r=!1,s=!1,a=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=r,this.dispersion=s,this.retroreflection=a,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null,this.dfg=null,this.multiScatteringCompensation=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Hm().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Hm().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Hm().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Hm().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Hm().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Gb.dot(Db).clamp(),t=JM({outsideIOR:Um(1),eta2:pg,cosTheta1:e,thinFilmThickness:fg,baseF0:yg}),n=JM({outsideIOR:Um(1),eta2:pg,cosTheta1:e,thinFilmThickness:fg,baseF0:ig.rgb});this.iridescenceFresnel=yv(t,n,og),this.iridescenceF0Dielectric=wM({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=wM({f:n,f90:1,dotVH:e})}if(!0===this.transmission){const t=Nb,n=fb.sub(Nb).normalize(),i=Hb,r=e.context;r.backdrop=KM(i,n,ag,rg,bg,xg,t,bb,db,cb,Eg,Rg,Ng,Cg,this.dispersion?Pg:null),r.backdropAlpha=Ag,ig.a.mulAssign(yv(1,r.backdrop.a,Ag))}const t=Gb.dot(Db).clamp();this.dfg=TM({roughness:ag,dotNV:t}).toConst("dfg");const n=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=bg.mul(n.reciprocal().sub(1)).add(1).toConst("multiScatteringCompensation"),super.start(e)}computeMultiscattering(e,t,n,i,r=null){const s=this.dfg,a=r?dg.mix(i,r):i,o=a.mul(s.x).add(n.mul(s.y)),l=s.x.add(s.y).oneMinus(),u=a.add(a.oneMinus().mul(.047619)),c=o.mul(u).div(l.mul(u).oneMinus());e.addAssign(o),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Gb.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(RM({lightDirection:e})));const t=ew({normal:Gb,viewDir:Db,roughness:hg}),n=ew({normal:Gb,viewDir:e,roughness:hg}),r=cg.r.max(cg.g).max(cg.b).mul(t.max(n)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const n=Wb.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(bM({lightDirection:e,f0:tw,f90:nw,roughness:ug,normalView:Wb})))}const r=e.add(Db).normalize(),s=Db.dot(r).clamp();let a=rM({f0:yg,f90:xg,dotVH:s}),o=bM({lightDirection:e,f0:bg,f90:1,roughness:ag,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(!0===this.retroreflection){const t=Db.negate().reflect(Gb),n=e.add(t).normalize(),i=t.dot(n).clamp(),r=rM({f0:yg,f90:xg,dotVH:i}),s=bM({lightDirection:e,viewDirection:t,f0:bg,f90:1,roughness:ag,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});a=yv(a,r,Lg.clamp()),o=yv(o,s,Lg.clamp())}n.directDiffuse.addAssign(i.mul(sM({diffuseColor:rg})).mul(a.oneMinus())),n.directSpecular.addAssign(i.mul(o).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:r,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(i),l=t.sub(n).sub(i),u=t.sub(n).add(i),c=t.add(n).add(i),h=Gb,d=Db,p=Lb.toVar(),f=CM({N:h,V:d,roughness:ag}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=Qm(Hm(m.x,0,m.y),Hm(0,1,0),Hm(m.z,0,m.w)).toVar(),v=bg.mul(g.x).add(xg.sub(bg).mul(g.y)).toVar();if(r.directSpecular.addAssign(e.mul(v).mul(LM({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),r.directDiffuse.addAssign(e.mul(rg).mul(LM({N:h,V:d,P:p,mInv:Qm(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c}))),!0===this.clearcoat){const t=Wb,n=CM({N:t,V:d,roughness:ug}),i=s.sample(n),r=a.sample(n),h=Qm(Hm(i.x,0,i.y),Hm(0,1,0),Hm(i.z,0,i.w)),f=tw.mul(r.x).add(nw.sub(tw).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(f).mul(LM({N:t,V:d,P:p,mInv:h,p0:o,p1:l,p2:u,p3:c})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context,i=Hm().toVar(),r=Hm().toVar();this.computeMultiscattering(i,r,xg,yg,this.iridescenceF0Dielectric);const s=t.mul(sM({diffuseColor:rg})).mul(i.add(r).oneMinus()).toVar();if(!0===this.sheen){const e=ew({normal:Gb,viewDir:Db,roughness:hg});this.sheenSpecularIndirect.addAssign(t.mul(cg,e,1/Math.PI));const n=cg.r.max(cg.g).max(cg.b).mul(e).oneMinus();s.mulAssign(n)}n.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(cg,ew({normal:Gb,viewDir:Db,roughness:hg}),1/Math.PI)),!0===this.clearcoat){const e=Wb.dot(Db).clamp(),t=MM({dotNV:e,specularColor:tw,specularF90:nw,roughness:ug});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=Hm().toVar("singleScatteringDielectric"),s=Hm().toVar("multiScatteringDielectric"),a=Hm().toVar("singleScatteringMetallic"),o=Hm().toVar("multiScatteringMetallic");this.computeMultiscattering(r,s,xg,yg,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,xg,ig.rgb,this.iridescenceF0Metallic);const l=yv(r,a,og),u=yv(s,o,og),c=r.add(s),h=rg.mul(c.oneMinus()),d=n.mul(1/Math.PI),p=t.mul(l).add(u.mul(d)).toVar(),f=h.mul(d).toVar();if(!0===this.sheen){const e=ew({normal:Gb,viewDir:Db,roughness:hg}),t=cg.r.max(cg.g).max(cg.b).mul(e).oneMinus();p.mulAssign(t),f.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(f)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,i=Gb.dot(Db).clamp().add(t),r=ag.mul(-16).oneMinus().negate().exp2(),s=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Wb.dot(Db).clamp(),n=rM({dotVH:e,f0:tw,f90:nw}),i=t.mul(lg.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(lg));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(e)}}}const rw=Um(1),sw=Um(-2),aw=Um(.8),ow=Um(-1),lw=Um(.4),uw=Um(2),cw=Um(.305),hw=Um(3),dw=Um(.21),pw=Um(4),fw=Um(4),mw=Um(16),gw=Nm(([e])=>{const t=Hm(X_(e)).toVar(),n=Um(-1).toVar();return Dm(t.x.greaterThan(t.z),()=>{Dm(t.x.greaterThan(t.y),()=>{n.assign(Av(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(Av(e.y.greaterThan(0),1,4))})}).Else(()=>{Dm(t.z.greaterThan(t.y),()=>{n.assign(Av(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(Av(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),_w=Nm(([e,t])=>{const n=km().toVar();return Dm(t.equal(0),()=>{n.assign(km(e.z,e.y).div(X_(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(km(e.x.negate(),e.z.negate()).div(X_(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(km(e.x.negate(),e.y).div(X_(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(km(e.z.negate(),e.y).div(X_(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(km(e.x.negate(),e.z).div(X_(e.y)))}).Else(()=>{n.assign(km(e.x,e.y).div(X_(e.z)))}),Yg(.5,n.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),vw=Nm(([e])=>{const t=Um(0).toVar();return Dm(e.greaterThanEqual(aw),()=>{t.assign(rw.sub(e).mul(ow.sub(sw)).div(rw.sub(aw)).add(sw))}).ElseIf(e.greaterThanEqual(lw),()=>{t.assign(aw.sub(e).mul(uw.sub(ow)).div(aw.sub(lw)).add(ow))}).ElseIf(e.greaterThanEqual(cw),()=>{t.assign(lw.sub(e).mul(hw.sub(uw)).div(lw.sub(cw)).add(uw))}).ElseIf(e.greaterThanEqual(dw),()=>{t.assign(cw.sub(e).mul(pw.sub(hw)).div(cw.sub(dw)).add(hw))}).Else(()=>{t.assign(Um(-2).mul(R_(Yg(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),yw=Nm(([e,t,n,i,r,s])=>{const a=Um(n),o=Hm(t),l=bv(vw(a),sw,s),u=I_(l),c=P_(l),h=Hm(bw(e,o,c,i,r,s)).toVar();return Dm(u.notEqual(0),()=>{const t=Hm(bw(e,o,c.add(1),i,r,s)).toVar();h.assign(yv(h,t,u))}),h}),bw=Nm(([e,t,n,i,r,s])=>{const a=Um(n).toVar(),o=Hm(t),l=Um(gw(o)).toVar(),u=Um(lv(fw.sub(a),0)).toVar();a.assign(lv(a,fw));const c=Um(E_(a)).toVar(),h=km(_w(o,l).mul(c.sub(2)).add(1)).toVar();return Dm(l.greaterThan(2),()=>{h.y.addAssign(c),l.subAssign(3)}),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(Yg(3,mw))),h.y.addAssign(Yg(4,E_(s).sub(c))),h.x.mulAssign(i),h.y.mulAssign(r),e.sample(h).grad(km(),km())}),xw=Nm(({SAMPLES:e,sigma:t,outputDirection:n,mipInt:i,envMap:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=Hm(0).toVar();return Dm(t.equal(0),()=>{l.assign(bw(r,n,i,s,a,o))}).Else(()=>{const u=Av(X_(n.z).lessThan(.999),Hm(0,0,1),Hm(1,0,0)),c=D_(fv(u,n)).toVar(),h=fv(n,c).toVar(),d=ov(t.mul(3),Math.PI),p=w_(d.mul(d).mul(-.5).div(t.mul(t))).oneMinus().toVar(),f=Um(0).toVar();JS({start:Fm(0),end:e},({i:u})=>{const d=Um(u).add(.5).div(Um(e)),m=t.mul(C_(A_(d.mul(p).oneMinus()).mul(-2))).toVar(),g=Um(u).mul(2.399963229728653).toVar(),_=c.mul(O_(g)).add(h.mul(U_(g))),v=n.mul(O_(m)).add(_.mul(U_(m))),y=U_(m).div(m).toVar();l.addAssign(bw(r,v,i,s,a,o).mul(y)),f.addAssign(y)}),l.divAssign(f)}),Xm(l,1)}),Sw=Nm(([e])=>{const t=Om(e).toVar();return t.assign(t.shiftLeft(Om(16)).bitOr(t.shiftRight(Om(16)))),t.assign(t.bitAnd(Om(1431655765)).shiftLeft(Om(1)).bitOr(t.bitAnd(Om(2863311530)).shiftRight(Om(1)))),t.assign(t.bitAnd(Om(858993459)).shiftLeft(Om(2)).bitOr(t.bitAnd(Om(3435973836)).shiftRight(Om(2)))),t.assign(t.bitAnd(Om(252645135)).shiftLeft(Om(4)).bitOr(t.bitAnd(Om(4042322160)).shiftRight(Om(4)))),t.assign(t.bitAnd(Om(16711935)).shiftLeft(Om(8)).bitOr(t.bitAnd(Om(4278255360)).shiftRight(Om(8)))),Um(t).mul(2.3283064365386963e-10)}),Tw=Nm(([e,t])=>km(Um(e).div(Um(t)),Sw(e))),Mw=Nm(([e,t,n])=>{const i=n.mul(n).toConst(),r=Hm(1,0,0).toConst(),s=fv(t,r).toConst(),a=C_(e.x).toConst(),o=Yg(2,3.14159265359).mul(e.y).toConst(),l=a.mul(O_(o)).toConst(),u=a.mul(U_(o)).toVar(),c=Yg(.5,t.z.add(1)).toConst();u.assign(c.oneMinus().mul(C_(l.mul(l).oneMinus())).add(c.mul(u)));const h=r.mul(l).add(s.mul(u)).add(t.mul(C_(lv(0,l.mul(l).add(u.mul(u)).oneMinus()))));return D_(Hm(i.mul(h.x),i.mul(h.y),lv(0,h.z)))}),ww=Nm(({roughness:e,mipInt:t,envMap:n,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=Hm(i).toVar(),u=Hm(0).toVar(),c=Um(0).toVar();return Dm(e.lessThan(.001),()=>{u.assign(bw(n,l,t,s,a,o))}).Else(()=>{const i=Av(X_(l.z).lessThan(.999),Hm(0,0,1),Hm(1,0,0)),h=D_(fv(i,l)).toVar(),d=fv(l,h).toVar();JS({start:Om(0),end:r},({i:i})=>{const p=Tw(i,r),f=Mw(p,Hm(0,0,1),e),m=D_(h.mul(f.x).add(d.mul(f.y)).add(l.mul(f.z))),g=D_(m.mul(pv(l,m).mul(2)).sub(l)),_=lv(pv(l,g),0);Dm(_.greaterThan(0),()=>{const e=bw(n,g,t,s,a,o);u.addAssign(e.mul(_)),c.addAssign(_)})}),Dm(c.greaterThan(0),()=>{u.assign(u.div(c))})}),Xm(u,1)}),Ew=new Ra(-1,1,1,-1,0,1),Aw=new Ta(90,1),Rw=new yi;let Cw=null,Nw=0,Pw=0;const Lw=new fn,Dw=new fn,Iw=new WeakMap,Uw=[3,1,5,0,4,2],Fw=xy("outputDirection").normalize();class Ow{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=Lw,renderTarget:o=null}=r;if(this._setSize(s),!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.');Cw=this._renderer.getRenderTarget(),Nw=this._renderer.getActiveCubeFace(),Pw=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTarget(!0);return this._init(l),this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,i=100,r={}){return Kt('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Kt('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Kt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=zw(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Vw(),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===Z||e.mapping===Q?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],r=Uw[e];h.set(i,c*u*r);for(let e=0;e4&&i--}return{lodMeshes:n,sizeLods:t}}(t)),this._blurMaterial=function(e,t,n){const i=Py(),r=zg(0),s=zg(0),a=Um(1/t),o=Um(1/n),l=Um(e),u={envMap:i,sigma:r,mipInt:s,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},c=kw("blur");return c.fragmentNode=xw({...u,outputDirection:Fw,SAMPLES:Fm(20)}),Iw.set(c,u),c}(t,e.width,e.height),this._ggxMaterial=function(e,t,n){const i=Py(),r=zg(0),s=zg(0),a=Um(1/t),o=Um(1/n),l=Um(e),u={envMap:i,roughness:r,mipInt:s,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},c=kw("ggx");return c.fragmentNode=ww({...u,N_immutable:Fw,GGX_SAMPLES:Om(256)}),Iw.set(c,u),c}(t,e.width,e.height)}}async _compileMaterial(e){const t=new qr(new br,e);await this._renderer.compile(t,Ew)}_sceneToCubeUV(e,t,n,i,r){const s=Aw;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(Rw),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new qr(new ys,new Fr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const c=this._backgroundBox,h=c.material;let d=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,d=!0):(h.color.copy(Rw),d=!0),l.setRenderTarget(i),l.clear(),d&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;this._setViewport(i,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===Z||e.mapping===Q;i?null===this._cubemapMaterial&&(this._cubemapMaterial=zw(e)):null===this._equirectMaterial&&(this._equirectMaterial=Vw(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=r;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Ew)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;th-4?n-h+4:0),f=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,this._setViewport(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,Ew),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,this._setViewport(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,Ew)}_blur(e,t,n,i){const r=this._pingPongRenderTarget,s=Math.min(i,Math.PI)/Math.SQRT2;this._blurPass(e,r,t,n,s),this._blurPass(r,e,n,n,s)}_blurPass(e,t,n,i,r){const s=this._renderer,a=this._blurMaterial,o=this._lodMeshes[i];o.material=a;const l=Iw.get(a);e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.sigma.value=r,l.mipInt.value=this._lodMax-n;const u=this._sizeLods[i],c=3*u*(i>this._lodMax-4?i-this._lodMax+4:0),h=4*(this._cubeSize-u);this._setViewport(t,c,h,3*u,2*u),s.setRenderTarget(t),s.render(o,Ew)}_setViewport(e,t,n,i,r){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-r-n,i,r),e.scissor.set(t,e.height-r-n,i,r)):(e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r))}}function Bw(e,t,n){const i=new In(e,t,{magFilter:le,minFilter:le,generateMipmaps:!1,type:ve,format:Ee,colorSpace:yt,depthBuffer:n});return i.texture.mapping=te,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function kw(e){const t=new PT;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function zw(e){const t=kw("cubemap");return t.fragmentNode=rx(e,Fw),t}function Vw(e){const t=kw("equirect");return t.fragmentNode=Py(e,WT(Fw),0),t}const Gw=new WeakMap;function Hw(e,t,n){const i=function(e){let t=Gw.get(e);void 0===t&&(t=new WeakMap,Gw.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let i=0;i0}(t))return null;r=n.fromEquirectangular(e,r)}if(r.pmremVersion=e.pmremVersion,!1===i.has(e)){const t=()=>{e.removeEventListener("dispose",t);const n=i.get(e);void 0!==n&&(n.dispose(),i.delete(e))};e.addEventListener("dispose",t)}i.set(e,r)}return r.texture}class Ww extends Ff{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const i=new Ln;i.isRenderTargetTexture=!0,this._texture=Py(i),this._width=zg(0),this._height=zg(0),this._maxMip=zg(0),this.updateBeforeType=Tf}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,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(t=!0===i.isPMREMTexture||i.mapping===te?i:Hw(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Ow(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=null===this._pmrem||this._pmrem.isRenderTargetTexture?Kb.mul(Hm(t.x,t.y.negate(),t.z)):Kb.mul(t);let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),yw(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const jw=wm(Ww).setParameterLength(1,3),$w=new WeakMap;class Xw extends sT{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const i=n.isTextureNode?n.value:t[n.property],r=this._getPMREMNodeCache(e.renderer);let s=r.get(i);void 0===s&&(s=jw(i),r.set(i,s)),n=s}const i=!0===t.useAnisotropy||t.anisotropy>0?Rx:Gb;let r=ly(n.context(qw(ag,i)).mul(Yb));if(!0===t.useRetroreflection||t.retroreflectivity>0){const e=ly(n.context(Yw(ag,i)).mul(Yb));r=Lg.clamp().mix(r,e)}const s=n.context(Kw(Hb)).mul(Math.PI).mul(Yb),a=ly(s);e.context.radiance.addAssign(r),e.context.iblIrradiance.addAssign(a);const o=e.context.lightingModel.clearcoatRadiance;if(o){const e=n.context(qw(ug,Wb)).mul(Yb),t=ly(e);o.addAssign(t)}}_getPMREMNodeCache(e){let t=$w.get(e);return void 0===t&&(t=new WeakMap,$w.set(e,t)),t}}const qw=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=Db.negate().reflect(t),n=_v(e).mix(n,t).normalize(),n=n.transformDirection(pb)),n),getTextureLevel:()=>e}},Yw=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=_v(e).mix(Db,t).normalize(),n=n.transformDirection(pb)),n),getTextureLevel:()=>e}},Kw=e=>({getUV:()=>e,getTextureLevel:()=>Um(1)}),Zw=new Xs;class Qw extends PT{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(Zw),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Xw(t):null}setupLightingModel(){return new iw}setupSpecular(){const e=yv(Hm(.04),ig.rgb,og);yg.assign(Hm(.04)),bg.assign(e),xg.assign(1)}setupVariants(){const e=this.metalnessNode?Um(this.metalnessNode):Yx;og.assign(e);let t=this.roughnessNode?Um(this.roughnessNode):qx;t=fM({roughness:t}),ag.assign(t),this.setupSpecular(),rg.assign(ig.rgb.mul(e.oneMinus()))}}const Jw=new qs;class eE extends Qw{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.retroreflectivityNode=null,this.anisotropyNode=null,this.setDefaultValues(Jw),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}get useRetroreflection(){return this.retroreflectivity>0||null!==this.retroreflectivityNode}setupSpecular(){const e=this.iorNode?Um(this.iorNode):uS,t=this.specularColorNode?Hm(this.specularColorNode):jx,n=this.specularIntensityNode?Um(this.specularIntensityNode):Wx;Eg.assign(e),yg.assign(ov(gv(Eg.sub(1).div(Eg.add(1))).mul(t),Hm(1)).mul(n)),bg.assign(yv(yg,ig.rgb,og)),xg.assign(yv(n,1,og))}setupLightingModel(){return new iw(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useRetroreflection)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Um(this.clearcoatNode):Zx,t=this.clearcoatRoughnessNode?Um(this.clearcoatRoughnessNode):Qx;lg.assign(e),ug.assign(fM({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Hm(this.sheenNode):tS,t=this.sheenRoughnessNode?Um(this.sheenRoughnessNode):nS;cg.assign(e),hg.assign(t)}if(this.useRetroreflection){const e=this.retroreflectivityNode?Um(this.retroreflectivityNode):yS;Lg.assign(e)}if(this.useIridescence){const e=this.iridescenceNode?Um(this.iridescenceNode):rS,t=this.iridescenceIORNode?Um(this.iridescenceIORNode):sS,n=this.iridescenceThicknessNode?Um(this.iridescenceThicknessNode):aS;dg.assign(e),pg.assign(t),fg.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?km(this.anisotropyNode):iS).toVar();gg.assign(e.length()),Dm(gg.equal(0),()=>{e.assign(km(1,0))}).Else(()=>{e.divAssign(km(gg)),gg.assign(gg.saturate())}),mg.assign(gg.pow2().mix(ag.pow2(),1)),_g.assign(Ax[0].mul(e.x).add(Ax[1].mul(e.y))),vg.assign(Ax[1].mul(e.x).sub(Ax[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Um(this.transmissionNode):oS,t=this.thicknessNode?Um(this.thicknessNode):lS,n=this.attenuationDistanceNode?Um(this.attenuationDistanceNode):cS,i=this.attenuationColorNode?Hm(this.attenuationColorNode):hS;if(Ag.assign(e),Rg.assign(t),Cg.assign(n),Ng.assign(i),this.useDispersion){const e=this.dispersionNode?Um(this.dispersionNode):vS;Pg.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Hm(this.clearcoatNormalNode):Jx}setup(e){e.context.setupClearcoatNormal=()=>Iv(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}}const tE=Nm(({normal:e,lightDirection:t,builder:n})=>{const i=e.dot(t),r=km(i.mul(.5).add(.5),0);if(n.material.gradientMap){const e=lx("gradientMap","texture").context({getUV:()=>r});return Hm(e.r)}{const e=r.fwidth().mul(.5);return yv(Hm(.7),Hm(1),Tv(Um(.7).sub(e.x),Um(.7).add(e.x),r.x))}});class nE extends eM{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const r=tE({normal:Gb,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(r.mul(sM({diffuseColor:ig.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(sM({diffuseColor:ig}))),i.indirectDiffuse.mulAssign(t)}}const iE=new Ks;class rE extends PT{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(iE),this.setValues(e)}setupLightingModel(){return new nE}}const sE=Nm(()=>{const e=Hm(Db.z,0,Db.x.negate()).normalize(),t=Db.cross(e);return km(e.dot(Gb),t.dot(Gb)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),aE=new ta;class oE extends PT{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(aE),this.setValues(e)}setupVariants(e){const t=sE;let n;n=e.material.matcap?lx("matcap","texture").context({getUV:()=>t}):Hm(yv(.2,.8,t.y)),ig.rgb.mulAssign(n.rgb)}}class lE extends Ff{static get type(){return"RotateNode"}constructor(e,t,n="XYZ"){super(),this.positionNode=e,this.rotationNode=t,this._order=n}customCacheKey(){return uf(this._order)}setOrder(e){return this._order=e,this}getOrder(){return this._order}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Zm(e,i,i.negate(),e).mul(n)}{const e=t,i=this._order,r={X:Jm(Xm(1,0,0,0),Xm(0,O_(e.x),U_(e.x),0),Xm(0,U_(e.x).negate(),O_(e.x),0),Xm(0,0,0,1)),Y:Jm(Xm(O_(e.y),0,U_(e.y).negate(),0),Xm(0,1,0,0),Xm(U_(e.y),0,O_(e.y),0),Xm(0,0,0,1)),Z:Jm(Xm(O_(e.z),U_(e.z),0,0),Xm(U_(e.z).negate(),O_(e.z),0,0),Xm(0,0,1,0),Xm(0,0,0,1))};return r[i.charAt(0)].mul(r[i.charAt(1)]).mul(r[i.charAt(2)]).mul(Xm(n,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}}const uE=wm(lE).setParameterLength(2,3),cE=new Nr;class hE extends PT{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(cE),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:i,rotationNode:r,scaleNode:s,sizeAttenuation:a}=this,o=Sb.mul(Hm(i||0));let l=km(bb[0].xyz.length(),bb[1].xyz.length());null!==s&&(l=l.mul(km(s))),n.isPerspectiveCamera&&!1===a&&(l=l.mul(o.z.negate()));let u=Ab.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>new Hv(e,t,n))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=Um(r||eS),h=uE(u,c);return Xm(o.xy.add(h),o.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const dE=new ps,pE=new dn;class fE extends hE{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(dE),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Sb.mul(Hm(e||Rb)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:i,scaleNode:r,sizeNode:s,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==s?km(s):_S;l=l.mul(Hy),n.isPerspectiveCamera&&!0===a&&(l=l.mul(mE.div(Lb.z.negate()))),r&&r.isNode&&(l=l.mul(km(r)));let u=Ab.xy;if(i&&i.isNode){const e=Um(i);u=uE(u,e)}return u=u.mul(l),u=u.div(qy.div(2)),u=u.mul(o.w),o=o.add(Xm(u,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const mE=zg(1).setGroup(Og).onRenderUpdate(function({renderer:e}){const t=e.getSize(pE);this.value=.5*t.y});class gE extends eM{constructor(){super(),this.shadowNode=Um(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){ig.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(ig.rgb)}}const _E=new ks;class vE extends PT{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(_E),this.setValues(e)}setupLightingModel(){return new gE}}tg("vec3"),tg("vec3"),tg("vec3");class yE{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,n)};e()}stop(){this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class bE{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return void 0===n&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.onObjectDispose=()=>{this.dispose()},this.object.addEventListener("dispose",this.onObjectDispose),this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose),null!==this._sourceMaterial&&this._sourceMaterial.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.getNodeBuilderState().hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set,r={};for(const s of e){let e;if(s.node&&s.node.attribute?e=s.node.attribute:(e=t.getAttribute(s.name),void 0!==e&&(e.isInterleavedBufferAttribute?r[s.name]=e.data.uuid:r[s.name]=e.id)),void 0===e)continue;n.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}return this.attributes=n,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:r}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let l=1;if(!0===n.isInstancedBufferGeometry?l=n.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=r.start*u,h=(r.start+r.count)*u;null!==i&&(c=Math.max(c,i.start*u),h=Math.min(h,(i.start+i.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=i.length;e1)&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",uf(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const n=this.geometry.getAttribute(t);if(void 0===n)return!0;const i=n.isInterleavedBufferAttribute?n.data.uuid:n.id;if(e[t]!==i)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=hf(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=hf(e,1)),e=hf(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.object.removeEventListener("dispose",this.onObjectDispose),this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),null!==this._sourceMaterial&&this._sourceMaterial.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const ME=[];class wE{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this._chainMaps={},this._renderObjects=new Set}get(e,t,n,i,r,s,a,o){const l=this.getChainMap(o);ME[0]=e,ME[1]=t,ME[2]=s,ME[3]=r;let u=l.get(ME);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a,o),l.set(ME,u)):(u.camera=i,u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,i,r,s,a,o)):u.version=t.version)),ME[0]=null,ME[1]=null,ME[2]=null,ME[3]=null,u}getChainMap(e="default"){return this._chainMaps[e]||(this._chainMaps[e]=new bE)}dispose(){for(const e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,u,c){const h=this.getChainMap(c),d=new TE(e,t,n,i,r,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),h.delete(d.getChainArray()),this._renderObjects.delete(d)},this._renderObjects.add(d),d}}class EE{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 AE=1,RE=2,CE=3,NE=4,PE=16;class LE extends EE{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return null!==t&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===AE?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===RE?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===CE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===NE&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version=65535?ar:sr)(t,1);return r.version=DE(e),r.__id=IE(e),r}class FE extends EE{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const n=()=>{this.info.memory.geometries--;const i=t.index;null!==i&&this.attributes.delete(i);for(const e of Object.values(t.attributes))this.attributes.delete(e);const r=this.wireframes.get(t);void 0!==r&&this.attributes.delete(r);const s=new Set(Object.values(e.geometry.attributes));for(const t of e.getAttributes())!1===s.has(t)&&this.attributes.delete(t);t.removeEventListener("dispose",n),this._geometryDisposeListeners.delete(t),this.delete(t)};t.addEventListener("dispose",n),this._geometryDisposeListeners.set(t,n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,CE):this.updateAttribute(e,AE);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,RE);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,NE)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=UE(t),e.set(t,n)):n.version===DE(t)&&n.__id===IE(t)||(this.attributes.delete(n),n=UE(t),e.set(t,n)),i=n}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class OE{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new WeakMap}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):Yt("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap=new WeakMap}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const n=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:n,type:t}),this.memory[t]++,this.memory.total+=n,this.memory[t+"Size"]+=n}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){const t=e.byteLength;this.memoryMap.set(e,{size:t,type:"uniformBuffers"}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===de||e.type===he?t=1:e.type===pe||e.type===fe||e.type===ve?t=2:e.type!==me&&e.type!==ge&&e.type!==_e||(t=4);let n=4;e.format===Me||e.format===Ce||e.format===Ne||e.format===Ae||e.format===Re?n=1:e.format===Pe||e.format===Le?n=2:e.format!==we&&e.format!==De||(n=3);let i=t*n;e.type===ye||e.type===be?i=2:e.type!==xe&&e.type!==Se&&e.type!==Te||(i=4);const r=e.width||1,s=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=r*s*a*i;const l=e.mipmaps;if(l&&l.length>0){let e=0;for(let t=0;t>t))*(n.height||Math.max(1,s>>t))*a*i}}o+=e}else e.generateMipmaps&&(o*=1.333);return Math.round(o)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class BE{constructor(e){this.cacheKey=e,this.usedTimes=0}}class kE extends BE{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class zE extends BE{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let VE=0;class GE{constructor(e,t,n,i=null,r=null){this.id=VE++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=r,this.usedTimes=0}}class HE extends EE{constructor(e,t,n){super(),this.backend=e,this.nodes=t,this.info=n,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t,n=null){const{backend:i}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const s=r.pipeline;s&&(s.usedTimes--,s.computeProgram.usedTimes--);const a=this.nodes.getForCompute(e);let o=this.programs.compute.get(a.computeShader);void 0===o&&(s&&0===s.computeProgram.usedTimes&&this._releaseProgram(s.computeProgram),o=new GE(a.computeShader,"compute",e.name,a.transforms,a.nodeAttributes),this.programs.compute.set(a.computeShader,o),i.createProgram(o),this.info.createProgram(o));const l=this._getComputeCacheKey(e,o);let u=this.caches.get(l);void 0===u&&(s&&0===s.usedTimes&&this._releasePipeline(s),u=this._getComputePipeline(e,o,l,t,n)),u.usedTimes++,o.usedTimes++,r.version=e.version,r.pipeline=u}return r.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new GE(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o),this.info.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new GE(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l),this.info.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(r&&0===r.usedTimes&&this._releasePipeline(r),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,i.pipeline=c}return i.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const n=this.backend.get(t);return void 0!==n.pipeline&&null!==n.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,n,i,r){n=n||this._getComputeCacheKey(e,t);let s=this.caches.get(n);return void 0===s&&(s=new zE(n,t),this.caches.set(n,s),this.backend.createComputePipeline(s,i,r)),s}_getRenderPipeline(e,t,n,i,r){i=i||this._getRenderCacheKey(e,t,n);let s=this.caches.get(i);return void 0===s&&(s=new kE(i,t,n),this.caches.set(i,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class WE extends EE{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),n=this.get(e);return!0!==n.initialized&&(this._createBindings(t),n.initialized=!0),t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings,n=this.get(e);return!0===n.initialized&&n.bindings===t||(void 0!==n.bindings&&this._destroyBindings(n.bindings),this._createBindings(t),n.initialized=!0,n.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}updateSharedForRender(e){const t=this.getForRender(e);for(const e of t)for(const t of e.bindings)if((!0===t.isNodeUniformsGroup||!0===t.isNodeUniformBuffer)&&!0===t.groupNode.shared){if(!1===this.nodes.updateGroup(t))continue;t.update()&&this.backend.updateBinding(t),t.updateRanges.length>0&&t.clearUpdateRanges()}}deleteForCompute(e){const t=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(t),this.delete(e)}deleteForRender(e){const t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(const t of e){const n=this.get(t);if(void 0===n.bindGroup){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.createUniformBuffer(e),this.info.createUniformBuffer(e);else if(e.isSampledTexture)this.textures.updateTexture(e.texture);else if(e.isSampler)this.textures.updateSampler(e);else if(e.isStorageBuffer){const t=e.attribute,n=t.isIndirectStorageBufferAttribute?NE:CE;this.attributes.update(t,n)}this.backend.createBindings(t,e,""),n.bindGroup=t,n.usedTimes=1}else n.usedTimes++}}_destroyBindings(e){for(const t of e){const e=this.get(t);if(e.usedTimes--,0===e.usedTimes){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.destroyUniformBuffer(e),this.info.destroyUniformBuffer(e),e.release();else if(e.isSampler){if(!0!==e.isSampledTexture)this.backend.destroySampler(e);else if(null!==e.texture){const n=this.textures.get(e.texture);void 0!==n.bindGroups&&n.bindGroups.delete(t)}e.release()}this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(const t of e)this._update(t,e)}_update(e,t){const{backend:n}=this;let i=!1,r=!0,s="",a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?NE:CE,a=n.get(t);this.attributes.update(e,r),a.attribute!==e&&(a.attribute=e,i=!0),s+=e.id+","}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),l=t.texture,u=this.textures.get(l);o&&(this.textures.updateTexture(l),t.generation!==u.generation&&(t.generation=u.generation,i=!0),u.bindGroups.add(e));if(void 0!==n.get(l).externalTexture||u.isDefaultTexture?r=!1:(s+=l.id+",",a+=l.version),!0===l.isStorageTexture&&!0===l.mipmapsAutoUpdate){const e=this.get(l);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(l)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(l),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t);t.samplerKey!==e&&(t.samplerKey=e,i=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?s:"",a)}}const jE=Object.freeze([]);function $E(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function XE(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 qE(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class YE{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0,this.frameId=-1,this._lastOcclusionObject=null}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,n,i,r,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,i,r,s,a){!0===this.camera.reversedDepth&&(r=-r);const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===e.occlusionTest&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),!0===n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(qE(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(qE(n)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||$E),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||XE),this.transparent.length>1&&this.transparent.sort(t||XE)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:jE);for(let e=this.renderItemsIndex,t=this.renderItems.length;e10&&(t.clear(),this._activeLists.delete(t))}}dispose(){this.lists=new bE,this._activeLists.clear(),this._frameId=-1}}let JE=0;class eA{constructor(){this.id=JE++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new Dn,this.scissor=!1,this.scissorValue=new Dn,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.fullscreenPass=!1,this.isRenderContext=!0}getCacheKey(){return tA(this)}}function tA(e){const{textures:t,activeCubeFace:n,activeMipmapLevel:i}=e,r=[n,i];for(const e of t)r.push(e.id);return cf(r)}class nA{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let i;if(null===e)i="default";else{const t=e.texture.format,n=e.texture.type;i=`${e.textures.length}:${t}:${n}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=i+"-"+(null!==t?t.id:"default")+"-"+n;let s=this._renderContexts[r];return void 0===s&&(s=new eA,s.mrt=t,this._renderContexts[r]=s),null!==e&&(s.sampleCount=0===e.samples?1:e.samples),s.clearDepthValue=this.renderer.getClearDepth(),s.clearStencilValue=this.renderer.getClearStencil(),s}dispose(){this._renderContexts={}}}const iA=new fn;class rA extends EE{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const n=this.get(e),i=0===e.samples?1:e.samples,r=n.depthTextureMips||(n.depthTextureMips={}),s=e.textures,a=this.getSize(s[0]),o=a.width>>t,l=a.height>>t;let u=e.depthTexture||r[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;const d=void 0!==u&&void 0!==u.image&&u.image.depth>1,p=a.depth>1&&(e.useArrayDepthTexture||e.multiview||d);void 0===u&&c&&(u=new gs,u.format=e.stencilBuffer?Re:Ae,u.type=e.stencilBuffer?xe:ge,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.renderTarget=e,r[t]=u),u&&(u.isArrayTexture=p),n.width===a.width&&a.height===n.height||(h=!0,u&&u.renderTarget===e&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l,u.image.depth=p?a.depth:1)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u&&u.renderTarget===e&&(u.needsUpdate=!0),n.sampleCount=i);const f={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){const n=this.get(e);if(!0===n.initialized&&n.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===n.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:he}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;if("requestPaint"in t){if(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image),0===this._htmlTextures.size){const e=this._htmlTextures;t.onpaint=t=>{const n=t&&t.changedElements;for(const t of e)n&&!n.includes(t.image)||(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:s,height:a,depth:o}=this.getSize(e);if(t.width=s,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,s,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),n.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)qt("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)qt("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const s=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!s&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;!0!==n.initialized&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===Sn.enabled&&Sn.getTransfer(e.colorSpace)!==xt&&qt("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=iA){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),e.isHTMLTexture?(t.width=n.offsetWidth||1,t.height=n.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),n=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e{!0===t.isOverrideContextNode&&e.push(t.value.overrideNodes)});const t=new Map(e.flatMap(e=>Array.from(e.entries()))),n=super.getFlowContextData();return n.overrideNodes=t,n}}qf("overrideNode",(e,t,n)=>function(e,t=null,n=null){if(t&&t.isNode){const e=t;t=()=>e}return new aA(new Map([[e,t]]),n)}(t,n,e)),qf("overrideNodes",(e,t)=>function(e,t=null){const n=new Map;for(const[t,i]of e){const e=null!==i?"function"==typeof i?i:()=>i:null;n.set(t,e)}return new aA(n,t)}(t,e));class oA extends eg{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const n=this.getNodeType(e),i=e.getStructTypeNode(n);let r;return null!==i?r=i.getMemberType(e,t):(Yt(`TSL: Member "${t}" not found in struct "${n}".`,new of),r="float"),r}getHash(){return String(this.id)}generate(){return this.name}}class lA extends Df{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=-1){if(!0!==e.isNode)return Yt("TSL: Invalid node added to stack.",new of),this;if(-1===t)if(this._currentNode){let e=this._nodeDataLibrary.get(this._currentNode);void 0===e&&(e={delta:0},this._nodeDataLibrary.set(this._currentNode,e)),e.delta++,t=this.nodes.indexOf(this._currentNode)+e.delta}else t=this.nodes.length;return this.nodes.splice(t,0,e),this}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const n=new bm(t);return this._currentCond=Av(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){const n=new bm(t),i=Av(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new bm(e),this}Switch(e){return this._expressionNode=xm(e),this}Case(...e){const t=[];if(e.length>=2)for(let n=0;nI_(Um(52.9829189).mul(I_(pv(e,km(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),vA=Nm(([e,t,n])=>{const i=Um(2.399963229728653),r=C_(Um(e).add(.5).div(Um(t))),s=Um(e).mul(i).add(n);return km(O_(s),U_(s)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]}),yA=new Bn,bA=zg(0).setGroup(Og).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),xA=zg(1).setGroup(Og).onRenderUpdate(({scene:e})=>e.backgroundIntensity),SA=zg(new Bn).setGroup(Og).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping||e.backgroundNode&&e.backgroundNode.isNode?yA.makeRotationFromEuler(e.backgroundRotation).transpose():yA.identity(),yA}),TA=Nm(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),MA=Nm(([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"}]}),wA=Nm(([e,t])=>{const n=(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 n.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),EA=Nm(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),AA=Nm(([e,t])=>{const n=Qm(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Qm(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=EA(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),RA=Qm(Hm(1.6605,-.1246,-.0182),Hm(-.5876,1.1329,-.1006),Hm(-.0728,-.0083,1.1187)),CA=Qm(Hm(.6274,.0691,.0164),Hm(.3293,.9195,.088),Hm(.0433,.0113,.8956)),NA=Nm(([e])=>{const t=Hm(e).toVar(),n=Hm(t.mul(t)).toVar(),i=Hm(n.mul(n)).toVar();return Um(15.5).mul(i.mul(n)).sub(Yg(40.14,i.mul(t))).add(Yg(31.96,i).sub(Yg(6.868,n.mul(t))).add(Yg(.4298,n).add(Yg(.1191,t).sub(.00232))))}),PA=Nm(([e,t])=>{const n=Hm(e).toVar(),i=Qm(Hm(.856627153315983,.137318972929847,.11189821299995),Hm(.0951212405381588,.761241990602591,.0767994186031903),Hm(.0482516061458583,.101439036467562,.811302368396859)),r=Qm(Hm(1.1271005818144368,-.1413297634984383,-.14132976349843826),Hm(-.11060664309660323,1.157823702216272,-.11060664309660294),Hm(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=Um(-12.47393),a=Um(4.026069);return n.mulAssign(t),n.assign(CA.mul(n)),n.assign(i.mul(n)),n.assign(lv(n,1e-10)),n.assign(R_(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(bv(n,0,1)),n.assign(NA(n)),n.assign(r.mul(n)),n.assign(mv(lv(Hm(0),n),Hm(2.2))),n.assign(RA.mul(n)),n.assign(bv(n,0,1)),n}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),LA=Nm(([e,t])=>{const n=Um(.76),i=Um(.15);e=e.mul(t);const r=ov(e.r,ov(e.g,e.b)),s=Av(r.lessThan(.08),r.sub(Yg(6.25,r.mul(r))),.04);e.subAssign(s);const a=lv(e.r,lv(e.g,e.b));Dm(a.lessThan(n),()=>e);const o=qg(1,n),l=qg(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=qg(1,Kg(1,i.mul(a.sub(l)).add(1)));return yv(e,Hm(l),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class DA extends Df{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e,"void");const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.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 IA extends DA{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);if(""!==i){const t=e.getDataFromNode(this);!0!==t.declarationRegistered&&(s.name=i,e.registerDeclaration(s),t.declarationRegistered=!0)}const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function UA(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||Lb.z).negate()}const FA=Nm(([e,t],n)=>{const i=UA(n);return Tv(e,t,i)}),OA=Nm(([e],t)=>{const n=UA(t);return e.mul(e,n,n).negate().exp().oneMinus()}),BA=Nm(([e,t])=>Xm(t.toFloat().mix(Tg.rgb,e.toVec3()),Tg.a));let kA;function zA(e){kA=kA||new WeakMap;let t=kA.get(e);return void 0===t&&kA.set(e,t={}),t}function VA(e){const t=zA(e);return t.shadowMatrix||(t.shadowMatrix=zg("mat4").setGroup(Og).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function GA(e){const t=zA(e);return t.position||(t.position=zg(new fn).setGroup(Og).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld)))}function HA(e){const t=zA(e);return t.viewPosition||(t.viewPosition=zg(new fn).setGroup(Og).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new fn,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}const WA=e=>db.transformDirection(GA(e).sub(function(e){const t=zA(e);return t.targetPosition||(t.targetPosition=zg(new fn).setGroup(Og).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),jA=tg("vec3","totalDiffuse"),$A=tg("vec3","totalSpecular"),XA=tg("vec3","outgoingLight"),qA=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},YA=new WeakMap,KA=[];class ZA extends Df{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=jA,this.totalSpecularNode=$A,this.outgoingLightNode=XA,this._lights=[],this.global=!0}customCacheKey(){const e=this.getBuiltinLights();for(let t=0;te.sort((e,t)=>e.id-t.id))([...e.context.materialLightings,...this.getBuiltinLights()]),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(e);else{let i=null;if(null!==n&&(i=qA(e.id,n)),null===i){const t=r.getLightNodeClass(e.constructor);if(null===t){qt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===YA.has(e)&&YA.set(e,new t(e)),i=YA.get(e)}t.push(i)}return t}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...n,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){const t=e.getDataFromNode(this);return void 0===t.lightNodes&&(t.lightNodes=this.setupLightsNode(e)),t.lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,r=i.lightingModel,s=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,r.start(e);const{backdrop:l,backdropAlpha:u}=i,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let f=c.add(d);null!==l&&(f=Hm(null!==u?u.mix(f,l):l)),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),r.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this}getLights(){return this._lights}getBuiltinLights(){return this._lights}get hasLights(){return this._lights.length>0}}const QA=new WeakMap,JA=new bE,eR=[];class tR extends Df{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Tf,this.isShadowBaseNode=!0}getShadowMaterial(){return(e=>{let t=QA.get(e);return void 0===t&&(t=new PT,t.colorNode=Xm(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,QA.set(e,t)),t})(this.light)}disposeShadowMaterial(){(e=>{const t=QA.get(e);void 0!==t&&(t.dispose(),QA.delete(e))})(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){const n=e.shadowMap.type,i=e.getMRT();return((e,t,n,i)=>{eR[0]=e,eR[1]=t;let r=JA.get(eR);return void 0!==r&&r.shadowType===n&&r.useVelocity===i||(r=(r,s,a,o,l,u,c,h,d)=>{(!0===r.castShadow||r.receiveShadow&&3===n)&&(i&&(vf(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,s.overrideMaterial,u),e.renderObject(r,s,a,o,l,u,c,h,d),r.onAfterShadow(e,r,a,t.camera,o,s.overrideMaterial,u))},r.shadowType=n,r.useVelocity=i,JA.set(eR,r)),eR[0]=null,eR[1]=null,r})(e,t,n,!!i&&i.has("velocity"))}setupShadowPosition({context:e,material:t}){nR.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Nb)}}const nR=tg("vec3","shadowPositionWorld"),iR=Nm(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let i=Py(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(n)),i.compare(t.z)}),rR=Nm(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:i})=>{const r=(t,n)=>{let r=Py(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(n)},s=ax("mapSize","vec2",n).setGroup(Og),a=ax("radius","float",n).setGroup(Og),o=km(1).div(s),l=a.mul(o.x),u=_A($y.xy).mul(6.28318530718);return Xg(r(t.xy.add(vA(0,5,u).mul(l)),t.z),r(t.xy.add(vA(1,5,u).mul(l)),t.z),r(t.xy.add(vA(2,5,u).mul(l)),t.z),r(t.xy.add(vA(3,5,u).mul(l)),t.z),r(t.xy.add(vA(4,5,u).mul(l)),t.z)).mul(.2)}),sR=Nm(({depthTexture:e,shadowCoord:t,depthLayer:n},i)=>{let r=Py(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(n)),r=r.rg;const s=r.x,a=lv(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?uv(s,t.z):uv(t.z,s),l=Um(1).toVar();return Dm(o.notEqual(1),()=>{const e=t.z.sub(s);let n=a.div(a.add(e.mul(e)));n=bv(qg(n,.3).div(.65)),l.assign(lv(o,n))}),l}),aR=Nm(({samples:e,radius:t,size:n,shadowPass:i,depthLayer:r})=>{const s=Um(0).toVar("meanVertical"),a=Um(0).toVar("squareMeanVertical"),o=e.lessThanEqual(Um(1)).select(Um(0),Um(2).div(e.sub(1))),l=e.lessThanEqual(Um(1)).select(Um(0),Um(-1));JS({start:Fm(0),end:Fm(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(Um(e).mul(o));let c=i.sample(Xg($y.xy,km(0,u).mul(t)).div(n));i.value.isArrayTexture&&(c=c.depth(r)),c=c.x,s.addAssign(c),a.addAssign(c.mul(c))}),s.divAssign(e),a.divAssign(e);const u=C_(a.sub(s.mul(s)).max(0));return km(s,u)}),oR=Nm(({samples:e,radius:t,size:n,shadowPass:i,depthLayer:r})=>{const s=Um(0).toVar("meanHorizontal"),a=Um(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(Um(1)).select(Um(0),Um(2).div(e.sub(1))),l=e.lessThanEqual(Um(1)).select(Um(0),Um(-1));JS({start:Fm(0),end:Fm(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(Um(e).mul(o));let c=i.sample(Xg($y.xy,km(u,0).mul(t)).div(n));i.value.isArrayTexture&&(c=c.depth(r)),s.addAssign(c.x),a.addAssign(Xg(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=C_(a.sub(s.mul(s)).max(0));return km(s,u)}),lR=[iR,rR,null,sR];let uR;const cR=new mA;class hR extends tR{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r,depthLayer:s}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:n,shadowCoord:i,shadow:r,depthLayer:s});return a.select(o,Um(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,r=n.biasNode||ax("bias","float",n).setGroup(Og);let s,a=t;if(n.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z;else{const e=a.w;a=a.xy.div(e);const t=ax("near","float",n.camera).setGroup(Og),i=ax("far","float",n.camera).setGroup(Og);s=TT(e.negate(),t,i)}return a=Hm(a.x,a.y.oneMinus(),i.reversedDepthBuffer?s.sub(r):s.add(r)),a}getShadowFilterFn(e){return lR[e]}setupRenderTarget(e,t){const n=new gs(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?Ct:Et;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=n,{shadowMap:i,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:i,shadow:r}=this,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,l=t.hasCompatibility(Bt);if(1===o&&l?(s.minFilter=le,s.magFilter=le):(s.minFilter=se,s.magFilter=se),r.camera.coordinateSystem=n.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Pe,type:ve,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Pe,type:ve,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Pe,type:ve,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Pe,type:ve,depthBuffer:!1}));let t=Py(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let n=Py(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(n=n.depth(this.depthLayer));const i=ax("blurSamples","float",r).setGroup(Og),o=ax("radius","float",r).setGroup(Og),l=ax("mapSize","vec2",r).setGroup(Og),u=Cv(e.getSharedContext());let c=this.vsmMaterialVertical||(this.vsmMaterialVertical=new PT);c.contextNode=u,c.fragmentNode=aR({samples:i,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}),c.name="VSMVertical",c=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new PT),c.contextNode=u,c.fragmentNode=oR({samples:i,radius:o,size:l,shadowPass:n,depthLayer:this.depthLayer}),c.name="VSMHorizontal"}const u=ax("intensity","float",r).setGroup(Og),c=ax("normalBias","float",r).setGroup(Og),h=VA(i),d=Hb.mul(c);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=h.mul(nR.add(d));else{p=zg("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(h.value,e.matrixWorld)).mul(Rb).add(h.mul(Xm(d,0)))}const f=this.setupShadowCoord(e,p),m=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,_=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:g,shadowCoord:f,shadow:r,depthLayer:this.depthLayer});let v,y;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?v=rx(a.texture,f.xyz):(v=Py(a.texture,f),s.isArrayTexture&&(v=v.depth(this.depthLayer)))),y=v?yv(1,_.rgb.mix(v,1),u.mul(v.a)).toVar():yv(1,_,u).toVar(),this.shadowMap=a,this.shadow.map=a;const b=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return v&&y.toInspector(`${b} / Color`,()=>this.shadowMap.texture.isCubeTexture?rx(this.shadowMap.texture,jT()):Py(this.shadowMap.texture)),y.toInspector(`${b} / Depth`,()=>{const e=ax("near","float",this.shadow.camera),t=ax("far","float",this.shadow.camera);let n,i;return n=this.shadowMap.texture.isCubeTexture?rx(this.shadowMap.depthTexture,jT()).r:Py(this.shadowMap.depthTexture).r,i=this.shadow.camera.isPerspectiveCamera?ST(n,e,t):bT(n,e,t),i=yT(i,e,t),i.oneMinus()})}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Nm(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),null===n&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=s.name;s.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(s,t.camera),s.name=a}updateShadow(e){const{shadowMap:t,shadow:n}=this,{renderer:i,scene:r,camera:s}=e,a=i.shadowMap.type,o=t.depthTexture.version;this._depthVersionCached=o;const l=n.camera.layers.mask;4294967294&n.camera.layers.mask||(n.camera.layers.mask=s.layers.mask);const u=i.getRenderObjectFunction();uR=function(e,t,n){return n=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,n=gA(e,n)),n}(i,r,uR),r.overrideMaterial=this.getShadowMaterial(),i.setRenderObjectFunction(this.getShadowRenderObjectFunction(i,this.shadow||this.light.shadow)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(u),3===a&&!0!==n.isPointLightShadow&&this.vsmPass(i),n.camera.layers.mask=l,function(e,t,n){!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,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(i,r,uR)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),cR.material=this.vsmMaterialVertical,cR.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),cR.material=this.vsmMaterialHorizontal,cR.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.disposeShadowMaterial(),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){if(!0===e.renderer._isPreCompiling)return;const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId.get(e.camera)===e.frameId&&(n=!1),this._cameraFrameId.set(e.camera,e.frameId)),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const dR=new yi,pR=new Bn,fR=new fn,mR=new fn,gR=[new fn(1,0,0),new fn(-1,0,0),new fn(0,-1,0),new fn(0,1,0),new fn(0,0,1),new fn(0,0,-1)],_R=[new fn(0,-1,0),new fn(0,-1,0),new fn(0,0,-1),new fn(0,0,1),new fn(0,-1,0),new fn(0,-1,0)],vR=[new fn(1,0,0),new fn(-1,0,0),new fn(0,1,0),new fn(0,-1,0),new fn(0,0,1),new fn(0,0,-1)],yR=[new fn(0,-1,0),new fn(0,-1,0),new fn(0,0,1),new fn(0,0,-1),new fn(0,-1,0),new fn(0,-1,0)],bR=Nm(({depthTexture:e,bd3D:t,dp:n})=>rx(e,t).compare(n)),xR=Nm(({depthTexture:e,bd3D:t,dp:n,shadow:i})=>{const r=ax("radius","float",i).setGroup(Og),s=ax("mapSize","vec2",i).setGroup(Og),a=r.div(s.x),o=X_(t),l=D_(fv(t,o.x.greaterThan(o.z).select(Hm(0,1,0),Hm(1,0,0)))),u=fv(t,l),c=_A($y.xy).mul(6.28318530718),h=vA(0,5,c),d=vA(1,5,c),p=vA(2,5,c),f=vA(3,5,c),m=vA(4,5,c);return rx(e,t.add(l.mul(h.x).add(u.mul(h.y)).mul(a))).compare(n).add(rx(e,t.add(l.mul(d.x).add(u.mul(d.y)).mul(a))).compare(n)).add(rx(e,t.add(l.mul(p.x).add(u.mul(p.y)).mul(a))).compare(n)).add(rx(e,t.add(l.mul(f.x).add(u.mul(f.y)).mul(a))).compare(n)).add(rx(e,t.add(l.mul(m.x).add(u.mul(m.y)).mul(a))).compare(n)).mul(.2)}),SR=Nm(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:i},r)=>{const s=n.xyz.toConst(),a=s.abs().toConst(),o=a.x.max(a.y).max(a.z),l=zg("float").setGroup(Og).onRenderUpdate(()=>i.camera.near),u=zg("float").setGroup(Og).onRenderUpdate(()=>i.camera.far),c=ax("bias","float",i).setGroup(Og),h=Um(1).toVar();return Dm(o.sub(u).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{let n;r.renderer.reversedDepthBuffer?(n=((e,t,n)=>t.mul(e.add(n)).div(e.mul(t.sub(n))))(o.negate(),l,u),n.subAssign(c)):r.renderer.logarithmicDepthBuffer?(n=TT(o.negate(),l,u),n.addAssign(c)):(n=xT(o.negate(),l,u),n.addAssign(c));const a=s.normalize();h.assign(e({depthTexture:t,bd3D:a,dp:n,shadow:i}))}),h});class TR extends hR{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?bR:xR}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r}){return SR({filterFn:t,depthTexture:n,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const n=new _s(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?Ct:Et;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=n,{shadowMap:i,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e,a=t.camera,o=t.matrix,l=r.coordinateSystem===Ut,u=l?gR:vR,c=l?_R:yR;n.setSize(t.mapSize.width,t.mapSize.width);const h=r.autoClear,d=r.getClearColor(dR),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(n,e),r.clear();const l=i.distance||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),fR.setFromMatrixPosition(i.matrixWorld),a.position.copy(fR),mR.copy(a.position),mR.add(u[e]),a.up.copy(c[e]),a.lookAt(mR),a.updateMatrixWorld(),o.makeTranslation(-fR.x,-fR.y,-fR.z),pR.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(pR,a.coordinateSystem,a.reversedDepth);const h=s.name;s.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(s,a),s.name=h}r.autoClear=h,r.setClearColor(d,p)}}class MR extends sT{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new yi,this.colorNode=e&&e.colorNode||zg(this.color).setGroup(Og),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Sf,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return HA(this.light).sub(e.context.positionView||Lb)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new hR(e,t))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?xm(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const wR=Nm(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const i=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)});class ER extends MR{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=zg(0).setGroup(Og),this.decayExponentNode=zg(2).setGroup(Og)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new TR(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:i})=>{const r=t.normalize(),s=t.length(),a=wR({lightDistance:s,cutoffDistance:n,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const AR=Nm(([e,t])=>{const n=e.x,i=e.y,r=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(i)),s=s.add(t.element(2).mul(1.023328).mul(r)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(i)),s=s.add(t.element(5).mul(.858086).mul(i).mul(r)),s=s.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(r)),s=s.add(t.element(8).mul(.429043).mul(Yg(n,n).sub(Yg(i,i)))),s}),RR=new sA;class CR extends EE{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(RR),RR.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(RR),RR.a=1,s=!0;else if(!0===r.isNode){const o=this.get(e),l=r;RR.copy(i._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=Xm(l).mul(xA).context({getUV:()=>SA.mul(Vb),getTextureLevel:()=>bA}),d=cb.element(3).element(3).equal(1),p=Kg(1,cb.element(1).element(1)).mul(3),f=d.select(Rb.mul(p),Rb),m=Sb.mul(Xm(f,0));let g=cb.mul(Xm(m.xyz,1));g=g.setZ(g.w);const _=new PT;function v(){r.removeEventListener("dispose",v),u.material.dispose(),u.geometry.dispose()}_.name="Background.material",_.side=1,_.depthTest=!1,_.depthWrite=!1,_.allowOverride=!1,_.fog=!1,_.lights=!1,_.vertexNode=g,_.colorNode=h,o.backgroundMeshNode=h,o.backgroundMesh=u=new qr(new Os(1,32,32),_),u.frustumCulled=!1,u.name="Background.mesh",r.addEventListener("dispose",v)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=Xm(l).mul(xA),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else Yt("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?RR.set(0,0,0,1):"alpha-blend"===a&&RR.set(0,0,0,0),!0===i.autoClear||!0===s){const y=n.clearColorValue;y.r=RR.r,y.g=RR.g,y.b=RR.b,y.a=RR.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(y.r*=y.a,y.g*=y.a,y.b*=y.a),n.depthClearValue=i.getClearDepth(),n.stencilClearValue=i.getClearStencil(),n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let NR=0;class PR{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=NR++}}class LR{constructor(e,t,n,i,r,s,a,o,l,u,c=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=c,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.hardwareClipping=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new PR(t.name,[]);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class DR{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class IR{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}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 UR{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class FR extends UR{constructor(e,t,n=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=i}}class OR{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let BR=0;class kR{constructor(e=null){this.id=BR++,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 zR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class VR{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class GR extends VR{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class HR extends VR{constructor(e,t=new dn){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class WR extends VR{constructor(e,t=new fn){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class jR extends VR{constructor(e,t=new Dn){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class $R extends VR{constructor(e,t=new yi){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class XR extends VR{constructor(e,t=new $a){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class qR extends VR{constructor(e,t=new _n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class YR extends VR{constructor(e,t=new Bn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class KR extends GR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ZR extends HR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class QR extends WR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class JR extends jR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class eC extends $R{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class tC extends XR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class nC extends qR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class iC extends YR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let rC=0;const sC=new WeakMap,aC=new WeakMap,oC=new WeakMap,lC=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),uC=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0"),cC=e=>{if(e.writeUsageCount>0)return!0;if(void 0!==e.subBuildsCache)for(const t in e.subBuildsCache)if(cC(e.subBuildsCache[t]))return!0;return!1};class hC{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.compute=null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=uA(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new kR,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:rC++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,n){return new In(e,t,n)}createCubeRenderTarget(e,t){return new $T(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){const t=this.renderer.getRenderTarget();return null!==t?gf(t.textures[e]):"vec4"}getOutputStructName(){}_getBindGroup(e,t){const n=t[0].groupNode;let i,r=n.shared;if(r)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)n+=t.nodeUniform.node.id}else n+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let s=sC.get(r);void 0===s&&(s=new Map,sC.set(r,s));const a=uf(n);i=s.get(a),void 0===i&&(i=new PR(e,t),s.set(a,i))}else i=new PR(e,t);return i}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of Cf)for(const i in n[e]){const r=n[e][i],s=t[i]||(t[i]=[]);for(const e of r)!1===s.includes(e)&&s.push(e)}e=[];for(const n in t){const i=t[n],r=this._getBindGroup(n,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=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${uC(t.r)}, ${uC(t.g)}, ${uC(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`THREE.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 n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new DR(e,t);return this.registerDeclaration(i),n.push(i),i}getPropertyName(e){return e.name}isReservedKeyword(){return!1}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;return!0===e.isDepthTexture?"float":t===me?"int":t===ge?"uint":"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let n=ff(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return lC.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof or||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("THREE.NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=uA(this.stack);const e=Lm();return this.stacks.push(e),Pm(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Pm(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);void 0===i&&(i={},n.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];if(0===this.subBuildLayers.length)return r;const s=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=s),r}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t,n=null){const i=this.getDataFromNode(e,"vertex");let r=i.bufferAttribute;if(void 0===r){const s=this.uniforms.index++;null===n&&(n="nodeAttribute"+s),r=new DR(n,t,e),this.bufferAttributes.push(r),i.bufferAttribute=r}return r}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let s=r.structType;if(void 0===s){const a=this.structs.index++;null===n&&(n="StructType"+a),s=new zR(n,t),this.structs[i].push(s),this.types[i][n]=e,r.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new IR(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),this.registerDeclaration(s),r.uniform=s}return s}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,r=!1){const s=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",s.subBuilds);let o=s[a];if(void 0===o){const l=r?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),c=this.vars[l]||(this.vars[l]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+c,this.vars[l]++),"variable"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds));const h=e.getArrayCount(this);o=new UR(t,n,r,h),r||u.push(o),this.registerDeclaration(o),s[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this),i=null,r=null){const s=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",s.subBuilds);let o=s[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds)),o=new FR(t,n,i,r),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),i=this.renderer.debug.diagnostics.keywords,r=e.name;let s=r,a=this.getPropertyName(e),o=1;for(;i&&this.isReservedKeyword(s)||void 0!==n[a];)s=r+"_"+o++,e.name=s,a=this.getPropertyName(e);s!==r&&qt(`TSL: Declaration name '${r}' of '${e.type}' is a reserved keyword or already in use. Renamed to '${s}'.`),n[a]=e}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new OR("nodeCode"+s,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,s=t;for(;s;){if(!0===i.get(s)){r=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(r)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),s=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),s.set(n,!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),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=this.renderer.backend;let n=aC.get(t);void 0===n&&(n=new WeakMap,aC.set(t,n));let i=n.get(e);if(void 0===i){i=new IA;const t=this.currentFunctionNode;this.currentFunctionNode=i,i.code=this.buildFunctionCode(e),this.currentFunctionNode=t,n.set(e,i)}return i}flowShaderNode(e){const t=e.layout,n={[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)n[e.name]=new oA(e.type,e.name);e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,n=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,n);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new kR,this.stack=uA();for(const n of Rf)this.setBuildStage(n),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.declarations=r,this.cache=s,this.stack=o,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){qt("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.tab,s=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=l;let u=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,n);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,u=r}else u=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=r,this.context=o,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){qt("Abstract function.")}getVaryings(){qt("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e,t=!1){const n=[],i=this.vars[e];if(void 0!==i)for(const e of i)n.push(`${this.getVar(e.type,e.name,e.count)};`);return n.join(t?"\n":"\n\t")}getUniforms(){qt("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}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(){qt("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(n.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n,i;return n=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=n?e?n+"_"+e:n:e,i}prebuild(){const{renderer:e,material:t}=this;if(!0===e.contextNode.isContextNode?this.context={...this.context,...e.contextNode.getFlowContextData()}:Yt('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),t&&t.contextNode&&(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:Yt('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==t){let n=e.library.fromMaterial(t);null===n&&(Yt(`NodeBuilder: Material "${t.type}" is not compatible.`),n=new PT),n.build(this)}else this.addFlow("compute",this.compute)}build(){this.prebuild();for(const e of Rf){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Cf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(const e of Rf){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Cf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this);await Zt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=oC.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let i=n.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new KR(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new ZR(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new QR(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new JR(e);else if("color"===t)i=new eC(e);else if("mat2"===t)i=new tC(e);else if("mat3"===t)i=new nC(e);else{if("mat4"!==t)throw new Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);i=new iC(e)}n.cache=i}return i}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return 16===i&&9===r?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?(e="bool"===n?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),n)):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${e} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||null!==this.object&&!0===vf(this.object).useVelocity}}class dC{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,this.compute=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(this),n=e.updateReference(this);if(t===Sf){const t=this._getMaps(this.updateBeforeMap,n);if(t.frameId!==this.frameId){const n=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=n)}}else if(t===Tf){const t=this._getMaps(this.updateBeforeMap,n);if(t.renderId!==this.renderId){const n=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=n)}}else t===Mf&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(this),n=e.updateReference(this);if(t===Sf){const t=this._getMaps(this.updateAfterMap,n);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Tf){const t=this._getMaps(this.updateAfterMap,n);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===Mf&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(this),n=e.updateReference(this);if(t===Sf){const t=this._getMaps(this.updateMap,n);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Tf){const t=this._getMaps(this.updateMap,n);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===Mf&&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 pC{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}pC.isNodeFunctionInput=!0;class fC extends MR{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class mC extends MR{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:WA(this.light),lightColor:e}}}class gC extends MR{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=GA(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=zg(new yi).setGroup(Og)}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:n,lightDirectionNode:i}=this,r=Hb.dot(i).mul(.5).add(.5),s=yv(n,t,r);e.context.irradiance.addAssign(s)}}class _C extends MR{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=zg(0).setGroup(Og),this.penumbraCosNode=zg(0).setGroup(Og),this.cutoffDistanceNode=zg(0).setGroup(Og),this.decayExponentNode=zg(0).setGroup(Og),this.colorNode=zg(this.color).setGroup(Og)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:n,penumbraCosNode:i}=this;return Tv(n,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return void 0===n&&(n=function(e,t=Nb){const n=VA(e).mul(t);return n.xyz.div(n.w)}(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(WA(r)),l=this.getSpotAttenuation(e,o),u=s.length(),c=wR({lightDistance:u,cutoffDistance:n,decayExponent:i});let h,d,p=t.mul(l).mul(c);if(r.colorNode?(d=this.getLightCoord(e),h=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),h=Py(r.map,d.xy).onRenderUpdate(()=>r.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class vC extends _C{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){const n=this.light.iesMap;let i=null;if(n&&!0===n.isTexture){const e=t.acos().mul(1/Math.PI);this._iesTextureNode=Py(n,km(e,0),0),i=this._iesTextureNode.r}else i=super.getSpotAttenuation(e,t);return i}update(e){super.update(e),null!==this._iesTextureNode&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}}class yC extends MR{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new fn);this.lightProbe=Oy(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=AR(Hb,this.lightProbe);e.context.irradiance.addAssign(t)}}const bC=Nm(([e,t])=>{const n=e.abs().sub(t);return Y_(lv(n,0)).add(ov(lv(n.x,n.y),0))});class xC extends _C{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=Um(0),n=this.penumbraCosNode,i=VA(this.light).mul(e.context.positionWorld||Nb);return Dm(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=bC(e.xy.sub(km(.5)),km(.5)),s=Kg(-1,qg(1,H_(n)).sub(1));t.assign(xv(r.mul(-2).mul(s)))}),t}}const SC=new Bn,TC=new Bn;let MC=null;class wC extends MR{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=zg(new fn).setGroup(Og),this.halfWidth=zg(new fn).setGroup(Og),this.updateType=Tf}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;TC.identity(),SC.copy(t.matrixWorld),SC.premultiply(n),TC.extractRotation(SC),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(TC),this.halfHeight.value.applyMatrix4(TC)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=Py(MC.LTC_FLOAT_1),n=Py(MC.LTC_FLOAT_2)):(t=Py(MC.LTC_HALF_1),n=Py(MC.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:HA(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){MC=e}}class EC{parseFunction(){qt("Abstract function.")}}class AC{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){qt("Abstract function.")}}AC.isNodeFunction=!0;const RC=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,CC=/[a-z_0-9]+/gi,NC="#pragma main";class PC extends AC{constructor(e){const{type:t,inputs:n,name:i,precision:r,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(NC),n=(-1!==t?e.slice(t+12):e).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,""),i=n.match(RC);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=CC.exec(r));)s.push(a);const o=[];let l=0;for(;l{let n=this._createNodeBuilder(e,e.material);try{t?await n.buildAsync():n.build()}catch(i){n=this._createNodeBuilder(e,new PT),t?await n.buildAsync():n.build(),Yt("TSL: "+i)}return n};if(t)return a().then(e=>(i=this._createNodeBuilderState(e),r.set(s,i),i.usedTimes++,n.nodeBuilderState=i,i));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(n){t=this._createNodeBuilder(e,new PT),t.build();let i=n.stackTrace;!i&&n.stack&&(i=new of(n.stack)),Yt("TSL: "+n,i)}i=this._createNodeBuilderState(t),r.set(s,i)}}i.usedTimes++,n.nodeBuilderState=i}return i}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(void 0!==t.nodeBuilderState)return t.nodeBuilderState;const n=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(n);return void 0!==i?(i.usedTimes++,t.nodeBuilderState=i,i):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e,t=!1){const n=this.get(e);let i=n.nodeBuilderState;if(void 0===i||n.version!==e.version){const r=this.backend.createNodeBuilder(null,this.renderer);r.compute=e;const s=this.renderer.debug.onNodeBuilderCreated;if(null!==s&&s(r,e),t)return r.buildAsync().then(()=>(i=this._createNodeBuilderState(r),n.nodeBuilderState=i,n.version=e.version,i));r.build(),i=this._createNodeBuilderState(r),n.nodeBuilderState=i,n.version=e.version}return i}getForComputeAsync(e){const t=this.getForCompute(e,!0);return t.then?t:Promise.resolve(t)}_createNodeBuilderState(e){return new LR(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(!1===this.renderer.lighting.enabled)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){DC[0]=e,DC[1]=t;const n=this.renderer.info.calls,i=this.callHashCache.get(DC)||{};if(i.callId!==n){if(IC.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),IC.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){IC.push(t.getCacheKey(!0)),IC.push(this.renderer.shadowMap.enabled?1:0),IC.push(this.renderer.shadowMap.type);const n=this.getEnvironmentNode(e);n&&IC.push(n.getCacheKey())}const r=this.getFogNode(e);r&&IC.push(r.getCacheKey()),i.callId=n,i.cacheKey=cf(IC),this.callHashCache.set(DC,i),IC.length=0}return DC[0]=null,DC[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||i){const r=this.getCacheNode("background",n,()=>{if(!0===n.isCubeTexture||n.mapping===J||n.mapping===ee||n.mapping===te){if(e.backgroundBlurriness>0||n.mapping===te)return jw(n);{let e;return e=!0===n.isCubeTexture?rx(n):Py(n),ZT(e)}}if(!0===n.isTexture)return Py(n,Wy.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&Yt("WebGPUNodes: Unsupported background configuration.",n)},i);t.backgroundNode=r,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=r.get(t);if(void 0===s||i){if(void 0===s&&!0===t.isTexture){const e=()=>{t.removeEventListener("dispose",e);const n=r.get(t);void 0!==n&&(r.delete(t),n.dispose())};t.addEventListener("dispose",e)}s=n(),r.set(t,s)}return s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const e=ax("color","color",n).setGroup(Og),t=ax("density","float",n).setGroup(Og);return BA(e,OA(t))}if(n.isFog){const e=ax("color","color",n).setGroup(Og),t=ax("near","float",n).setGroup(Og),i=ax("far","float",n).setGroup(Og);return BA(e,FA(t,i))}Yt("Renderer: Unsupported fog configuration.",n)});t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,()=>!0===n.isCubeTexture?rx(n):!0===n.isTexture?Py(n):void Yt("Nodes: Unsupported environment configuration.",n));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null,s=null){const a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=n,a.camera=i,a.material=r,a.compute=s,a}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getNodeFrameForCompute(e){return this.getNodeFrame(this.renderer,null,null,null,null,e)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;let n;return n=e.isArrayTexture?this.backend.isWebGLBackend?Py(e,Wy).depth(ky("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Py(e,Wy).depth(UC).renderOutput(t.toneMapping,t.currentColorSpace):Py(e,Wy).renderOutput(t.toneMapping,t.currentColorSpace),n}setOutputLayerIndex(e){UC.value=e}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateBeforeForCompute(e){const t=this.getForCompute(e);for(const n of t.updateBeforeNodes)this.getNodeFrameForCompute(e).updateBeforeNode(n)}updateAfterForCompute(e){const t=this.getForCompute(e);for(const n of t.updateAfterNodes)this.getNodeFrameForCompute(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new dC,this.nodeBuilderCache=new Map,this.cacheLib={}}}const OC=new Ar;let BC=0;class kC{constructor(e=null){this.id=BC++,this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new Bn,this.viewNormalMatrix=new _n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,n){const i=e.length;for(let r=0;rgy(e,n.toneMapping,n.outputColorSpace),...r.getFlowContextData()}),YC.set(r,s))}else s=r;n.contextNode=s,n.setRenderTarget(i.renderTarget),i.rendercall(),n.contextNode=r}n.setRenderTarget(s),n._setXRLayerSize(r.x,r.y),this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer;!1===t.initialized&&await t.init(),this._gl=t.getContext();const n=this._gl;if(this._session=e,null!==e){if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(!0===this._supportsLayers){let i=null,r=null,s=null;const a=n.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(s=t.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,i=t.stencil?Re:Ae,r=t.stencil?xe:ge);const o={colorFormat:n.RGBA8,depthFormat:s,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const l=this._glBinding.createProjectionLayer(o),u=[l];this._glProjLayer=l,t.setPixelRatio(1),t._setXRLayerSize(l.textureWidth,l.textureHeight);const c=this._useMultiview?2:1,h=new gs(l.textureWidth,l.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,i,c);if(this._xrRenderTarget=new $C(l.textureWidth,l.textureHeight,{format:Ee,type:he,colorSpace:t.outputColorSpace,depthTexture:h,stencilBuffer:t.stencil,samples:a.antialias?4:0,resolveDepthBuffer:!1===l.ignoreDepthValues,resolveStencilBuffer:!1===l.ignoreDepthValues,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1===l.ignoreDepthValues,storeMultisampledStencilBuffer:!1===l.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new Fr({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=p,e.plane.material.blendSrc=v,e.plane.material.blendDst=v,e.xrlayer=this._createXRLayer(e),u.unshift(e.xrlayer);e.updateRenderState({layers:u})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());const i={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,n,i);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new $C(r.framebufferWidth,r.framebufferHeight,{format:Ee,type:he,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const n=e.near,i=e.far,r=this._cameraXR,s=this._cameraL,a=this._cameraR;r.near=a.near=s.near=n,r.far=a.far=s.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,s.layers.mask=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,l=r.cameras;ZC(r,o);for(let e=0;e=0&&(n[s]=null,t[s].disconnect(r))}for(let i=0;i=n.length){n.push(r),s=e;break}if(null===n[e]){n[e]=r,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(r)}}function tN(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function nN(e,t){if(void 0===t)return;const n=this._cameraXR,i=this._renderer,r=i.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views,t=this._isWebGPUSession()?this._getWebGPUViewData(e):null;null!==this._glBaseLayer&&null===t&&r.setXRTarget(s.framebuffer);let a=!1;e.length!==n.cameras.length&&(n.cameras.length=0,a=!0);for(let i=0;i{await this.compileAsync(n,t,e);const i=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,r=this._renderLists.get(e,t,this.lighting),s=this._renderContexts.get(i,this._mrt),a=e.overrideMaterial||n.material,o=this._objects.get(n,a,e,t,r.lightsNode,s,s.clippingContext),{fragmentShader:l,vertexShader:u}=o.getNodeBuilderState();return{fragmentShader:l,vertexShader:u}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new FC(this,n),this._animation=new yE(this,this._nodes,this.info),this._attributes=new LE(n,this.info),this._background=new CR(this,this._nodes),this._geometries=new FE(this._attributes,this.info),this._textures=new rA(this,n,this.info),this._pipelines=new HE(n,this._nodes,this.info),this._bindings=new WE(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new wE(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new QE,this._bundles=new GC,this._renderContexts=new nA(this),this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null,i=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init(),2===this.shadowMap.type&&(qt("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=1);const r=this._nodes.nodeFrame,s=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction,u=this._compilationPromises;null===n&&(n=e);const c=!0===e.isScene?e:!0===n.isScene?n:rN,h=this.needsFrameBufferTarget&&null===this._renderTarget,d=this._renderTarget||this._outputRenderTarget,p=!0===this.xr.isPresenting&&this.isOutputTarget,f=h?this._getFrameBufferTarget():d,m=this._renderContexts.get(f,this._mrt),g=this._activeMipmapLevel,_=[];this._currentRenderContext=m,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=_,r.renderId++,r.update(),m.depth=this.depth,m.stencil=this.stencil,m.clippingContext||(m.clippingContext=new kC),m.clippingContext.updateGlobal(c,t),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t,p),c.onBeforeRender(this,e,t,f),uN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?lN.setFromArrayCamera(t):oN.setFromProjectionMatrix(uN,t.coordinateSystem,t.reversedDepth);const v=this._renderLists.get(c,t,this.lighting);if(v.begin(),this._projectObject(e,t,0,v,m.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&v.pushLight(e)}),v.finish(),null!==f){this._textures.updateRenderTarget(f,g);const e=this._textures.get(f);m.textures=e.textures,m.depthTexture=e.depthTexture}else m.textures=null,m.depthTexture=null;n!==e?this._background.update(n,v,m):this._background.update(c,v,m);const y=v.opaque,b=v.transparent,x=v.transparentDoublePass,S=v.lightsNode;!0===this.opaque&&y.length>0&&this._renderObjects(y,t,c,S),!0===this.transparent&&b.length>0&&this._renderTransparents(b,x,t,c,S),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._compilationPromises=u;const T=_.length;let M=0;for(const e of _){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,await this._nodes.getForRenderAsync(t),this._isPreCompiling=!0,this._nodes.updateBefore(t),this._geometries.updateForRender(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t),this._isPreCompiling=!1;const n=[];this._pipelines.getForRender(t,n),n.length>0&&await Promise.all(n),this._isPreCompiling=!0,this._nodes.updateAfter(t),this._isPreCompiling=!1,M++,null!==i&&i(new ProgressEvent("progress",{lengthComputable:!0,loaded:M,total:T})),await Zt()}}async compileComputeAsync(e,t=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const n=Array.isArray(e)?e:[e];if(0===n.length||n.some(e=>null==e||!0!==e.isComputeNode))throw new Error("THREE.Renderer: .compileComputeAsync() expects a ComputeNode.");const i=n.length;let r=0;const s=this._pipelines,a=this._bindings,o=this._nodes;for(const e of n){if(!1===s.has(e)){const t=()=>{e.removeEventListener("dispose",t),s.delete(e),a.deleteForCompute(e),o.delete(e)};e.addEventListener("dispose",t);const n=e.onInitFunction;null!==n&&n.call(e,{renderer:this})}await o.getForComputeAsync(e),o.updateBeforeForCompute(e),o.updateForCompute(e),a.updateForCompute(e);const n=a.getForCompute(e),l=[];s.getForCompute(e,n,l),await Promise.all(l),o.updateAfterForCompute(e),r++,null!==t&&t(new ProgressEvent("progress",{lengthComputable:!0,loaded:r,total:i})),r0&&this._renderObjects(c,r,t,n),!0===this.transparent&&u.length>0&&this._renderTransparents(u,e,r,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t{r.removeEventListener("dispose",a),s.dispose(),this._frameBufferTargets.delete(r)};r.addEventListener("dispose",a),this._frameBufferTargets.set(r,s)}const a=this.getOutputRenderTarget();s.depthBuffer=n,s.stencilBuffer=i,null!==a?s.setSize(a.width,a.height,a.depth):s.setSize(e,t,1);const o=this._outputRenderTarget?this._outputRenderTarget.viewport:r._viewport,l=this._outputRenderTarget?this._outputRenderTarget.scissor:r._scissor,u=this._outputRenderTarget?1:r._pixelRatio,c=this._outputRenderTarget?this._outputRenderTarget.scissorTest:r._scissorTest;return s.viewport.copy(o),s.scissor.copy(l),s.viewport.multiplyScalar(u),s.scissor.multiplyScalar(u),s.scissorTest=c,s.multiview=null!==a&&a.multiview,s.useArrayDepthTexture=null!==a&&a.useArrayDepthTexture,s.resolveDepthBuffer=null===a||a.resolveDepthBuffer,s.resolveStencilBuffer=null===a||a.resolveStencilBuffer,s.storeMultisampledColorBuffer=null===a||a.storeMultisampledColorBuffer,s.storeMultisampledDepthBuffer=null===a||a.storeMultisampledDepthBuffer,s.storeMultisampledStencilBuffer=null===a||a.storeMultisampledStencilBuffer,s._autoAllocateDepthBuffer=null!==a&&a._autoAllocateDepthBuffer,s}_renderScene(e,t,n=!0){if(!0===this._isDeviceLost)return;2===this.shadowMap.type&&(qt("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=1);const i=n?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,s=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;const u=!0===e.isScene?e:rN,c=this._renderTarget||this._outputRenderTarget,h=!0===this.xr.isPresenting&&this.isOutputTarget,d=this._activeCubeFace,p=this._activeMipmapLevel;let f;if(null!==i?(f=i,this.setRenderTarget(f)):f=c,null!==f&&!0===f.depthBuffer){const e=this._textures.get(f);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const m=this._renderContexts.get(f,this._mrt,this._callDepth);this._currentRenderContext=m,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(m),this.inspector.beginRender(this.backend.getTimestampUID(m),e,t,f),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t,h);const g=this._canvasTarget;let _=g._viewport,v=g._scissor,y=g._pixelRatio;null!==f&&(_=f.viewport,v=f.scissor,y=1),this.getDrawingBufferSize(sN),aN.set(0,0,sN.width,sN.height);const b=void 0===_.minDepth?0:_.minDepth,x=void 0===_.maxDepth?1:_.maxDepth;m.viewportValue.copy(_).multiplyScalar(y).floor(),m.viewportValue.width>>=p,m.viewportValue.height>>=p,m.viewportValue.minDepth=b,m.viewportValue.maxDepth=x,m.viewport=!1===m.viewportValue.equals(aN),m.scissorValue.copy(v).multiplyScalar(y).floor(),m.scissor=g._scissorTest&&!1===m.scissorValue.equals(aN),m.scissorValue.width>>=p,m.scissorValue.height>>=p,m.clippingContext||(m.clippingContext=new kC),m.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,f),uN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?lN.setFromArrayCamera(t):oN.setFromProjectionMatrix(uN,t.coordinateSystem,t.reversedDepth),this._renderLists.update(r.frameId);const S=this._renderLists.get(e,t,this.lighting);if(S.begin(),this._projectObject(e,t,0,S,m.clippingContext),S.finish(),!0===this.sortObjects&&S.sort(this._opaqueSort,this._transparentSort),null!==f){this._textures.updateRenderTarget(f,p);const e=this._textures.get(f);m.textures=e.textures,m.depthTexture=e.depthTexture,m.width=e.width,m.height=e.height,m.renderTarget=f,m.depth=f.depthBuffer,m.stencil=f.stencilBuffer}else m.textures=null,m.depthTexture=null,m.width=sN.width,m.height=sN.height,m.depth=this.depth,m.stencil=this.stencil;m.width>>=p,m.height>>=p,m.activeCubeFace=d,m.activeMipmapLevel=p,m.occlusionQueryCount=S.occlusionQueryCount,m.fullscreenPass=!0===e.isQuadMesh,m.scissorValue.max(cN.set(0,0,0,0)),m.scissorValue.x+m.scissorValue.width>m.width&&(m.scissorValue.width=Math.max(m.width-m.scissorValue.x,0)),m.scissorValue.y+m.scissorValue.height>m.height&&(m.scissorValue.height=Math.max(m.height-m.scissorValue.y,0)),this._background.update(u,S,m),m.camera=t,this.backend.beginRender(m);const{bundles:T,lightsNode:M,transparentDoublePass:w,transparent:E,opaque:A}=S;return T.length>0&&this._renderBundles(T,u,M),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,M),!0===this.transparent&&E.length>0&&this._renderTransparents(E,w,t,u,M),this.backend.finishRender(m),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this.lighting.finishRender(e),this._callDepth--,null!==i&&(this.setRenderTarget(c,d,p),this._renderOutput(f)),u.onAfterRender(this,e,t,f),this.inspector.finishRender(this.backend.getTimestampUID(m)),m}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let n,i=this._quadCache.get(e.texture);if(void 0===i){n=new mA(new PT),n.name="Output Color Transform",n.material.name="outputColorTransform",n.material.fragmentNode=this._nodes.getOutputNode(e.texture),i={quad:n,cacheKey:t},this._quadCache.set(e.texture,i);const r=()=>{n.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",r)};e.texture.addEventListener("dispose",r)}else n=i.quad,i.cacheKey!==t&&(n.material.fragmentNode=this._nodes.getOutputNode(e.texture),n.material.needsUpdate=!0,i.cacheKey=t);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(n,e),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,n=0,i=-1){if(null!==t&&t.isReadbackBuffer&&!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}if(n%4!=0||i>0&&i%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,n,i)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,i){this._canvasTarget.setScissor(e,t,n,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}resetState(){if(!1===this._initialized)throw new Error('THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.');this.backend.resetState()}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,i,r=0,s=1){this._canvasTarget.setViewport(e,t,n,i,r,s)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)throw new Error('THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.get(i,null,-1),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel(),!0===i.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,n,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Kt('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){Kt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Kt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Kt('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==Sn.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:(this.needsFrameBufferTarget||!0===this._currentRenderContext?.fullscreenPass)&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Sn.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}async dispose(){if(!0===this._initialized){this.info.dispose(),this._inspector.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();await this.backend.dispose()}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return qt('Renderer: ".compute()" called before the backend is initialized. Try using ".computeAsync()" instead.'),this.computeAsync(e,t);const n=this._nodes.nodeFrame,i=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,s=this._pipelines,a=this._bindings,o=this._nodes,l=Array.isArray(e)?e:[e];if(void 0===l[0]||!0!==l[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const n of l){if(!1===s.has(n)){const e=()=>{n.removeEventListener("dispose",e),s.delete(n),a.deleteForCompute(n),o.delete(n)};n.addEventListener("dispose",e);const t=n.onInitFunction;null!==t&&t.call(n,{renderer:this})}o.updateBeforeForCompute(n),o.updateForCompute(n),a.updateForCompute(n);const i=a.getForCompute(n),l=s.getForCompute(n,i);r.compute(e,n,i,l,t),o.updateAfterForCompute(n)}r.finishCompute(e),n.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Kt('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Kt('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=cN.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Yt("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=cN.copy(t).floor()}else t=cN.set(0,0,e.image.width,e.image.height);let n,i=this._currentRenderContext;null!==i?n=i.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),i=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,r,s),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,i,r,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,i,r,a)}_projectObject(e,t,n,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const s=t.isArrayCamera?lN:oN;if(!e.frustumCulled||e.intersectsFrustum(s)){!0===this.sortObjects&&cN.setFromMatrixPosition(e.matrixWorld).applyMatrix4(uN);const{geometry:t,material:s}=e;s.visible&&i.push(e,t,s,n,cN.z,null,r)}}else if(e.isLineLoop)Yt("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const s=t.isArrayCamera?lN:oN;if(!e.frustumCulled||e.intersectsFrustum(s)){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),cN.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(uN)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,i,r)}_renderObjects(e,t,n,i,r=null){for(let s=0,a=e.length;s(t.not().discard(),e))(l)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),n={version:t,colorNode:l,depthNode:u,positionNode:o},this._cacheShadowNodes.set(e,n)}return n}_updateCamera(e,t){const n=this.xr;if(!1===n.isPresenting||!1===t){let t=!1;if(!0===this.reversedDepthBuffer&&!0!==e.reversedDepth){if(e._reversedDepth=!0,e.isArrayCamera)for(const t of e.cameras)t._reversedDepth=!0;t=!0}const n=this.coordinateSystem;if(e.coordinateSystem!==n){if(e.coordinateSystem=n,e.isArrayCamera)for(const t of e.cameras)t.coordinateSystem=n;t=!0}if(!0===t&&(e.updateProjectionMatrix(),e.isArrayCamera))for(const t of e.cameras)t.updateProjectionMatrix()}return null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===t&&!0===n.enabled&&!0===n.isPresenting&&(!0===n.cameraAutoUpdate&&n.updateCamera(e),e=n.getCamera()),e}renderObject(e,t,n,i,r,s,a,o=null,l=null){let u,c,h,d,p,f,m,g=!1;const _=this._currentSourceMaterial;if(e.onBeforeRender(this,t,n,i,r,s),!0===r.allowOverride&&null!==t.overrideMaterial){this._currentSourceMaterial=r;const e=t.overrideMaterial;if(g=!0,u=e.isNodeMaterial?e.colorNode:null,c=e.isNodeMaterial?e.depthNode:null,h=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,p=e.displacementMap,f=e.displacementScale,m=e.displacementBias,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.displacementMap=r.displacementMap,e.displacementScale=r.displacementScale,e.displacementBias=r.displacementBias,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:n,positionNode:i}=this._getShadowNodes(r);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:hN[r.side],null!==t&&(e.colorNode=t),null!==n&&(e.depthNode=n),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,n,a,s,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,n,a,s,o,l),r.side=2):this._handleObjectFunction(e,r,t,n,a,s,o,l),g&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=c,t.overrideMaterial.positionNode=h,t.overrideMaterial.side=d,t.overrideMaterial.displacementMap=p,t.overrideMaterial.displacementScale=f,t.overrideMaterial.displacementBias=m),this._currentSourceMaterial=_,e.onAfterRender(this,t,n,i,r,s)}hasCompatibility(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);if(l.drawRange=e.geometry.drawRange,l.group=s,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}const u=this._nodes.needsRefresh(l);u===Vt?(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)):u===zt&&(this._nodes.updateBefore(l),this._nodes.updateForRender(l),this._bindings.updateSharedForRender(l)),this._pipelines.updateForRender(l),this._pipelines.isReady(l)&&(this.backend.draw(l,this.info),u!==kt&&this._nodes.updateAfter(l))}_createObjectPipeline(e,t,n,i,r,s,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:n,camera:i,lightsNode:r,group:s,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class pN{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}function fN(e){return e+(PE-e%PE)%PE}class mN extends pN{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return fN(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}}class gN extends mN{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let _N=0;class vN extends gN{constructor(e,t){super("UniformBuffer_"+(e&&e.name?e.name:_N++),e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get byteLength(){return fN(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}}class yN extends gN{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){const t=e.index;if(this._addedIndices.has(t))return;let n=this._updateRangeCache.get(t);void 0===n&&(n={start:0,count:0},this._updateRangeCache.set(t,n)),n.start=e.offset,n.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(n)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,i=this.uniforms.length;n> 24 ) / 127.0, -1.0 ); }"),floatunpack_unorm_4x8:new DA("vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }")},CN={equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatpack_snorm_4x8:"tsl_packSnorm4x8",floatpack_unorm_4x8:"tsl_packUnorm4x8",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16",floatunpack_snorm_4x8:"tsl_unpackSnorm4x8",floatunpack_unorm_4x8:"tsl_unpackUnorm4x8"},NN={low:"lowp",medium:"mediump",high:"highp"},PN={swizzleAssign:!0,storageBuffer:!1},LN={perspective:"smooth",linear:"noperspective"},DN={centroid:"centroid"},IN="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n",UN=new Set(["const","uniform","buffer","shared","attribute","varying","coherent","volatile","restrict","readonly","writeonly","atomic_uint","layout","centroid","flat","smooth","noperspective","patch","sample","invariant","precise","break","continue","do","for","while","switch","case","default","if","else","subroutine","in","out","inout","int","void","bool","true","false","float","double","discard","return","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","uint","uvec2","uvec3","uvec4","dvec2","dvec3","dvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","dmat2","dmat3","dmat4","dmat2x2","dmat2x3","dmat2x4","dmat3x2","dmat3x3","dmat3x4","dmat4x2","dmat4x3","dmat4x4","lowp","mediump","highp","precision","sampler2D","sampler3D","samplerCube","sampler2DShadow","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","struct","common","partition","active","asm","class","union","enum","typedef","template","this","resource","goto","inline","noinline","public","static","extern","external","interface","long","short","half","fixed","unsigned","superp","input","output","hvec2","hvec3","hvec4","fvec2","fvec3","fvec4","sampler3DRect","filter","sizeof","cast","namespace","using","main"]);class FN extends hC{constructor(e,t){super(e,t,new LC),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==_t}_include(e){const t=RN[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==RN[e]&&this._include(e),CN[e]||e}getBitcastMethod(e,t){const n=this.getComponentType(t),i=this.getComponentType(e);return"float"!==n&&"float"!==i&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${n}_${i}`)}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=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${n.vars}\n\n${n.code}\n\treturn ${n.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,n=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let s=r?Ne:Ce;2===i?s=r?Le:Pe:3===i?s=r?De:we:4===i&&(s=r?Ie:Ee);const a={Float32Array:_e,Uint8Array:he,Uint16Array:fe,Uint32Array:ge,Int8Array:de,Int16Array:pe,Int32Array:me,Uint8ClampedArray:he},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n/i))));let l=Math.ceil(n/i/o);o*l*i0?r:"";t=`${n.name} {\n\t${i} ${e.name}[${s}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const n=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let s=`${i} ${t.name};`;null!==r&&(s=NN[r]+" "+s),n.push("\t"+s)}i[t]=n}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=NN[i]+" "+t),t="uniform "+t,n.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==me){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.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 n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],i=[];for(const e of n)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return"fragment"===e&&0===i.length&&i.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const i of n){"compute"===e&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${LN[i.interpolationType]||i.interpolationType} ${DN[i.interpolationSampling]||""} out ${n} ${i.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}out ${n} ${i.name};\n`}else t+=`${n} ${i.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);if(e.interpolationType){t+=`${LN[e.interpolationType]||e.interpolationType} ${DN[e.interpolationSampling]||""} in ${n} ${e.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}}for(const n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.compute.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){Yt("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){Yt("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){Yt("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=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 n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:i}of n.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=PN[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}PN[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${this.format(i.result,r.getNodeType(this),"vec4")};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${this.format(i.result,r.getNodeType(this),this.getOutputType())};`)))}const s=e[t];if(s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t,!0),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=n,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(s.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new wN(r.name,r.node,i),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new EN(r.name,r.node,i),l.push(a);else if("texture3D"===t)a=new AN(r.name,r.node,i),l.push(a);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let n=t.buffer;void 0===n&&(e.name=`NodeBuffer_${e.id}`,n=new vN(e,i),n.name=e.name,t.buffer=n),l.push(n),a=n}else{let e=this.uniformGroups[o];void 0===e?(e=new xN(o,i),this.uniformGroups[o]=e,l.push(e)):-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const n=a.name,s=e.uniforms.some(e=>e.name===n);s||e.addUniform(a)}s.uniformGPU=a}return r}}let ON=null,BN=null;class kN{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Ot]:null,[Ft]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),n=this.renderer.info.frame;let i,r=e.id;Array.isArray(e)?(r=e.map(e=>e.id).join(","),i="c:"+this.renderer.info.compute.frameCalls):i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+r+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Ft:Ot;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Kt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return ON=ON||new dn,this.renderer.getDrawingBufferSize(ON)}setScissorTest(){}resetState(){}getClearColor(){const e=this.renderer;return BN=BN||new sA,e.getClearColor(BN),BN.getRGB(BN),BN}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:Wt(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}async dispose(){for(const e of Object.values(this.timestampQueryPool))null!==e&&await e.dispose()}}let zN,VN,GN=0;class HN{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 WN{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)l=i.HALF_FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===me,id:GN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,s);c=new HN(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),c=new Uint8Array(new ArrayBuffer(u)),t.buffer=c.buffer}else c=new Uint8Array(t);return s.bindBuffer(s.COPY_READ_BUFFER,l),s.getBufferSubData(s.COPY_READ_BUFFER,n,c),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:c.buffer}_createBuffer(e,t,n,i){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,n,i),e.bindBuffer(t,null),r}}class jN{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor=new yi(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;zN={[p]:e.FUNC_ADD,[f]:e.FUNC_SUBTRACT,[m]:e.FUNC_REVERSE_SUBTRACT,[g]:e.MIN,[_]:e.MAX},VN={[v]:e.ZERO,[y]:e.ONE,[b]:e.SRC_COLOR,[S]:e.SRC_ALPHA,[R]:e.SRC_ALPHA_SATURATE,[E]:e.DST_COLOR,[M]:e.DST_ALPHA,[x]:e.ONE_MINUS_SRC_COLOR,[T]:e.ONE_MINUS_SRC_ALPHA,[A]:e.ONE_MINUS_DST_COLOR,[w]:e.ONE_MINUS_DST_ALPHA,[C]:e.CONSTANT_COLOR,[N]:e.ONE_MINUS_CONSTANT_COLOR,[P]:e.CONSTANT_ALPHA,[L]:e.ONE_MINUS_CONSTANT_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=(new Dn).fromArray(t),this.currentViewport=(new Dn).fromArray(n),this._tempVec4=new Dn}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:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){const i=this.gl,r=this.backend.drawBuffersIndexedExt;if(r)for(let s=0;s0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()})}}let XN,qN,YN,KN=!1;class ZN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===KN&&(this._init(),KN=!0)}_init(){const e=this.gl;XN={[ne]:e.REPEAT,[ie]:e.CLAMP_TO_EDGE,[re]:e.MIRRORED_REPEAT},qN={[se]:e.NEAREST,[ae]:e.NEAREST_MIPMAP_NEAREST,[oe]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[ue]:e.LINEAR_MIPMAP_NEAREST,[ce]:e.LINEAR_MIPMAP_LINEAR},YN={[Tt]:e.NEVER,[Nt]:e.ALWAYS,[Mt]:e.LESS,[Et]:e.LEQUAL,[wt]:e.EQUAL,[Ct]:e.GEQUAL,[At]:e.GREATER,[Rt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r,s=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];qt("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=null;i&&(l=o.get("EXT_texture_norm16"),l||qt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let u=t;if(t===a.RED&&(n===a.FLOAT&&(u=a.R32F),n===a.HALF_FLOAT&&(u=a.R16F),n===a.UNSIGNED_BYTE&&(u=a.R8),n===a.BYTE&&(u=a.R8_SNORM),n===a.UNSIGNED_SHORT&&l&&(u=l.R16_EXT),n===a.SHORT&&l&&(u=l.R16_SNORM_EXT)),t===a.RED_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.R8UI),n===a.UNSIGNED_SHORT&&(u=a.R16UI),n===a.UNSIGNED_INT&&(u=a.R32UI),n===a.BYTE&&(u=a.R8I),n===a.SHORT&&(u=a.R16I),n===a.INT&&(u=a.R32I)),t===a.RG&&(n===a.FLOAT&&(u=a.RG32F),n===a.HALF_FLOAT&&(u=a.RG16F),n===a.UNSIGNED_BYTE&&(u=a.RG8),n===a.BYTE&&(u=a.RG8_SNORM),n===a.UNSIGNED_SHORT&&l&&(u=l.RG16_EXT),n===a.SHORT&&l&&(u=l.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.RG8UI),n===a.UNSIGNED_SHORT&&(u=a.RG16UI),n===a.UNSIGNED_INT&&(u=a.RG32UI),n===a.BYTE&&(u=a.RG8I),n===a.SHORT&&(u=a.RG16I),n===a.INT&&(u=a.RG32I)),t===a.RGB){const e=s?bt:Sn.getTransfer(r);n===a.FLOAT&&(u=a.RGB32F),n===a.HALF_FLOAT&&(u=a.RGB16F),n===a.UNSIGNED_BYTE&&(u=e===xt?a.SRGB8:a.RGB8),n===a.BYTE&&(u=a.RGB8_SNORM),n===a.UNSIGNED_SHORT&&l&&(u=l.RGB16_EXT),n===a.SHORT&&l&&(u=l.RGB16_SNORM_EXT),n===a.UNSIGNED_SHORT_5_6_5&&(u=a.RGB565),n===a.UNSIGNED_SHORT_5_5_5_1&&(u=a.RGB5_A1),n===a.UNSIGNED_SHORT_4_4_4_4&&(u=a.RGB4),n===a.UNSIGNED_INT_5_9_9_9_REV&&(u=a.RGB9_E5),n===a.UNSIGNED_INT_10F_11F_11F_REV&&(u=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.RGB8UI),n===a.UNSIGNED_SHORT&&(u=a.RGB16UI),n===a.UNSIGNED_INT&&(u=a.RGB32UI),n===a.BYTE&&(u=a.RGB8I),n===a.SHORT&&(u=a.RGB16I),n===a.INT&&(u=a.RGB32I)),t===a.RGBA){const e=s?bt:Sn.getTransfer(r);n===a.FLOAT&&(u=a.RGBA32F),n===a.HALF_FLOAT&&(u=a.RGBA16F),n===a.UNSIGNED_BYTE&&(u=e===xt?a.SRGB8_ALPHA8:a.RGBA8),n===a.BYTE&&(u=a.RGBA8_SNORM),n===a.UNSIGNED_SHORT&&l&&(u=l.RGBA16_EXT),n===a.SHORT&&l&&(u=l.RGBA16_SNORM_EXT),n===a.UNSIGNED_SHORT_4_4_4_4&&(u=a.RGBA4),n===a.UNSIGNED_SHORT_5_5_5_1&&(u=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.RGBA8UI),n===a.UNSIGNED_SHORT&&(u=a.RGBA16UI),n===a.UNSIGNED_INT&&(u=a.RGBA32UI),n===a.BYTE&&(u=a.RGBA8I),n===a.SHORT&&(u=a.RGBA16I),n===a.INT&&(u=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(n===a.UNSIGNED_SHORT&&(u=a.DEPTH_COMPONENT16),n===a.UNSIGNED_INT&&(u=a.DEPTH_COMPONENT24),n===a.FLOAT&&(u=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&n===a.UNSIGNED_INT_24_8&&(u=a.DEPTH24_STENCIL8),u!==a.R16F&&u!==a.R32F&&u!==a.RG16F&&u!==a.RG32F&&u!==a.RGBA16F&&u!==a.RGBA32F||o.get("EXT_color_buffer_float"),u}setTextureParameters(e,t){const{gl:n,extensions:i,backend:r}=this,{state:s}=this.backend,a=Sn.getPrimaries(Sn.workingColorSpace),o=t.colorSpace===_t?null:Sn.getPrimaries(t.colorSpace),l=t.colorSpace===_t||a===o?n.NONE:n.BROWSER_DEFAULT_WEBGL;s.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),n.texParameteri(e,n.TEXTURE_WRAP_S,XN[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,XN[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,XN[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,qN[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,c=t.minFilter===le&&u?ce:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,qN[c]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,YN[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===se)return;if(t.minFilter!==oe&&t.minFilter!==ce)return;if(t.type===_e&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r})}createTexture(e,t){const{gl:n,backend:i}=this;let r,s,a,o,l;if(!0===e.isExternalTexture)r=e.sourceTexture,s=this.getGLTextureType(e);else{const{levels:u,width:c,height:h,depth:d}=t;a=i.utils.convert(e.format,e.colorSpace),o=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,a,o,e.normalized,e.colorSpace,e.isVideoTexture),r=n.createTexture(),s=this.getGLTextureType(e),i.state.bindTexture(s,r),this.setTextureParameters(s,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,u,l,c,h,d):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,u,l,c,h,d):e.isVideoTexture||n.texStorage2D(s,u,l,c,h)}i.set(e,{textureGPU:r,glTextureType:s,glFormat:a,glType:o,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{state:r}=i,{textureGPU:s,glTextureType:a,glFormat:o,glType:l}=i.get(t),{width:u,height:c}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,s),r.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(a,0,0,0,u,c,o,l,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==s)if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0){const i=qa(s.width,s.height,e.format,e.type);for(const r of e.layerUpdates){const e=s.data.subarray(r*i/s.data.BYTES_PER_ELEMENT,(r+1)*i/s.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,r,s.width,s.height,1,o,e)}}else n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,r.depth,o,s.data);else qt("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()");else n.texSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,r.depth,o,l,s.data);else null!==o?n.compressedTexSubImage2D(n.TEXTURE_2D,t,0,0,s.width,s.height,o,s.data):qt("WebGLBackend: Unsupported compressed texture format")}e.isCompressedArrayTexture&&e.layerUpdates.size>0&&e.clearLayerUpdates()}else if(e.isCubeTexture){const s=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=QN(s[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,o,l,t);for(let t=0;t0){const t=qa(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,o,l,e)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,l,i.data)}else if(e.isData3DTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,u,o,l,t.image);else if(e.isHTMLTexture)"function"==typeof n.texElementImage2D&&(3===n.texElementImage2D.length?n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,t.image):n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image));else{const s=e.mipmaps;if(s.length>0)for(let e=0,t=s.length;e0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(c|=i.STENCIL_BUFFER_BIT)):(c=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,n),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=h-o-u;i.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,n),r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,l,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,s,0),i.blitFramebuffer(0,0,l,u,0,0,l,u,c,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,h-u-o,l,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:r}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,n,t,u,c)):r.renderbufferStorage(r.RENDERBUFFER,t,u,c);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&l&&(n>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,n,r.DEPTH24_STENCIL8,u,c):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,u,c),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,i,r,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();if(a.state.bindFramebuffer(o.READ_FRAMEBUFFER,h),e.isData3DTexture||e.isDataArrayTexture||e.isArrayTexture)o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,l,0,s);else{const t=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,t,l,0)}const d=this._getTypedArrayType(c),p=i*r*this._getBytesPerTexel(c,u),f=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,f),o.bufferData(o.PIXEL_PACK_BUFFER,p,o.STREAM_READ),o.readPixels(t,n,i,r,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const m=new d(p/d.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,f),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,m),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteBuffer(f),o.deleteFramebuffer(h),m}_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(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let i=0;return e===n.UNSIGNED_BYTE&&(i=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(i=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(i=4),t===n.RGBA?4*i:t===n.RGB?3*i:t===n.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function QN(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class JN{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 eP{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(null!==this.maxUniformBlockSize)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const tP={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class nP{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:n,mode:i,object:r,type:s,info:a,index:o}=this;0!==o?n.drawElements(i,t,s,e):n.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,n){const{gl:i,mode:r,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?i.drawElementsInstanced(r,t,s,e,n):i.drawArraysInstanced(r,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:r,object:s,info:a}=this;if(0===n)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;ithis.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null);const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){Yt("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){Yt("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,n]of this.queryOffsets){if("ended"===this.queryStates.get(n)){const i=this.queries[n];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},n=[];this.timestamps.clear();for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===n.includes(s)&&n.push(s),void 0===t[s]&&(t[s]=0);const a=await r;this.timestamps.set(i,a),t[s]+=a}const i=t[n[n.length-1]];return this.lastValue=i,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return Yt("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let n,i=!1;const r=e=>{i||(i=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){Yt("Error checking query:",e),t(this.lastValue)}};s()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.lastValue=0,this.activeQuery=null}}}const sP=[];class aP extends kN{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function r(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new JN(this),this.capabilities=new eP(this),this.attributeUtils=new WN(this),this.textureUtils=new ZN(this),this.bufferRenderer=new nP(this),this.state=new jN(this),this.utils=new $N(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(qt("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return It}get hasTimestamp(){return null!==this.disjoint}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==n){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&qt("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new rP(this.gl,e,2048));const n=this.timestampQueryPool[e];null!==n.allocateQueriesForContext(t)&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:n}=this.getDrawingBufferSize();t.viewport(0,0,e,n)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:n}=this.getDrawingBufferSize();t.scissor(0,0,e,n)}this.initTimestampQuery(Ot,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0?(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0):void 0!==n.lastOcclusionObject&&(n.lastOcclusionObject=void 0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),r=i.previousContext;n.resetVertexState();if(e.occlusionQueryCount>0){const n=i.lastOcclusionObject;n&&!0===n.occlusionTest&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e)}const s=e.textures;if(null!==s)for(let e=0;e{let a=!0;for(let t=0;t1?t.renderInstances(n,i,r):t.render(n,i)}draw(e){const{object:t,pipeline:n,material:i,context:r,hardwareClippingPlanes:s}=e,{programGPU:a}=this.get(n),{gl:o,state:l}=this,u=this.get(r),c=e.getDrawParameters();if(null===c)return;this._bindUniforms(e.getBindings());const h=t.isMesh&&t.matrixWorld.determinantAffine()<0;l.setMaterial(i,h,s),null!==r.mrt&&null!==r.textures&&l.setMRTBlending(r.textures,r.mrt,i),l.useProgram(a);const d=e.getAttributes(),p=this.get(d);let f=p.vaoGPU;if(void 0===f){const e=this._getVaoKey(d);f=this.vaoCache[e],void 0===f&&(f=this._createVao(d),this.vaoCache[e]=f,p.vaoGPU=f)}const m=e.getIndex(),g=null!==m?this.get(m).bufferGPU:null;l.setVertexState(f,g);const _=u.lastOcclusionObject;if(_!==t&&void 0!==_){if(null!==_&&!0===_.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),u.occlusionQueries[u.occlusionQueryIndex]=e,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const v=this.bufferRenderer;t.isPoints?v.mode=o.POINTS:t.isLineSegments?v.mode=o.LINES:t.isLine?v.mode=o.LINE_STRIP:t.isLineLoop?v.mode=o.LINE_LOOP:!0===i.wireframe?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=o.LINES):v.mode=o.TRIANGLES;const{vertexCount:y,instanceCount:b}=c;let{firstVertex:x}=c;if(v.object=t,null!==m){x*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);v.index=m.count,v.type=e.type}else v.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const n=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,r=i.length;n{const r=this.parallel,s=()=>{n.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(s)};s()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e":" "} ${r}: ${n[e]}`)}return i.join("\n")}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,n){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,n,t);else{const s=this._getShaderErrors(i,n,"vertex"),a=this._getShaderErrors(i,t,"fragment");Yt("WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+s+"\n"+a)}else""!==r&&qt("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:n,gl:i}=this,r=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(s,i.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s,pipeline:s})}createComputePipeline(e,t,n=null){const{gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:s}=e,a=i.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;e{const s=()=>{i.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeComputeCompile(e,t),n()):requestAnimationFrame(s)};s()});return void n.push(s)}this._completeComputeCompile(e,t)}_completeComputeCompile(e,t){const{state:n,gl:i}=this,{programGPU:r,fragmentShader:s,vertexShader:a}=this.get(e);!1===i.getProgramParameter(r,i.LINK_STATUS)&&this._logProgramError(r,s,a),n.useProgram(r),this._setupBindings(t,r)}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,n=0;for(const i of t){this.set(i,{textures:n,uniformBuffers:e});for(const t of i.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&n++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const n of e.bindings){const e=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){const i=n.buffer,r=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,r);const s=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),0===s.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=Gt(i),n=e?1:i.BYTES_PER_ELEMENT;for(let r=0,a=s.length;rtP[t]===e),n=this.extensions;for(let e=0;e1,h=!0===r.isXRRenderTarget,d=!0===h&&!0===r._hasExternalTextures;let p=s.msaaFrameBuffer,f=s.depthRenderbuffer;const m=this.extensions.get("WEBGL_multisampled_render_to_texture"),g=this.extensions.get("OVR_multiview2"),_=this._useMultisampledExtension(r);let v=r.samples;null!==e.depthTexture&&e.depthTexture.renderTarget!==r&&!1===_&&v>0&&(Kt('WebGLBackend: Shared depth texture is not supported with MSAA when "WEBGL_multisampled_render_to_texture" is unsupported. Falling back to single-sample rendering.'),v=0);const y=tA(e);let b;if(l?(s.cubeFramebuffers||(s.cubeFramebuffers={}),b=s.cubeFramebuffers[y]):h&&!1===d?b=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),b=s.framebuffers[y]),void 0===b){b=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,b);const i=e.textures,a=[];if(l){s.cubeFramebuffers[y]=b;const{textureGPU:e}=this.get(i[0]),n=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,r)}else{s.framebuffers[y]=b;for(let n=0;n0&&!1===_&&!r.multiview){if(void 0===p){p=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,p);const i=[],r=e.textures;for(let n=0;n0&&void 0!==r.msaaFrameBuffer&&!1===this._useMultisampledExtension(i)){const s=r.framebuffers[e.getCacheKey()];let a=!1===i.resolveColorBuffer?0:t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,l=r.msaaRenderbuffers,u=e.textures,c=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,o),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),c)for(let e=0;e0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,sP),sP.length=0)}}else if(!0===this._supportsInvalidateFramebuffer&&r.framebuffers&&(!0===i._autoAllocateDepthBuffer||i.samples>0&&!1===i.storeMultisampledDepthBuffer)){const i=r.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}async dispose(){await super.dispose(),null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const oP="point-list",lP="line-list",uP="line-strip",cP="triangle-list",hP="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},dP="never",pP="less",fP="equal",mP="less-equal",gP="greater",_P="not-equal",vP="greater-equal",yP="always",bP="store",xP="discard",SP="load",TP="clear",MP="ccw",wP="cw",EP="none",AP="back",RP="uint16",CP="uint32",NP="r8unorm",PP="r8snorm",LP="r8uint",DP="r8sint",IP="r16uint",UP="r16sint",FP="r16float",OP="rg8unorm",BP="rg8snorm",kP="rg8uint",zP="rg8sint",VP="r16unorm",GP="r16snorm",HP="r32uint",WP="r32sint",jP="r32float",$P="rg16uint",XP="rg16sint",qP="rg16float",YP="rgba8unorm",KP="rgba8unorm-srgb",ZP="rgba8snorm",QP="rgba8uint",JP="rgba8sint",eL="bgra8unorm",tL="bgra8unorm-srgb",nL="rg16unorm",iL="rg16snorm",rL="rgb9e5ufloat",sL="rgb10a2unorm",aL="rg11b10ufloat",oL="rg32uint",lL="rg32sint",uL="rg32float",cL="rgba16uint",hL="rgba16sint",dL="rgba16float",pL="rgba16unorm",fL="rgba16snorm",mL="rgba32uint",gL="rgba32sint",_L="rgba32float",vL="depth16unorm",yL="depth24plus",bL="depth24plus-stencil8",xL="depth32float",SL="depth32float-stencil8",TL="bc1-rgba-unorm",ML="bc1-rgba-unorm-srgb",wL="bc2-rgba-unorm",EL="bc2-rgba-unorm-srgb",AL="bc3-rgba-unorm",RL="bc3-rgba-unorm-srgb",CL="bc4-r-unorm",NL="bc4-r-snorm",PL="bc5-rg-unorm",LL="bc5-rg-snorm",DL="bc6h-rgb-ufloat",IL="bc6h-rgb-float",UL="bc7-rgba-unorm",FL="bc7-rgba-unorm-srgb",OL="etc2-rgb8unorm",BL="etc2-rgb8unorm-srgb",kL="etc2-rgb8a1unorm",zL="etc2-rgb8a1unorm-srgb",VL="etc2-rgba8unorm",GL="etc2-rgba8unorm-srgb",HL="eac-r11unorm",WL="eac-r11snorm",jL="eac-rg11unorm",$L="eac-rg11snorm",XL="astc-4x4-unorm",qL="astc-4x4-unorm-srgb",YL="astc-5x4-unorm",KL="astc-5x4-unorm-srgb",ZL="astc-5x5-unorm",QL="astc-5x5-unorm-srgb",JL="astc-6x5-unorm",eD="astc-6x5-unorm-srgb",tD="astc-6x6-unorm",nD="astc-6x6-unorm-srgb",iD="astc-8x5-unorm",rD="astc-8x5-unorm-srgb",sD="astc-8x6-unorm",aD="astc-8x6-unorm-srgb",oD="astc-8x8-unorm",lD="astc-8x8-unorm-srgb",uD="astc-10x5-unorm",cD="astc-10x5-unorm-srgb",hD="astc-10x6-unorm",dD="astc-10x6-unorm-srgb",pD="astc-10x8-unorm",fD="astc-10x8-unorm-srgb",mD="astc-10x10-unorm",gD="astc-10x10-unorm-srgb",_D="astc-12x10-unorm",vD="astc-12x10-unorm-srgb",yD="astc-12x12-unorm",bD="astc-12x12-unorm-srgb",xD="clamp-to-edge",SD="repeat",TD="mirror-repeat",MD="linear",wD="nearest",ED="zero",AD="one",RD="src",CD="one-minus-src",ND="src-alpha",PD="one-minus-src-alpha",LD="dst",DD="one-minus-dst",ID="dst-alpha",UD="one-minus-dst-alpha",FD="src-alpha-saturated",OD="constant",BD="one-minus-constant",kD="add",zD="subtract",VD="reverse-subtract",GD="min",HD="max",WD=0,jD=15,$D="keep",XD="zero",qD="replace",YD="invert",KD="increment-clamp",ZD="decrement-clamp",QD="increment-wrap",JD="decrement-wrap",eI="storage",tI="read-only-storage",nI="write-only",iI="read-only",rI="read-write",sI="non-filtering",aI="comparison",oI="float",lI="unfilterable-float",uI="depth",cI="sint",hI="uint",dI="2d",pI="3d",fI="2d",mI="2d-array",gI="cube",_I="3d",vI="all",yI="vertex",bI="instance",xI={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},SI={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class TI extends SN{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class MI extends mN{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let wI=0;class EI extends MI{constructor(e,t){super("StorageBuffer_"+(e&&e.name?e.name:wI++),e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Af,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}const AI=[null];class RI{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?SL:bL:!0===this.backend.renderer.reversedDepthBuffer?xL:yL),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 n=this.backend.get(e);t=void 0!==n.texture?n.texture.sampleCount:this.backend.renderer.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture,i=t>1&&null!==e.renderTarget&&!0===e.isDepthTexture&&!0===e.isArrayTexture;return{samples:t,primarySamples:n||i?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?oP:e.isLineSegments||e.isMesh&&!0===t.wireframe?lP:e.isLine?uP:e.isMesh?cP:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return null===this._preferredCanvasFormat&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(e===he)return eL;if(e===ve)return dL;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}}function CI(e,t){AI[0]=t,e.queue.submit(AI),AI[0]=null}class NI{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}}class PI{constructor(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}}class LI{constructor(){this.label=""}reset(){this.label=""}}class DI{constructor(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}}class II{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}}class UI{constructor(){this.label="",this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label="",this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}}class FI{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new OI,this.fragment=null}reset(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}}class OI{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}}class BI{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}}class kI{constructor(){this.label="",this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label="",this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}}class zI{constructor(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}reset(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}}const VI=new NI,GI=new PI,HI=new LI,WI=new DI,jI=new UI,$I=new FI,XI=new II,qI=new BI,YI=new kI,KI=new zI;class ZI extends EE{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:MD}),this.flipYSampler=e.createSampler({minFilter:wD}),GI.size=4,GI.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(GI),GI.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),GI.size=4,GI.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(GI),GI.reset(),this.transferPipelines={},qI.label="mipmap",qI.code="\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n",this.mipmapShaderModule=e.createShaderModule(qI),qI.reset()}getTransferPipeline(e,t){const n=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[n];return void 0===i&&($I.label=`mipmap-${e}-${t}`,$I.vertex={module:this.mipmapShaderModule},$I.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},$I.layout="auto",i=this.device.createRenderPipeline($I),$I.reset(),this.transferPipelines[n]=i),i}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size;YI.size.width=r,YI.size.height=s,YI.format=i,YI.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;const a=this.device.createTexture(YI);YI.reset();const o=this.getTransferPipeline(i,e.textureBindingViewDimension),l=this.getTransferPipeline(i,a.textureBindingViewDimension),u=this.device.createCommandEncoder(HI),c=(e,t,n,i,r,s)=>{const a=e.getBindGroupLayout(0);KI.dimension=t.textureBindingViewDimension||"2d-array",KI.mipLevelCount=1;const o=t.createView(KI);KI.reset(),VI.layout=a,VI.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:o},{binding:2,resource:{buffer:s?this.flipUniformBuffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(VI);VI.reset(),KI.dimension="2d",KI.mipLevelCount=1,KI.baseArrayLayer=r,KI.arrayLayerCount=1;const c=i.createView(KI);KI.reset(),XI.view=c,XI.loadOp=TP,XI.storeOp=bP,jI.colorAttachments.push(XI);const h=u.beginRenderPass(jI);jI.reset(),XI.reset(),h.setPipeline(e),h.setBindGroup(0,l),h.draw(3,1,0,n),h.end()};c(o,e,n,a,0,!1),c(l,a,0,e,n,!0),CI(this.device,u.finish()),a.destroy()}generateMipmaps(e,t=null){const n=this.get(e),i=n.layers||this._mipmapCreateBundles(e);let r=t;null===r&&(HI.label="mipmapEncoder",r=this.device.createCommandEncoder(HI),HI.reset()),this._mipmapRunBundles(r,i),null===t&&CI(this.device,r.finish()),n.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),i=n.getBindGroupLayout(0),r=[];for(let s=1;s1&&null!==p&&a>1&&l===dI,m=void 0!==GPUTextureUsage.TRANSIENT_ATTACHMENT&&!1===f,g=!0===e.isDepthTexture&&m&&!1===p?.storeMultisampledDepthBuffer&&(!1===p.stencilBuffer||!1===p.storeMultisampledStencilBuffer),_=!0!==e.isDepthTexture&&m&&!1===p?.storeMultisampledColorBuffer;let v=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(v|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&u!==rL&&(v|=GPUTextureUsage.RENDER_ATTACHMENT),h>1&&g&&(v=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);const y=new kI;if(y.label=e.name,y.size.width=r,y.size.height=s,y.size.depthOrArrayLayers=a,y.mipLevelCount=o,y.sampleCount=h,y.dimension=l,y.format=u,y.usage=v,void 0===u)return qt("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(y.textureBindingViewDimension=gI);try{i.texture=n.device.createTexture(y)}catch(t){return qt("WebGPURenderer: Failed to create texture with descriptor:",y),void this.createDefaultTexture(e)}if(d||f){const e=Object.assign({},y);if(e.label=e.label+"-msaa",e.sampleCount=c,e.mipLevelCount=1,(g||_)&&(e.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),f){e.size=Object.assign({},e.size,{depthOrArrayLayers:1}),i.msaaTextures=[];for(let t=0;t0)for(let t=0,s=i.length;t0){for(const i of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,r,i,e.flipY,i);e.clearLayerUpdates()}else for(let i=0;i0?(this._copyCompressedBufferToTexture(e.mipmaps,n.texture,r,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,n.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,r);else if(e.isHTMLTexture){const t=this.backend.device,i=this.backend.renderer.domElement,s=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!n.hasPaintCallback)return n.hasPaintCallback=!0,void i.requestPaint();const a=r.size.width,o=r.size.height;2===t.queue.copyElementImageToTexture.length?t.queue.copyElementImageToTexture({source:s},{destination:{texture:n.texture},width:a,height:o}):t.queue.copyElementImageToTexture(s,a,o,{texture:n.texture}),e.flipY&&this._flipY(n.texture,r)}else if(i.length>0)for(let t=0,s=i.length;t0?e.width:n.size.width,u=a>0?e.height:n.size.height;aU.source=e,aU.flipY=r,oU.texture=t,oU.mipLevel=a,oU.origin.z=i,oU.premultipliedAlpha=s,uU.width=l,uU.height=u;try{o.queue.copyExternalImageToTexture(aU,oU,uU)}catch(e){}finally{aU.reset(),oU.reset(),uU.reset()}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new ZI(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,i,r,s=0,a=0){const o=this.backend.device,l=e.data,u=this._getBytesPerTexel(n.format),c=e.width*u;iU.texture=t,iU.mipLevel=a,iU.origin.z=i,sU.offset=e.width*e.height*u*s,sU.bytesPerRow=c,uU.width=e.width,uU.height=e.height,o.queue.writeTexture(iU,l,sU,uU),iU.reset(),sU.reset(),uU.reset(),!0===r&&this._flipY(t,n,i)}_copyCompressedBufferToTexture(e,t,n,i=null){const r=this.backend.device,s=this._getBlockData(n.format),a=n.size.depthOrArrayLayers>1,o=i&&i.size>0?i:null;for(let i=0;i]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,gU=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,_U={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",sampler_comparison:"samplerComparison",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class vU extends AC{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s,outputType:a}=(e=>{const t=(e=e.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,"")).match(mU);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=gU.exec(n));)i.push({name:r[1],type:r[2]});const s=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class yU extends EC{parseFunction(e){return new vU(e)}}const bU={[wf]:"read",[Ef]:"write",[Af]:"read_write"},xU={[ne]:"repeat",[ie]:"clamp",[re]:"mirror"},SU={vertex:hP.VERTEX,fragment:hP.FRAGMENT,compute:hP.COMPUTE},TU={instance:!0,swizzleAssign:!1,storageBuffer:!0},MU={"^^":"tsl_xor"},wU={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},EU={},AU={tsl_xor:new DA("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new DA("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new DA("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new DA("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new DA("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new DA("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new DA("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new DA("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new DA("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new DA("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new DA("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 DA("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new DA("\nfn tsl_inverse_mat2( m : mat2x2 ) -> mat2x2 {\n\n\tlet det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];\n\n\treturn mat2x2(\n\t\tm[ 1 ][ 1 ], - m[ 0 ][ 1 ],\n\t\t- m[ 1 ][ 0 ], m[ 0 ][ 0 ]\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat3:new DA("\nfn tsl_inverse_mat3( m : mat3x3 ) -> mat3x3 {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];\n\n\tlet b01 = a22 * a11 - a12 * a21;\n\tlet b11 = - a22 * a10 + a12 * a20;\n\tlet b21 = a21 * a10 - a11 * a20;\n\n\tlet det = a00 * b01 + a01 * b11 + a02 * b21;\n\n\treturn mat3x3(\n\t\tb01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),\n\t\tb11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),\n\t\tb21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat4:new DA("\nfn tsl_inverse_mat4( m : mat4x4 ) -> mat4x4 {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];\n\tlet a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];\n\n\tlet b00 = a00 * a11 - a01 * a10;\n\tlet b01 = a00 * a12 - a02 * a10;\n\tlet b02 = a00 * a13 - a03 * a10;\n\tlet b03 = a01 * a12 - a02 * a11;\n\tlet b04 = a01 * a13 - a03 * a11;\n\tlet b05 = a02 * a13 - a03 * a12;\n\tlet b06 = a20 * a31 - a21 * a30;\n\tlet b07 = a20 * a32 - a22 * a30;\n\tlet b08 = a20 * a33 - a23 * a30;\n\tlet b09 = a21 * a32 - a22 * a31;\n\tlet b10 = a21 * a33 - a23 * a31;\n\tlet b11 = a22 * a33 - a23 * a32;\n\n\tlet det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n\treturn mat4x4(\n\t\ta11 * b11 - a12 * b10 + a13 * b09,\n\t\ta02 * b10 - a01 * b11 - a03 * b09,\n\t\ta31 * b05 - a32 * b04 + a33 * b03,\n\t\ta22 * b04 - a21 * b05 - a23 * b03,\n\t\ta12 * b08 - a10 * b11 - a13 * b07,\n\t\ta00 * b11 - a02 * b08 + a03 * b07,\n\t\ta32 * b02 - a30 * b05 - a33 * b01,\n\t\ta20 * b05 - a22 * b02 + a23 * b01,\n\t\ta10 * b10 - a11 * b08 + a13 * b06,\n\t\ta01 * b08 - a00 * b10 - a03 * b06,\n\t\ta30 * b04 - a31 * b02 + a33 * b00,\n\t\ta21 * b02 - a20 * b04 - a23 * b00,\n\t\ta11 * b07 - a10 * b09 - a12 * b06,\n\t\ta00 * b09 - a01 * b07 + a02 * b06,\n\t\ta31 * b01 - a30 * b03 - a32 * b00,\n\t\ta20 * b03 - a21 * b01 + a22 * b00\n\t) * ( 1.0 / det );\n\n}\n"),biquadraticTexture:new DA("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new DA("\nfn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},RU={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",inverse_mat2:"tsl_inverse_mat2",inverse_mat3:"tsl_inverse_mat3",inverse_mat4:"tsl_inverse_mat4",inversesqrt:"inverseSqrt",faceforward:"faceForward",bitcast:"bitcast",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatpack_snorm_4x8:"pack4x8snorm",floatpack_unorm_4x8:"pack4x8unorm",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float",floatunpack_snorm_4x8:"unpack4x8snorm",floatunpack_unorm_4x8:"unpack4x8unorm"},CU=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","NULL","Self","abstract","active","alignas","alignof","as","asm","asm_fragment","async","attribute","auto","await","become","binding_array","cast","catch","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const_cast","consteval","constexpr","constinit","crate","debugger","decltype","delete","demote","demote_to_helper","do","dynamic_cast","enum","explicit","export","extends","extern","external","fallthrough","filter","final","finally","friend","from","fxgroup","get","goto","groupshared","highp","impl","implements","import","inline","instanceof","interface","layout","lowp","macro","macro_rules","match","mediump","meta","mod","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","non_coherent","noncoherent","noperspective","null","nullptr","of","operator","package","packoffset","partition","pass","patch","pixelfragment","precise","precision","premerge","priv","protected","pub","public","readonly","ref","regardless","register","reinterpret_cast","require","resource","restrict","self","set","shared","sizeof","smooth","snorm","static","static_assert","static_cast","std","subroutine","super","target","template","this","thread_local","throw","trait","try","type","typedef","typeid","typename","typeof","union","unless","unorm","unsafe","unsized","use","using","varying","virtual","volatile","wgsl","where","with","writeonly","yield","main"]);let NU="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(NU+="diagnostic( off, derivative_uniformity );\n");class PU extends hC{constructor(e,t){super(e,t,new yU),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,i,r,s=this.shaderStage){return"fragment"===s?i?r?`textureSample( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",i)}generateTextureSampleLevel(e,t,n,i,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,i,r):this.generateTextureLod(e,t,n,r,s,i)}generateWrapFunction(e){const t=`tsl_coord_${xU[e.wrapS]}S_${xU[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`;let n=EU[t];if(void 0===n){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===ne?(i.push(AU.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===ie?(i.push(AU.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===re?(i.push(AU.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,qt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",EU[t]=n=new DA(s,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[n];if(void 0===i.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",s=l||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,r=new Pv(new hy(`textureDimensions( ${s} )`,a)),i.dimensionsSnippet[n]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Pv(new hy(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Pv(new hy("6u","u32")))}return r.build(this)}generateTextureSize(e,t,n){const{primarySamples:i}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${i>1||e.isStorageTexture?t:`${t}, ${n}`} )`}generateFilteredTexture(e,t,n,i,r="0u",s){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(n=`${n} + vec2(${i}) / ${o}`),s?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${n} ), ${o}, u32( ${s} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${n} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,n,i,r,s="0u"){if(!0===e.isCubeTexture){r&&(n=`${n} + vec3(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${e.isDepthTexture?"u32":"f32"}( ${s} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,s),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(n=`${n} + ${l}(${r}) / ${l}( ${o} )`);return n=`${l}( clamp( floor( ${a}( ${n} ) * ${l}( ${o} ) ), ${`${l}( 0 )`}, ${`${l}( ${o} - ${"vec3"===l?"vec3( 1, 1, 1 )":"vec2( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,n,s,i,null)}generateStorageTextureLoad(e,t,n,i,r,s){let a;return s&&(n=`${n} + ${s}`),a=r?`textureLoad( ${t}, ${n}, ${r} )`:`textureLoad( ${t}, ${n} )`,a}generateTextureLoad(e,t,n,i,r,s){let a;return null===i&&(i="0u"),s&&(n=`${n} + ${s}`),r?a=`textureLoad( ${t}, ${n}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,i,r){let s;return s=i?`textureStore( ${t}, ${n}, ${i}, ${r} )`:`textureStore( ${t}, ${n}, ${r} )`,s}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(Bt)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===_e||!1===this.isSampleCompare(e)&&e.minFilter===se&&e.magFilter===se||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||!0===e.normalized&&(e.type===pe||e.type===fe)}generateTexture(e,t,n,i,r,s=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,n,i,r,"0",s):this._generateTextureSample(e,t,n,i,r,s),a}generateTextureGrad(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${i[0]}, ${i[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${i[0]}, ${i[1]} )`:s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;Yt(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;Yt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,n,i,r,s){const a=!0===e.isDepthTexture?"":`${i}, `;return r?s?`textureGather( ${a}${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:`textureGather( ${a}${t}, ${t}_sampler, ${n}, ${r} )`:s?`textureGather( ${a}${t}, ${t}_sampler, ${n}, ${s} )`:`textureGather( ${a}${t}, ${t}_sampler, ${n})`}generateTextureGatherCompare(e,t,n,i,r,s){return r?s?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i})`:s?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i})`}generateTextureLevel(e,t,n,i,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,i,r):this.generateTextureLod(e,t,n,r,s,i)}generateTextureBias(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;Yt(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"cubeDepthTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}isReservedKeyword(e){return CU.has(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=MU[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?"vertex"===t?(qt("WebGPURenderer: Atomic operations are not supported in the vertex stage. They are only available in the fragment and compute stages."),wf):Af:wf:e.access}getStorageAccess(e,t){return bU[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const s=this.getNodeAccess(e,n);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new AN(r.name,r.node,o,s):new wN(r.name,r.node,o,s):"cubeTexture"===t||"cubeDepthTexture"===t?i=new EN(r.name,r.node,o,s):"texture3D"===t&&(i=new AN(r.name,r.node,o,s)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(SU[n]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store||null!==e.gatherNode){const e=new TI(`${r.name}_sampler`,r.node,o);e.setVisibility(SU[n]),u.push(e,i),a=[e,i]}else u.push(i),a=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=this.getSharedDataFromNode(e);let l=s.buffer;if(void 0===l){l=new("buffer"===t?vN:EI)(e,o),s.buffer=l}l.setVisibility(l.getVisibility()|SU[n]),u.push(l),a=l,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[l];void 0===e&&(e=new xN(l,o),e.setVisibility(hP.VERTEX|hP.FRAGMENT|hP.COMPUTE),this.uniformGroups[l]=e),-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(r,t);const n=a.name,i=e.uniforms.some(e=>e.name===n);i||e.addUniform(a)}s.uniformGPU=a}return r}getBuiltin(e,t,n,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:n}),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,n=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${n.vars}\n${n.code}\n`;return n.result&&(r+=`\treturn ${n.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")+".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=[],n=this.directives[e];if(void 0!==n)for(const e of n)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`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,n,i,r){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i,isAtomic:r}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:i,bufferCount:r,isAtomic:s}of this.scopedArrays.values()){let a=this.getType(i);!0===s&&(a=`atomic<${a}>`),t.push(`var<${n}> ${e}: array< ${a}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","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 n=this.getAttributesArray();for(let e=0,i=n.length;e"),t.push(`\t${i+n.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null,i=""){let r=`var${i} ${t} : `;return r+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),r}getVars(e,t=!1){let n="";t&&(n="");const i=[],r=this.vars[e];if(void 0!==r)for(const e of r)i.push(`${this.getVar(e.type,e.name,e.count,n)};`);return t?i.join("\n"):`\n\t${i.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];let r=0;for(let s=0;sn.value.itemSize;return i&&!r}getUniforms(e){const t=this.renderer.backend,n=this.uniforms[e],i=[],r=[],s=[],a={};for(const s of n){const n=s.groupNode.name,o=this.bindingsIndexes[n];if("texture"===s.type||"cubeTexture"===s.type||"cubeDepthTexture"===s.type||"storageTexture"===s.type||"texture3D"===s.type){const n=s.node,r=n.value;let a;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==n.isStorageTextureNode||null!==n.gatherNode)&&(this.isSampleCompare(r)&&n.isSampleCompare()?i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name}_sampler : sampler_comparison;`):i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name}_sampler : sampler;`));let l="";const{primarySamples:u}=t.utils.getTextureSampleData(r);if(u>1&&(l="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)a="texture_depth_cube";else if(!0===r.isCubeTexture)a="texture_cube";else if(!0===r.isDepthTexture)a=t.compatibilityMode&&null===r.compareFunction?`texture${l}_2d`:`texture_depth${l}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===s.node.isStorageTextureNode){const n=fU(r,t.device),i=this.getStorageAccess(s.node,e),o=s.node.value.is3DTexture,l=s.node.value.isArrayTexture;a=`texture_storage_${o?"3d":"2d"+(l?"_array":"")}<${n}, ${i}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture){a=`texture_2d_array<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}else if(!0===r.is3DTexture||!0===r.isData3DTexture){a=`texture_3d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}else{a=`texture${l}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${s.name} : ${a};`)}else if("buffer"===s.type||"storageBuffer"===s.type||"indirectStorageBuffer"===s.type){const t=s.node,n=this.getType(t.getNodeType(this)),i=t.bufferCount,a=i>0&&"buffer"===s.type?", "+i:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(s))r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${l}> ${s.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${a} >`;r.push(this._getWGSLStructBinding(s.name,e,l,o.binding++,o.group))}}else{const e=s.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const n=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));n.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=i),a[e]={index:i.index,id:i.id,snippets:n}}}}}for(const e in a){const t=a[e];s.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...i,...r,...s].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,n),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=this.flowCode[t];const s=this.flowNodes[t],a=s[s.length-1],o=a.outputNode,l=void 0!==o&&!0===o.isOutputStructNode;for(const e of s){const n=this.getFlowData(e),s=e.name;if(s&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${s}\n`),r+=`${n.code}\n\t`,e===a&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.builtinClipSpace = ${n.result};`;else if("fragment"===t)if(l)i.returnType=o.getNodeType(this),i.structs+="var output : "+i.returnType+";",r+=`return ${n.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`;const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",e),i.structs+="\nvar output : OutputStruct;",r+=`output.color = ${this.format(n.result,a.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}i.flow=r}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.compute.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return wU[e]||e}isAvailable(e){let t=TU[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),TU[e]=t),t}_getWGSLMethod(e){return void 0!==AU[e]&&this._include(e),RU[e]}_include(e){const t=AU[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${NU}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[n,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${n}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// local vars\n\t${this.allowGlobalVariables?"":e.vars}\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${n} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}const LU=new PI,DU=new LI,IU=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32"]],[Uint32Array,["uint32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&IU.set(Float16Array,["float16"]);const UU=new Map([[or,["float16"]]]),FU=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class OU{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const a=i.device;let o,l=n.array;if(!1===e.normalized&&!0!==e.isInterleavedBufferAttribute)if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let e=0;e1&&n.itemSize*l.BYTES_PER_ELEMENT%4!=0){const e=n.itemSize*l.BYTES_PER_ELEMENT;o=4*Math.floor((e+3)/4)/l.BYTES_PER_ELEMENT}if(void 0!==o){const e=n.itemSize,t=new l.constructor(n.count*o);for(let i=0;i1&&e%4!=0&&(e=4*Math.floor((e+3)/4))),a={arrayStride:e,attributes:[],stepMode:t},n.set(s,a)}const o=this._getVertexFormat(i),l=!0===i.isInterleavedBufferAttribute?i.offset*r:0;a.attributes.push({shaderLocation:e,offset:l,format:o})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){const r=this.backend,s=r.device,a=r.get(this._getBufferAttribute(e)).buffer,o=-1===i?a.size-n:i;let l;if(null!==t&&t.isReadbackBuffer){const e=r.get(t);if(!0===t._mapped)throw new Error("THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,void 0===e.readBufferGPU){LU.label=`${t.name}_readback`,LU.size=t.maxByteLength,LU.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=s.createBuffer(LU),LU.reset();const n=()=>{t.buffer=null,t._mapped=!1,l.unmap()},i=()=>{t.buffer=null,t._mapped=!1,l.destroy(),r.delete(t),t.removeEventListener("release",n),t.removeEventListener("dispose",i)};t.addEventListener("release",n),t.addEventListener("dispose",i),e.readBufferGPU=l}else l=e.readBufferGPU}else LU.label=`${e.name}_readback`,LU.size=o,LU.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=s.createBuffer(LU),LU.reset();DU.label=`readback_encoder_${e.name}`;const u=s.createCommandEncoder(DU);DU.reset(),u.copyBufferToBuffer(a,n,l,0,o);if(CI(s,u.finish()),await l.mapAsync(GPUMapMode.READ,0,o),null===t){const e=l.getMappedRange(0,o).slice();return l.destroy(),e}if(t.isReadbackBuffer)return t.buffer=l.getMappedRange(0,o),t;{const e=l.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),l.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,i=e.array.constructor,r=e.constructor;let s;if(1===t)s=FU.get(i);else{const e=(UU.get(r)||IU.get(i))[n?1:0];if(e){const n=i.BYTES_PER_ELEMENT*t,r=4*Math.floor((n+3)/4)/i.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");s=`${e}x${r}`}}return s||Yt("WebGPUAttributeUtils: Vertex format not supported yet."),s}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const BU=new NI,kU=new PI,zU=new zI;class VU{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class GU{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,n=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const r=this._createLayoutEntries(e),s=uf(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(s);return void 0===a&&(a=new VU(n.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(s,a)),a.usedTimes++,i.layout=a,i.layoutKey=s,a.layoutGPU}createBindings(e,t,n,i=0){const{backend:r}=this,s=r.get(e),a=this.createBindingsLayout(e);let o;""!==n&&(void 0===s.groups&&(s.groups={},s.versions={}),s.versions[n]===i&&(o=s.groups[n])),void 0===o&&(o=this.createBindGroup(e,a),""!==n&&(s.groups[n]=o,s.versions[n]=i)),s.group=o}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,r=t.get(e).buffer,s=e.updateRanges;if(0===s.length)n.queue.writeBuffer(r,0,i,0);else{const e=Gt(i),t=e?1:i.BYTES_PER_ELEMENT;let a=s[0].start;for(let o=0,l=s.length;o1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${n}-${i}`,s=e[r],void 0===s){const a=vI;let o;o=t.isSampledCubeTexture?gI:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?mI:t.isSampledTexture3D?_I:fI,zU.aspect=a,zU.dimension=o,zU.mipLevelCount=n,zU.baseMipLevel=i,s=e[r]=e.texture.createView(zU),zU.reset()}}BU.entries.push({binding:r,resource:s})}else if(t.isSampler){const e=n.get(t);BU.entries.push({binding:r,resource:e.sampler})}r++}const s=i.createBindGroup(BU);return BU.reset(),s}_createLayoutEntries(e){const t=[];let n=0;for(const i of e.bindings){const e=this.backend,r={binding:n,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&hP.COMPUTE?i.access===Af||i.access===Ef?e.type=eI:e.type=tI:i.nodeUniform&&i.nodeUniform.isAtomic&&i.visibility&hP.FRAGMENT?e.type=eI:e.type=tI),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===Af?rI:t===Ef?nI:iI,i.texture.isArrayTexture?e.viewDimension=mI:i.texture.is3DTexture&&(e.viewDimension=_I),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:n}=e.utils.getTextureSampleData(i.texture);if(n>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=lI)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=lI:t.sampleType=uI;else{const e=i.texture.type;e===me?t.sampleType=cI:e===ge?t.sampleType=hI:!0!==i.texture.normalized||e!==pe&&e!==fe?e===_e&&(this.backend.hasFeature("float32-filterable")?t.sampleType=oI:t.sampleType=lI):t.sampleType=lI}i.isSampledCubeTexture?t.viewDimension=gI:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=mI:i.isSampledTexture3D&&(t.viewDimension=_I),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&i.textureNode.isSampleCompare()&&e.hasCompatibility(Bt)?t.type=aI:t.type=sI),r.sampler=t}else Yt(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,0===n.layout.usedTimes&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class HU{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}const WU=new class{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}},jU=new class{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}},$U=new DI,XU=new FI;class qU{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:i,geometry:r,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:n}=e.layout;d.push(n)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;0===i.blending||1===i.blending&&!1===i.transparent||(f=this._getBlending(i));let m={};!0===i.stencilWrite&&(m={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(null!==e.context.textures){const t=e.context.textures,n=e.context.mrt;for(let e=0;e1,XU.layout=M;const w={},E=e.context.depth,A=e.context.stencil;!0!==E&&!0!==A||(!0===E&&(w.format=S,w.depthWriteEnabled=i.depthWrite,w.depthCompare=x),!0===A&&(w.stencilFront=m,w.stencilBack=m,w.stencilReadMask=i.stencilFuncMask,w.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&b.topology===cP&&(w.depthBias=i.polygonOffsetUnits,w.depthBiasSlopeScale=i.polygonOffsetFactor,w.depthBiasClamp=0),XU.depthStencil=w),u.pushErrorScope("validation");const R=[{program:a,module:v.module},{program:o,module:y.module}],C=XU.label;if(null===t)h.pipeline=u.createRenderPipeline(XU),XU.reset(),u.popErrorScope().then(e=>{null!==e&&(h.error=!0,Yt(`WebGPURenderer: Render pipeline creation failed (${C}): ${e.message}`),this._reportShaderDiagnostics(R,C))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=u.createRenderPipelineAsync(XU)}catch(t){e=t}if(XU.reset(),null!==t)try{h.pipeline=await t}catch(t){e=t}const n=await u.popErrorScope();if(null!==n||null!==e){h.error=!0;const t=n&&n.message||e&&e.message||"unknown";Yt(`WebGPURenderer: Async render pipeline creation failed (${C}): ${t}`),await this._reportShaderDiagnostics(R,C)}}finally{e()}});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:i,device:r}=n,s=i.getCurrentDepthStencilFormat(e),a=i.getCurrentColorFormats(e),o=this._getSampleCount(e);$U.label=t,$U.colorFormats=a,$U.depthStencilFormat=s,$U.sampleCount=o;const l=r.createRenderBundleEncoder($U);return $U.reset(),l}createComputePipeline(e,t,n=null){const i=this.backend,r=i.device,s=i.get(e.computeProgram).module,a=i.get(e),o=[];for(const e of t){const t=i.get(e),{layoutGPU:n}=t.layout;o.push(n)}const l=e.computeProgram,u=`computePipeline_${l.stage}${l.name?`_${l.name}`:""}`;r.pushErrorScope("validation"),jU.bindGroupLayouts=o;const c=r.createPipelineLayout(jU);if(jU.reset(),WU.label=u,WU.compute=s,WU.layout=c,null===n)a.pipeline=r.createComputePipeline(WU),WU.reset(),r.popErrorScope().then(e=>{null!==e&&(a.error=!0,Yt(`WebGPURenderer: Compute pipeline creation failed (${u}): ${e.message}`),this._reportShaderDiagnostics([{program:l,module:s.module}],u))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=r.createComputePipelineAsync(WU)}catch(t){e=t}if(WU.reset(),null!==t)try{a.pipeline=await t}catch(t){e=t}const n=await r.popErrorScope();if(null!==n||null!==e){a.error=!0;const t=n&&n.message||e&&e.message||"unknown";Yt(`WebGPURenderer: Async compute pipeline creation failed (${u}): ${t}`),await this._reportShaderDiagnostics([{program:l,module:s.module}],u)}}finally{e()}});n.push(e)}}async _reportShaderDiagnostics(e,t){for(const{program:n,module:i}of e){const e=await i.getCompilationInfo();if(0===e.messages.length)continue;const r=n.code.split("\n");for(const i of e.messages){const e=i.lineNum>0?` at line ${i.lineNum}${i.linePos>0?`:${i.linePos}`:""}`:"",s=`WebGPURenderer [${t} / ${n.stage} ${i.type}]${e}: ${i.message}`;let a="";i.lineNum>0&&i.lineNum<=r.length&&(a=`\n ${r[i.lineNum-1]}`,i.linePos>0&&(a+=`\n ${" ".repeat(i.linePos-1)}^`)),("error"===i.type?Yt:qt)(s+a)}}}_getBlending(e){let t,n;const i=e.blending,r=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:kD},n={srcFactor:r,dstFactor:s,operation:kD}};if(e.premultipliedAlpha)switch(i){case 1:r(AD,PD,AD,PD);break;case 2:r(AD,AD,AD,AD);break;case 3:r(ED,CD,ED,AD);break;case 4:r(LD,PD,ED,AD)}else switch(i){case 1:r(ND,PD,AD,PD);break;case 2:r(ND,AD,AD,AD);break;case 3:Yt(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:Yt(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};Yt("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case v:t=ED;break;case 201:t=AD;break;case 202:t=RD;break;case 203:t=CD;break;case S:t=ND;break;case T:t=PD;break;case 208:t=LD;break;case 209:t=DD;break;case 206:t=ID;break;case 207:t=UD;break;case 210:t=FD;break;case 211:case 213:t=OD;break;case 212:case 214:t=BD;break;default:Yt("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=dP;break;case 519:t=yP;break;case 513:t=pP;break;case 515:t=mP;break;case 514:t=fP;break;case 518:t=vP;break;case 516:t=gP;break;case 517:t=_P;break;default:Yt("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case St:t=$D;break;case 0:t=XD;break;case 7681:t=qD;break;case 5386:t=YD;break;case 7682:t=KD;break;case 7683:t=ZD;break;case 34055:t=QD;break;case 34056:t=JD;break;default:Yt("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case p:t=kD;break;case 101:t=zD;break;case 102:t=VD;break;case 103:t=GD;break;case 104:t=HD;break;default:Yt("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?RP:CP);let s=1===n.side;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(s=!s),i.frontFace=!0===s?wP:MP,i.cullMode=2===n.side?EP:AP,i}_getColorWriteMask(e){return!0===e.colorWrite?jD:WD}_getDepthCompare(e){let t;if(!1===e.depthTest)t=yP;else{const n=this.backend.parameters.reversedDepthBuffer?Qt[e.depthFunc]:e.depthFunc;switch(n){case 0:t=dP;break;case 1:t=yP;break;case 2:t=pP;break;case 3:t=mP;break;case 4:t=fP;break;case 5:t=vP;break;case 6:t=gP;break;case 7:t=_P;break;default:Yt("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class YU{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}}const KU=new PI,ZU=new LI,QU=new YU;class JU extends iP{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,QU.label=`queryset_global_timestamp_${t}`,QU.type="timestamp",QU.count=this.maxQueries,this.querySet=this.device.createQuerySet(QU),QU.reset();const i=8*this.maxQueries;KU.label=`buffer_timestamp_resolve_${t}`,KU.size=i,KU.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(KU),KU.reset(),KU.label=`buffer_timestamp_result_${t}`,KU.size=i,KU.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(KU),KU.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear());const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder(ZU);i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const r=i.finish();if(CI(this.device,r),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),a={},o=[];this.timestamps.clear();for(const[t,n]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=s[n],l=s[n+1],u=Number(l-r)/1e6;this.timestamps.set(t,u),a[i]+=u}const l=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=o,l}catch(e){return Yt("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){Yt("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){Yt("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.pendingResolve=null}}}class eF{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}}const tF={r:0,g:0,b:0,a:1},nF={r:0,g:0,b:0,a:0},iF=new PI,rF=new LI,sF=new class{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}},aF=new YU,oF=new BI,lF=new class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},uF=new QI,cF=new QI,hF=new kI,dF=new zI,pF=new JI;class fF extends kN{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new RI(this),this.attributeUtils=new OU(this),this.bindingUtils=new GU(this),this.capabilities=new HU(this),this.pipelineUtils=new qU(this),this.textureUtils=new pU(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[Bt]:t}}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const i={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},r="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(i):null;if(null===r)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");const s=Object.values(xI),a=[];for(const e of s)r.features.has(e)&&a.push(e);const o={requiredFeatures:a,requiredLimits:t.requiredLimits};n=await r.requestDevice(o)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(t=>{if("destroyed"===t.reason)return;const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}),n.onuncapturederror=t=>{const n=t.error,i=n&&n.constructor?n.constructor.name:"GPUError",r=n&&n.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:i,message:r,originalEvent:t})},this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(xI.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,n=null){const i=this.get(e.texture);i.texture=t,i.format=t.format,i.externalTexture=!0,i.xrViewDescriptors=n,i.initialized=!0}get context(){const t=this.renderer.getCanvasTarget(),n=this.get(t);let i=n.context;if(void 0===i){const r=this.parameters;i=!0===t.isDefaultCanvasTarget&&void 0!==r.context?r.context:t.domElement.getContext("webgpu"),"setAttribute"in t.domElement&&t.domElement.setAttribute("data-engine",`three.js r${e} webgpu`);const s=r.alpha?"premultiplied":"opaque",a=r.outputType===ve?"extended":"standard";i.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:s,toneMapping:{mode:a}}),n.context=i}return i}get coordinateSystem(){return Ut}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),i=e.currentSamples;let r=n.descriptor;if(void 0===r||n.samples!==i){if(r=new UI,r.colorAttachments.push(new II),!0===e.depth||!0===e.stencil){const t=new eF;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),r.depthStencilAttachment=t}const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,n.descriptor=r,n.samples=i}const s=r.colorAttachments[0];return i>0?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){const t=e.camera;return e.depthTexture&&!0===e.depthTexture.isArrayTexture&&null!==t&&!0===t.isArrayCamera}_hasExternalTexture(e){const t=e.textures;if(null===t)return!1;for(let e=0;e1)if(!0===u){const t=e.camera.cameras;for(let e=0;e0?(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,aF.label=`occlusionQuerySet_${e.id}`,aF.type="occlusion",aF.count=i,r=n.createQuerySet(aF),aF.reset(),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null):void 0!==t.lastOcclusionObject&&(t.lastOcclusionObject=void 0,t.occlusionQuerySet.destroy(),t.occlusionQuerySet=void 0),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:SP}),this.initTimestampQuery(Ot,this.getTimestampUID(e),s),s.occlusionQuerySet=r;const a=s.depthStencilAttachment,o=e.renderTarget,l=e.sampleCount>1&&!1===o?.storeMultisampledColorBuffer,u=e.sampleCount>1&&!1===o?.storeMultisampledDepthBuffer,c=e.sampleCount>1&&!1===o?.storeMultisampledStencilBuffer,h=!0===e.fullscreenPass&&this._hasExternalTexture(e);if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n1&&!1===r?.storeMultisampledDepthBuffer,a=e.sampleCount>1&&!1===r?.storeMultisampledStencilBuffer;for(let r=0;r0&&t.currentPass.executeBundles(t.renderBundles);const i=t.lastOcclusionObject;i&&!0===i.occlusionTest&&t.currentPass.endOcclusionQuery();const r=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const n=this._finishArrayCameraBundleEncoders(t),i=t.arrayCameraRenderStages;i.push({bundles:n});for(let n=0;ne.loadOp),o=s.colorAttachments.map(e=>e.storeOp),l=s.depthStencilAttachment?.depthLoadOp,u=s.depthStencilAttachment?.depthStoreOp,c=s.depthStencilAttachment?.stencilLoadOp,h=s.depthStencilAttachment?.stencilStoreOp;for(let t=0;t0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(iF.size=i,iF.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,r=this.device.createBuffer(iF),iF.reset(),this.occludedResolveCache.set(i,r)),iF.size=i,iF.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const s=this.device.createBuffer(iF);iF.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(CI(this.device,t.encoder.finish()),null!==e.textures){const t=e.textures;for(let e=0;eo&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),s.dispatchSize=r}r=s.dispatchSize}o.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),CI(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,n,i,r,s,a,o,l,u=-1){const{object:c,material:h,context:d}=e,p=e.getIndex(),f=null!==p;l.pipeline!==i&&(o.setPipeline(i),l.pipeline=i);const m=l.bindingGroups;for(let e=0,t=r.length;e0){const r=this.get(e.camera),a=e.camera.cameras,h=e.getBindingGroup("cameraIndex");if(void 0===r.indexesGPU||r.indexesGPU.length!==a.length){const e=this.get(h),t=[],n=new Uint32Array([0,0,0,0]);for(let i=0,r=a.length;i(qt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new aP(e)));super(new t(e),e),this.library=new _F,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const yF={type:"change"},bF={type:"start"},xF={type:"end"},SF=1e-6,TF=-1,MF=0,wF=1,EF=2,AF=3,RF=4,CF=new dn,NF=new dn,PF=new fn,LF=new fn,DF=new fn,IF=new pn,UF=new fn,FF=new fn,OF=new fn,BF=new fn;class kF extends Xa{constructor(e,r=null){super(e,r),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.rollSpeed=1,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.multiTouchRoll=!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:t,MIDDLE:n,RIGHT:i},this.target=new fn,this.state=TF,this.keyState=TF,this._lastPosition=new fn,this._lastUp=new fn,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._touchRollAngle=0,this._touchRollPointerIds="",this._lastAngle=0,this._lastRollAngle=0,this._eye=new fn,this._movePrev=new dn,this._moveCurr=new dn,this._lastAxis=new fn,this._zoomStart=new dn,this._zoomEnd=new dn,this._panStart=new dn,this._panEnd=new dn,this._pointers=[],this._pointerPositions={},this._onPointerMove=VF.bind(this),this._onPointerDown=zF.bind(this),this._onPointerUp=GF.bind(this),this._onPointerCancel=HF.bind(this),this._onContextMenu=KF.bind(this),this._onMouseWheel=YF.bind(this),this._onKeyDown=jF.bind(this),this._onKeyUp=WF.bind(this),this._onTouchStart=ZF.bind(this),this._onTouchMove=QF.bind(this),this._onTouchEnd=JF.bind(this),this._onMouseDown=$F.bind(this),this._onMouseMove=XF.bind(this),this._onMouseUp=qF.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!==r&&(this.connect(r),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){if(this._eye.subVectors(this.object.position,this.target),this.noRotate||(this._rotateCamera(),!0===this.multiTouchRoll&&this._rollCamera()),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);const e=this._lastPosition.distanceToSquared(this.object.position)>SF,t=this._lastUp.distanceToSquared(this.object.up)>SF;(e||t)&&(this.dispatchEvent(yF),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up))}else if(this.object.isOrthographicCamera){this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>SF,t=this._lastUp.distanceToSquared(this.object.up)>SF,n=this._lastZoom!==this.object.zoom;(e||t||n)&&(this.dispatchEvent(yF),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom)}else console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=TF,this.keyState=TF,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(yF),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom}_panCamera(){if(NF.copy(this._panEnd).sub(this._panStart),NF.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;NF.x*=e,NF.y*=t}NF.multiplyScalar(this._eye.length()*this.panSpeed),LF.copy(this._eye).cross(this.object.up).setLength(NF.x),LF.add(PF.copy(this.object.up).setLength(NF.y)),this.object.position.add(LF),this.target.add(LF),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(NF.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){BF.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=BF.length();e?(this._eye.copy(this.object.position).sub(this.target),UF.copy(this._eye).normalize(),FF.copy(this.object.up).normalize(),OF.crossVectors(FF,UF).normalize(),FF.setLength(this._moveCurr.y-this._movePrev.y),OF.setLength(this._moveCurr.x-this._movePrev.x),BF.copy(FF.add(OF)),DF.crossVectors(BF,this._eye).normalize(),e*=this.rotateSpeed,IF.setFromAxisAngle(DF,e),this._eye.applyQuaternion(IF),this.object.up.applyQuaternion(IF),this._lastAxis.copy(DF),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),IF.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(IF),this.object.up.applyQuaternion(IF)),this._movePrev.copy(this._moveCurr)}_rollCamera(){const e=this._getTouchRollAngle();if(e)this._lastRollAngle=e*this.rollSpeed;else{if(this.staticMoving||!this._lastRollAngle)return;this._lastRollAngle*=Math.sqrt(1-this.dynamicDampingFactor)}UF.copy(this._eye).normalize(),IF.setFromAxisAngle(UF,this._lastRollAngle),this.object.up.applyQuaternion(IF)}_getTouchRollAngle(){const e=this._pointers[0],t=this._pointers[1];if(void 0===t||"touch"!==e.pointerType||"touch"!==t.pointerType)return this._touchRollPointerIds="",0;const n=`${e.pointerId},${t.pointerId}`,i=this._pointerPositions[e.pointerId],r=this._pointerPositions[t.pointerId],s=Math.atan2(r.y-i.y,r.x-i.x);if(n!==this._touchRollPointerIds)return this._touchRollPointerIds=n,this._touchRollAngle=s,0;let a=s-this._touchRollAngle;return this._touchRollAngle=s,a>Math.PI?a-=2*Math.PI:a<-Math.PI&&(a+=2*Math.PI),a}_zoomCamera(){let e;this.state===RF?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=hn.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=hn.clamp(this.object.zoom/e,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 CF.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),CF}_getMouseOnCircle(e,t){return CF.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),CF}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tthis.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()Math.PI&&(n-=oO),i<-Math.PI?i+=oO:i>Math.PI&&(i-=oO),this._spherical.theta=n<=i?Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,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 r=!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),r=e!=this._spherical.radius}if(aO.setFromSpherical(this._spherical),aO.applyQuaternion(this._quatInverse),t.copy(this.target).add(aO),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 e=null;if(this.object.isPerspectiveCamera){const t=aO.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),r=!!n}else if(this.object.isOrthographicCamera){const t=new fn(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=n!==this.object.zoom;const i=new fn(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=aO.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(iO.origin.copy(this.object.position),iO.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(iO.direction))gO||8*(1-this._lastQuaternion.dot(this.object.quaternion))>gO||this._lastTargetPosition.distanceToSquared(this.target)>gO)&&(this.dispatchEvent(eO),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?oO/60*this.autoRotateSpeed*e:oO/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){aO.setFromMatrixColumn(t,0),aO.multiplyScalar(-e),this._panOffset.add(aO)}_panUp(e,t){!0===this.screenSpacePanning?aO.setFromMatrixColumn(t,1):(aO.setFromMatrixColumn(t,0),aO.crossVectors(this.object.up,aO)),aO.multiplyScalar(e),this._panOffset.add(aO)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;aO.copy(i).sub(this.target);let r=aO.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.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 n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(oO*this._rotateDelta.x/t.clientHeight),this._rotateUp(oO*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(oO*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(-oO*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(oO*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(-oO*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),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+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),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(n,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(oO*this._rotateDelta.x/t.clientHeight),this._rotateUp(oO*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),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,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),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+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 s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tPO||8*(1-this._lastQuaternion.dot(t.quaternion))>PO)&&(this.dispatchEvent(NO),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 IO(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 UO(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 FO(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 OO(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function BO(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 kO(){!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 zO(e){!1!==this.enabled&&e.preventDefault()}const VO={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 GO{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 HO=new Ra(-1,1,1,-1,0,1);const WO=new class extends br{constructor(){super(),this.setAttribute("position",new lr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lr([0,2,0,0,2,0],2))}};class jO{constructor(e){this._mesh=new qr(WO,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,HO)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class $O extends GO{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof js?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=Ws.clone(e.uniforms),this.material=new js({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new jO(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.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 XO extends GO{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=e.getContext(),r=e.state;let s,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),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 qO extends GO{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class YO{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new dn);this._width=n.width,this._height=n.height,(t=new Un(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ve})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new $O(VO),this.copyPass.material.blending=0,this.timer=new Ba}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;t1?i-1:0),s=1;s=0&&r<1?(o=s,l=a):r>=1&&r<2?(o=a,l=s):r>=2&&r<3?(l=s,u=a):r>=3&&r<4?(l=a,u=s):r>=4&&r<5?(o=a,u=s):r>=5&&r<6&&(o=s,u=a);var c=n-s/2;return i(o+c,l+c,u+c)}var lB={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 uB=/^#[a-fA-F0-9]{6}$/,cB=/^#[a-fA-F0-9]{8}$/,hB=/^#[a-fA-F0-9]{3}$/,dB=/^#[a-fA-F0-9]{4}$/,pB=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,fB=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,mB=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,gB=/^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 _B(e){if("string"!=typeof e)throw new rB(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return lB[t]?"#"+lB[t]:e}(e);if(t.match(uB))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(cB)){var n=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:n}}if(t.match(hB))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(dB)){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=pB.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=fB.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=mB.exec(t);if(a){var o="rgb("+oB(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=pB.exec(o);if(!l)throw new rB(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=gB.exec(t.substring(0,50));if(u){var c="rgb("+oB(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=pB.exec(c);if(!h)throw new rB(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new rB(5)}function vB(e){return function(e){var t,n=e.red/255,i=e.green/255,r=e.blue/255,s=Math.max(n,i,r),a=Math.min(n,i,r),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(i-r)/l+(i=1?MB(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new rB(7)}function EB(e){if("object"!=typeof e)throw new rB(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return wB(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 MB(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,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=1?TB(e.hue,e.saturation,e.lightness):"rgba("+oB(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new rB(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,n){if("object"==typeof e&&void 0===t&&void 0===n)return TB(e.hue,e.saturation,e.lightness);throw new rB(1)}(e);throw new rB(8)}function AB(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):AB(e,t,i)}}function RB(e){return AB(e,e.length,[])}function CB(e,t,n){return Math.max(e,Math.min(t,n))}RB(function(e,t){if("transparent"===t)return t;var n=vB(t);return EB(ZO({},n,{hue:n.hue+parseFloat(e)}))}),RB(function(e,t){if("transparent"===t)return t;var n=vB(t);return EB(ZO({},n,{lightness:CB(0,1,n.lightness-parseFloat(e))}))}),RB(function(e,t){if("transparent"===t)return t;var n=vB(t);return EB(ZO({},n,{saturation:CB(0,1,n.saturation-parseFloat(e))}))}),RB(function(e,t){if("transparent"===t)return t;var n=vB(t);return EB(ZO({},n,{lightness:CB(0,1,n.lightness+parseFloat(e))}))});var NB=RB(function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var i=_B(t),r=ZO({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),s=_B(n),a=ZO({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o===-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return wB({red:Math.floor(r.red*u+a.red*c),green:Math.floor(r.green*u+a.green*c),blue:Math.floor(r.blue*u+a.blue*c),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),PB=NB;var LB=RB(function(e,t){if("transparent"===t)return t;var n=_B(t);return wB(ZO({},n,{alpha:CB(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))}),DB=LB;RB(function(e,t){if("transparent"===t)return t;var n=vB(t);return EB(ZO({},n,{saturation:CB(0,1,n.saturation+parseFloat(e))}))}),RB(function(e,t){return"transparent"===t?t:EB(ZO({},vB(t),{hue:parseFloat(e)}))}),RB(function(e,t){return"transparent"===t?t:EB(ZO({},vB(t),{lightness:parseFloat(e)}))}),RB(function(e,t){return"transparent"===t?t:EB(ZO({},vB(t),{saturation:parseFloat(e)}))}),RB(function(e,t){return"transparent"===t?t:PB(parseFloat(e),"rgb(0, 0, 0)",t)}),RB(function(e,t){return"transparent"===t?t:PB(parseFloat(e),"rgb(255, 255, 255)",t)}),RB(function(e,t){if("transparent"===t)return t;var n=_B(t);return wB(ZO({},n,{alpha:CB(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var IB=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-IB.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*IB.Bounce.In(2*e):.5*IB.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e1e4?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}}}}),UB=function(){return performance.now()},FB=function(){function e(){for(var e=[],t=0;t0;){this._tweensAddedDuringUpdate={};for(var i=0;i1?s(e[n],e[n-1],n-i):s(e[r],e[r+1>n?n:r+1],i-r)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},BB=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),kB=new FB,zB=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=IB.Linear.None,this._interpolationFunction=OB.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=BB.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=kB,kB.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=UB()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];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,n,i,r){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;hl)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,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=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),HB.hasOwnProperty(t)?{space:HB[t],local:e}:e}function jB(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===GB&&t.documentElement.namespaceURI===GB?t.createElement(e):t.createElementNS(n,e)}}function $B(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function XB(e){var t=WB(e);return(t.local?$B:jB)(t)}function qB(){}function YB(e){return null==e?qB:function(){return this.querySelector(e)}}function KB(){return[]}function ZB(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function QB(e){return function(t){return t.matches(e)}}var JB=Array.prototype.find;function ek(){return this.firstElementChild}var tk=Array.prototype.filter;function nk(){return Array.from(this.children)}function ik(e){return new Array(e.length)}function rk(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function sk(e,t,n,i,r,s){for(var a,o=0,l=t.length,u=s.length;ot?1:e>=t?0:NaN}function ck(e){return function(){this.removeAttribute(e)}}function hk(e){return function(){this.removeAttributeNS(e.space,e.local)}}function dk(e,t){return function(){this.setAttribute(e,t)}}function pk(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function fk(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function mk(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function gk(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function _k(e){return function(){this.style.removeProperty(e)}}function vk(e,t,n){return function(){this.style.setProperty(e,t,n)}}function yk(e,t,n){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function bk(e){return function(){delete this[e]}}function xk(e,t){return function(){this[e]=t}}function Sk(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function Tk(e){return e.trim().split(/^|\s+/)}function Mk(e){return e.classList||new wk(e)}function wk(e){this._node=e,this._names=Tk(e.getAttribute("class")||"")}function Ek(e,t){for(var n=Mk(e),i=-1,r=t.length;++i=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var qk=[null];function Yk(e,t){this._groups=e,this._parents=t}Yk.prototype={constructor:Yk,select:function(e){"function"!=typeof e&&(e=YB(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r=b&&(b=y+1);!(v=g[b])&&++b=0;)(i=r[s])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=uk);for(var n=this._groups,i=n.length,r=new Array(i),s=0;s1?this.each((null==t?_k:"function"==typeof t?yk:vk)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||gk(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?bk:"function"==typeof t?Sk:xk)(e,t)):this.node()[e]},classed:function(e,t){var n=Tk(e+"");if(arguments.length<2){for(var i=Mk(this.node()),r=-1,s=n.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?Wk:Hk,i=0;it&&ez.sort(iz),e=ez.shift(),t=ez.length,xz(e)}finally{ez.length=Mz.__r=0}}function wz(e,t,n,i,r,s,a,o,l,u,c){var h,d,p,f,m,g,_=i&&i.__k||dz,v=t.length;for(l=Ez(n,t,_,l,v),h=0;h0?a=e.__k[s]=_z(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=Rz(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(r>c?d--:rl?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s(c?1:0))for(r=n-1,s=n+1;r>=0||s=0?r--:s++])&&!(2&u.__u)&&o==u.key&&l==u.type)return a;return-1}function Cz(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||pz.test(t)?n:n+"px"}function Nz(e,t,n,i,r){var s,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)n&&t in n||Cz(e.style,t,"");if(n)for(t in n)i&&n[t]==i[t]||Cz(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(oz,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?i?n[az]=i[az]:(n[az]=lz,e.addEventListener(t,s?cz:uz,s)):e.removeEventListener(t,s?cz:uz,s);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function Pz(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t[sz])t[sz]=lz++;else if(t[sz]0?e:fz(e)?e.map(Uz):void 0!==e.constructor?null:mz({},e)}function Fz(e,t,n,i,r,s,a,o,l){var u,c,h,d,p,f,m,g=n.props||hz,_=t.props,v=t.type;if("svg"==v?r="http://www.w3.org/2000/svg":"math"==v?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u2&&(a.children=arguments.length>3?Kk.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return _z(e,a,i,r,null)}(vz,null,[e]),i||hz,hz,t.namespaceURI,i?null:t.firstChild?Kk.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,s),Iz(r,e,s),e.props.children=null}function Vz(e,t,n){var i,r,s,a,o=mz({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?i=t[s]:"ref"==s?r=t[s]:o[s]=void 0===t[s]&&null!=a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?Kk.call(arguments,2):n),_z(e.type,o,i||e.key,r||e.ref,null)}function Gz(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===n?{}:n,r=function(e){return"string"==typeof e?new Yk([[document.querySelector(e)]],[document.documentElement]):new Yk([[e]],qk)}(!!e&&"object"===$z(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var n=jz(e,2),i=n[0],r=n[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(s),function(e){t.mouseInside=!0;var n=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),s=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(s),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(s),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,n;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return Jk(Vz(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(n=e.tooltipEl.node()).__k,zz(Xz(t),n)):e.tooltipEl.text("")}});!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===n&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");const Yz=e=>{e instanceof Array?e.forEach(Yz):(e.map&&e.map.dispose(),e.dispose())},Kz=e=>{e.geometry&&e.geometry.dispose(),e.material&&Yz(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Kz)},Zz=window.THREE?window.THREE:{WebGLRenderer:class{constructor(t={}){const{canvas:n=Wt(),context:i=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:u=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:d=!1,outputBufferType:p=he}=t;let f;if(this.isWebGLRenderer=!0,null!==i){if("undefined"!=typeof WebGLRenderingContext&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=a;const m=p,g=new Set([Ie,Le,Ne]),_=new Set([he,ge,fe,xe,ye,be]),v=new Uint32Array(4),y=new Int32Array(4),b=new fn;let x=null,S=null;const T=[],M=[];let w=null;this.domElement=n,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let A=!1,R=null,C=null,N=null,P=null;this._outputColorSpace=vt;let L=0,D=0,I=null,U=-1,F=null;const O=new Dn,B=new Dn;let k=null;const z=new yi(0);let V=0,G=n.width,H=n.height,W=1,j=null,$=null;const X=new Dn(0,0,G,H),q=new Dn(0,0,G,H);let Y=!1;const K=new ts;let Z=!1,Q=!1;const J=new Bn,ee=new fn,te=new Dn,ne={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let re=!1;function se(){return null===I?W:1}let ae,oe,ue,de,pe,me,_e,Se,Te,Me,we,Ee,Ae,Re,Ce,De,Ue,Fe,Oe,Be,ke,ze,Ve,Ge=i;function He(e,t){return n.getContext(e,t)}try{const t={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:u,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${e}`),n.addEventListener("webglcontextlost",$e,!1),n.addEventListener("webglcontextrestored",Xe,!1),n.addEventListener("webglcontextcreationerror",qe,!1),null===Ge){const e="webgl2";if(Ge=He(e,t),null===Ge)throw He(e)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}We()}catch(e){throw n.removeEventListener("webglcontextlost",$e,!1),n.removeEventListener("webglcontextrestored",Xe,!1),n.removeEventListener("webglcontextcreationerror",qe,!1),Yt("WebGLRenderer: "+e.message),e}function We(){ae=new wo(Ge),ae.init(),ke=new Du(Ge,ae),oe=new ao(Ge,ae,t,ke),ue=new Pu(Ge,ae),oe.reversedDepthBuffer&&d&&ue.buffers.depth.setReversed(!0),C=Ge.createFramebuffer(),N=Ge.createFramebuffer(),P=Ge.createFramebuffer(),de=new Ro(Ge),pe=new fu,me=new Lu(Ge,ae,ue,pe,oe,ke,de),_e=new Mo(E),Se=new Ka(Ge),ze=new ro(Ge,Se),Te=new Eo(Ge,Se,de,ze),Me=new No(Ge,Te,Se,ze,de),Fe=new Co(Ge,oe,me),Ce=new oo(pe),we=new pu(E,_e,ae,oe,ze,Ce),Ee=new Bu(E,pe),Ae=new vu,Re=new Mu(ae),Ue=new io(E,_e,ue,Me,f,l),De=new Nu(E,Me,oe),Ve=new ku(Ge,de,oe,ue),Oe=new so(Ge,ae,de),Be=new Ao(Ge,ae,de),de.programs=we.programs,E.capabilities=oe,E.extensions=ae,E.properties=pe,E.renderLists=Ae,E.shadowMap=De,E.state=ue,E.info=de}m!==he&&(w=new Lo(m,n.width,n.height,o,r,s));const je=new Uu(E,Ge);function $e(e){e.preventDefault(),$t("WebGLRenderer: Context Lost."),A=!0}function Xe(){$t("WebGLRenderer: Context Restored."),A=!1;const e=de.autoReset,t=De.enabled,n=De.autoUpdate,i=De.needsUpdate,r=De.type;We(),de.autoReset=e,De.enabled=t,De.autoUpdate=n,De.needsUpdate=i,De.type=r}function qe(e){Yt("WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function Ye(e){const t=e.target;t.removeEventListener("dispose",Ye),function(e){(function(e){const t=pe.get(e).programs;void 0!==t&&(t.forEach(function(e){we.releaseProgram(e)}),e.isShaderMaterial&&we.releaseShaderCache(e))})(e),pe.remove(e)}(t)}function Ke(e,t,n,i){null!==R&&e.isNodeMaterial&&R.setObject(i,e),!0===Z&&Ce.setState(e,n,!1),!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,at(e,t,i),e.side=0,e.needsUpdate=!0,at(e,t,i),e.side=2):at(e,t,i)}this.xr=je,this.getContext=function(){return Ge},this.getContextAttributes=function(){return Ge.getContextAttributes()},this.forceContextLoss=function(){const e=ae.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=ae.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return W},this.setPixelRatio=function(e){void 0!==e&&(W=e,this.setSize(G,H,!1))},this.getSize=function(e){return e.set(G,H)},this.setSize=function(e,t,i=!0){je.isPresenting?qt("WebGLRenderer: Can't change size while VR device is presenting."):(G=e,H=t,n.width=Math.floor(e*W),n.height=Math.floor(t*W),!0===i&&(n.style.width=e+"px",n.style.height=t+"px"),null!==w&&w.setSize(n.width,n.height),this.setViewport(0,0,e,t))},this.getDrawingBufferSize=function(e){return e.set(G*W,H*W).floor()},this.setDrawingBufferSize=function(e,t,i){G=e,H=t,W=i,n.width=Math.floor(e*i),n.height=Math.floor(t*i),this.setViewport(0,0,e,t)},this.setEffects=function(e){if(m!==he){if(e)for(let t=0;t0),d=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,f=!!n.morphAttributes.color;let m=0;i.toneMapped&&(null!==I&&!0!==I.isXRRenderTarget||(m=E.toneMapping));const g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=void 0!==g?g.length:0,v=pe.get(i),y=S.state.lights;if(!0===Z&&(!0===Q||e!==F)){const t=e===F&&i.id===U;Ce.setState(i,e,t)}let x=!1;i.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching?x=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r._colorsTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r._colorsTexture||r.isInstancedMesh&&!1===v.instancing?x=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?x=!0:r.isSkinnedMesh||!0!==v.skinning?r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==u||!0===i.fog&&v.fog!==s?x=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===Ce.numPlanes&&v.numIntersection===Ce.numIntersection?(v.vertexAlphas!==c||v.vertexTangents!==h||v.morphTargets!==d||v.morphNormals!==p||v.morphColors!==f||v.toneMapping!==m||v.morphTargetsCount!==_||!!v.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(x=!0):x=!0:x=!0:x=!0:x=!0:(x=!0,v.__version=i.version);let T=v.currentProgram;!0===x&&(T=at(i,t,r),R&&i.isNodeMaterial&&R.onUpdateProgram(i,T,v));let M=!1,w=!1,A=!1;const C=T.getUniforms(),N=v.uniforms;ue.useProgram(T.program)&&(M=!0,w=!0,A=!0);i.id!==U&&(U=i.id,w=!0);if(v.needsLights){const e=function(e,t){if(0===e.length)return null;if(1===e.length)return null!==e[0].texture?e[0]:null;b.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t0&&C.setValue(Ge,"sunShadowMap",y.state.sunShadowMap,me),y.state.directionalShadowMap.length>0&&C.setValue(Ge,"directionalShadowMap",y.state.directionalShadowMap,me),y.state.spotShadowMap.length>0&&C.setValue(Ge,"spotShadowMap",y.state.spotShadowMap,me),y.state.pointShadowMap.length>0&&C.setValue(Ge,"pointShadowMap",y.state.pointShadowMap,me));if(r.isSkinnedMesh){C.setOptional(Ge,r,"bindMatrix"),C.setOptional(Ge,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(Ge,"boneTexture",e.boneTexture,me))}r.isBatchedMesh&&(C.setOptional(Ge,r,"batchingTexture"),C.setValue(Ge,"batchingTexture",r._matricesTexture,me),C.setOptional(Ge,r,"batchingIdTexture"),C.setValue(Ge,"batchingIdTexture",r._indirectTexture,me),C.setOptional(Ge,r,"batchingColorTexture"),null!==r._colorsTexture&&C.setValue(Ge,"batchingColorTexture",r._colorsTexture,me));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||Fe.update(r,n,T);(w||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,C.setValue(Ge,"receiveShadow",r.receiveShadow));(i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial)&&null===i.envMap&&null!==t.environment&&(N.envMapIntensity.value=t.environmentIntensity);void 0!==N.dfgLUT&&(N.dfgLUT.value=(null===Vu&&(Vu=new Kr(zu,16,16,Pe,ve),Vu.name="DFG_LUT",Vu.minFilter=le,Vu.magFilter=le,Vu.wrapS=ie,Vu.wrapT=ie,Vu.generateMipmaps=!1,Vu.needsUpdate=!0),Vu));if(w){if(C.setValue(Ge,"toneMappingExposure",E.toneMappingExposure),v.needsLights&&(D=A,(L=N).ambientLightColor.needsUpdate=D,L.lightProbe.needsUpdate=D,L.sunLights.needsUpdate=D,L.sunLightShadows.needsUpdate=D,L.directionalLights.needsUpdate=D,L.directionalLightShadows.needsUpdate=D,L.pointLights.needsUpdate=D,L.pointLightShadows.needsUpdate=D,L.spotLights.needsUpdate=D,L.spotLightShadows.needsUpdate=D,L.rectAreaLights.needsUpdate=D,L.hemisphereLights.needsUpdate=D),s&&!0===i.fog&&Ee.refreshFogUniforms(N,s),Ee.refreshMaterialUniforms(N,i,W,H,S.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){const e=v.lightProbeGrid;N.probesSH.value=e.texture,N.probesMin.value.copy(e.boundingBox.min),N.probesMax.value.copy(e.boundingBox.max),N.probesResolution.value.copy(e.resolution)}Ol.upload(Ge,ot(v),N,me)}var L,D;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(Ol.upload(Ge,ot(v),N,me),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(Ge,"center",r.center);if(C.setValue(Ge,"modelViewMatrix",r.modelViewMatrix),C.setValue(Ge,"normalMatrix",r.normalMatrix),C.setValue(Ge,"modelMatrix",r.matrixWorld),void 0!==i.uniformsGroups){const e=i.uniformsGroups;for(let t=0,n=e.length;t{function n(){i.forEach(function(e){const t=pe.get(e).currentProgram;(void 0===t||t.isReady())&&i.delete(e)}),0!==i.size?setTimeout(n,10):t(e)}null!==ae.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let Ze=null;function Qe(){et.stop()}function Je(){et.start()}const et=new Ya;function tt(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLightProbeGrid)S.pushLightProbeGrid(e);else if(e.isLight)S.pushLight(e),e.castShadow&&S.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||e.intersectsFrustum(K)){i&&te.setFromMatrixPosition(e.matrixWorld).applyMatrix4(J);const r=Me.update(e),s=e.material;s.visible&&x.push(e,r,s,n,te.z,null,t)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||e.intersectsFrustum(K))){const r=Me.update(e),s=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),te.copy(e.boundingSphere.center)):(null===r.boundingSphere&&r.computeBoundingSphere(),te.copy(r.boundingSphere.center)),te.applyMatrix4(e.matrixWorld).applyMatrix4(J)),Array.isArray(s)){const i=r.groups;for(let a=0,o=i.length;a0&&rt(r,t,n),s.length>0&&rt(s,t,n),a.length>0&&rt(a,t,n),ue.buffers.depth.setTest(!0),ue.buffers.depth.setMask(!0),ue.buffers.color.setMask(!0),ue.setPolygonOffset(!1)}function it(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;if(void 0===S.state.transmissionRenderTarget[i.id]){const e=ae.has("EXT_color_buffer_half_float")||ae.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[i.id]=new Un(1,1,{generateMipmaps:!0,type:e?ve:he,minFilter:ce,samples:Math.max(4,oe.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Sn.workingColorSpace})}const r=S.state.transmissionRenderTarget[i.id],a=i.viewport||O;r.setSize(a.z*E.transmissionResolutionScale,a.w*E.transmissionResolutionScale);const o=E.getRenderTarget(),l=E.getActiveCubeFace(),u=E.getActiveMipmapLevel();E.setRenderTarget(r),E.getClearColor(z),V=E.getClearAlpha(),V<1&&E.setClearColor(16777215,.5),E.clear(),re&&Ue.render(n);const c=E.toneMapping;E.toneMapping=0;const h=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),S.setupLightsView(i),!0===Z&&Ce.setGlobalState(E.clippingPlanes,i),rt(e,n,i),me.updateMultisampleRenderTarget(r),me.updateRenderTargetMipmap(r),!1===ae.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r0,i.currentProgram=h,i.uniformsList=null,h}function ot(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=Ol.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function lt(e,t){const n=pe.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function ut(e){const t=pe.get(e);return t.__readFormat===e.format&&t.__readType===e.type||(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=oe.textureFormatReadable(e.format),t.__typeReadable=oe.textureTypeReadable(e.type)),t}et.setAnimationLoop(function(e){Ze&&Ze(e)}),"undefined"!=typeof self&&et.setContext(self),this.setAnimationLoop=function(e){Ze=e,je.setAnimationLoop(e),null===e?et.stop():et.start()},je.addEventListener("sessionstart",Qe),je.addEventListener("sessionend",Je),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void Yt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===A)return;null!==R&&R.renderStart(e,t);const n=!0===je.enabled&&!0===je.isPresenting,i=null!==w&&(null===I||n)&&w.begin(E,I);if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0!==je.enabled||!0!==je.isPresenting||null!==w&&!1!==w.isCompositing()||(!0===je.cameraAutoUpdate&&je.updateCamera(t),t=je.getCamera()),!0===e.isScene&&e.onBeforeRender(E,e,t,I),S=Re.get(e,M.length),S.init(t),S.state.textureUnits=me.getTextureUnits(),M.push(S),J.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),K.setFromProjectionMatrix(J,It,t.reversedDepth),Q=this.localClippingEnabled,Z=Ce.init(this.clippingPlanes,Q),x=Ae.get(e,T.length),x.init(),T.push(x),!0===je.enabled&&!0===je.isPresenting){const e=E.xr.getDepthSensingMesh();null!==e&&tt(e,t,-1/0,E.sortObjects)}tt(e,t,0,E.sortObjects),x.finish(),null!==R&&R.updateLights(S.state.lightsArray),!0===E.sortObjects&&x.sort(j,$),re=!1===je.enabled||!1===je.isPresenting||!1===je.hasDepthSensing(),re&&Ue.addToRenderList(x,e),this.info.render.frame++,!0===this.info.autoReset&&this.info.reset(),!0===Z&&Ce.beginShadows();const r=S.state.shadowsArray;De.render(r,e,t),!0===Z&&Ce.endShadows();if(!1===(i&&w.hasRenderPass())){const n=x.opaque,i=x.transmissive;if(S.setupLights(),t.isArrayCamera){const r=t.cameras;if(i.length>0)for(let t=0,s=r.length;t0&&it(n,i,e,t),re&&Ue.render(e),nt(x,e,t)}null!==I&&0===D&&(me.updateMultisampleRenderTarget(I),me.updateRenderTargetMipmap(I)),i&&w.end(E),!0===e.isScene&&e.onAfterRender(E,e,t),ze.resetDefaultState(),U=-1,F=null,M.pop(),M.length>0?(S=M[M.length-1],me.setTextureUnits(S.state.textureUnits),!0===Z&&Ce.setGlobalState(E.clippingPlanes,S.state.camera)):S=null,T.pop(),x=T.length>0?T[T.length-1]:null,null!==R&&R.renderEnd()},this.getActiveCubeFace=function(){return L},this.getActiveMipmapLevel=function(){return D},this.getRenderTarget=function(){return I},this.setRenderTargetTextures=function(e,t,n){const i=pe.get(e);i.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===i.__autoAllocateDepthBuffer&&(i.__useRenderToTexture=!1),pe.get(e.texture).__webglTexture=t,pe.get(e.depthTexture).__webglTexture=i.__autoAllocateDepthBuffer?void 0:n,i.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=pe.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t},this.setRenderTarget=function(e,t=0,n=0){I=e,L=t,D=n;let i=null,r=!1,s=!1;if(e){const a=pe.get(e);if(void 0!==a.__useDefaultFramebuffer)return ue.bindFramebuffer(Ge.FRAMEBUFFER,a.__webglFramebuffer),O.copy(e.viewport),B.copy(e.scissor),k=e.scissorTest,ue.viewport(O),ue.scissor(B),ue.setScissorTest(k),void(U=-1);if(void 0===a.__webglFramebuffer)me.setupRenderTarget(e);else if(a.__hasExternalTextures)me.rebindTextures(e,pe.get(e.texture).__webglTexture,pe.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&pe.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");me.setupDepthRenderbuffer(e)}}const o=e.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(s=!0);const l=pe.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],r=!0):i=e.samples>0&&!1===me.useMultisampledRTT(e)?pe.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,O.copy(e.viewport),B.copy(e.scissor),k=e.scissorTest}else O.copy(X).multiplyScalar(W).floor(),B.copy(q).multiplyScalar(W).floor(),k=Y;0!==n&&(i=C);if(ue.bindFramebuffer(Ge.FRAMEBUFFER,i)&&ue.drawBuffers(e,i),ue.viewport(O),ue.scissor(B),ue.setScissorTest(k),r){const i=pe.get(e.texture);Ge.framebufferTexture2D(Ge.FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,Ge.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(s){const i=t;for(let t=0;t1&&Ge.readBuffer(Ge.COLOR_ATTACHMENT0+o);const c=ut(a);if(!1===c.__formatReadable)return void Yt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!1===c.__typeReadable)return void Yt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&Ge.readPixels(t,n,i,r,ke.convert(l),ke.convert(u),s)}finally{const e=null!==I?pe.get(I).__webglFramebuffer:null;ue.bindFramebuffer(Ge.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=pe.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r){ue.bindFramebuffer(Ge.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;e.textures.length>1&&Ge.readBuffer(Ge.COLOR_ATTACHMENT0+o);const h=ut(a);if(!1===h.__formatReadable)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!1===h.__typeReadable)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const d=Ge.createBuffer();Ge.bindBuffer(Ge.PIXEL_PACK_BUFFER,d),Ge.bufferData(Ge.PIXEL_PACK_BUFFER,s.byteLength,Ge.STREAM_READ),Ge.readPixels(t,n,i,r,ke.convert(u),ke.convert(c),0),Ge.bindBuffer(Ge.PIXEL_PACK_BUFFER,null);const p=null!==I?pe.get(I).__webglFramebuffer:null;ue.bindFramebuffer(Ge.FRAMEBUFFER,p);const f=Ge.fenceSync(Ge.SYNC_GPU_COMMANDS_COMPLETE,0);return Ge.flush(),await function(e,t,n){return new Promise(function(i,r){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}},n)})}(Ge,f,4),Ge.bindBuffer(Ge.PIXEL_PACK_BUFFER,d),Ge.getBufferSubData(Ge.PIXEL_PACK_BUFFER,0,s),Ge.bindBuffer(Ge.PIXEL_PACK_BUFFER,null),Ge.deleteBuffer(d),Ge.deleteSync(f),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;me.setTexture2D(e,0),Ge.copyTexSubImage2D(Ge.TEXTURE_2D,n,0,0,a,o,r,s),ue.unbindTexture()},this.copyTextureToTexture=function(e,t,n=null,i=null,r=0,s=0){let a,o,l,u,c,h,d,p,f;const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==i?(d=i.x,p=i.y,f=i.z):(d=0,p=0,f=0);const g=ke.convert(t.format),_=ke.convert(t.type);let v;t.isData3DTexture?(me.setTexture3D(t,0),v=Ge.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(me.setTexture2DArray(t,0),v=Ge.TEXTURE_2D_ARRAY):(me.setTexture2D(t,0),v=Ge.TEXTURE_2D),ue.activeTexture(Ge.TEXTURE0),ue.pixelStorei(Ge.UNPACK_FLIP_Y_WEBGL,t.flipY),ue.pixelStorei(Ge.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),ue.pixelStorei(Ge.UNPACK_ALIGNMENT,t.unpackAlignment);const y=ue.getParameter(Ge.UNPACK_ROW_LENGTH),b=ue.getParameter(Ge.UNPACK_IMAGE_HEIGHT),x=ue.getParameter(Ge.UNPACK_SKIP_PIXELS),S=ue.getParameter(Ge.UNPACK_SKIP_ROWS),T=ue.getParameter(Ge.UNPACK_SKIP_IMAGES);ue.pixelStorei(Ge.UNPACK_ROW_LENGTH,m.width),ue.pixelStorei(Ge.UNPACK_IMAGE_HEIGHT,m.height),ue.pixelStorei(Ge.UNPACK_SKIP_PIXELS,u),ue.pixelStorei(Ge.UNPACK_SKIP_ROWS,c),ue.pixelStorei(Ge.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,w=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=pe.get(e),i=pe.get(t),m=pe.get(n.__renderTarget),g=pe.get(i.__renderTarget);ue.bindFramebuffer(Ge.READ_FRAMEBUFFER,m.__webglFramebuffer),ue.bindFramebuffer(Ge.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n!0,triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:()=>{},triggerUpdate:!1},onClick:{default:()=>{},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(t=>t.render(e.scene,e.camera));const t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;let n=null;if(e.hoverDuringDrag||!e.isPointerDragging){const t=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&t.sort((t,n)=>e.hoverOrderComparator(t.object,n.object));const i=t.find(t=>e.hoverFilter(t.object))||null;n=i?i.object:null,e.intersection=i||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&Ld(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){const{x:t,y:n}=e.pointerPos;return{x:t,y:n}},cameraPosition:function(e,t,n,i){const r=e.camera;if(t&&e.initialised){const l=t,u=n||{x:0,y:0,z:0};if(e.povPosTween?.end(),e.povTgtTween?.end(),i){const t=Object.assign({},r.position),n=o();e.tweenGroup.add(e.povPosTween=new zB(t).to(l,i).easing(IB.Quadratic.Out).onUpdate(s).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new zB(n).to(u,i/3).easing(IB.Quadratic.Out).onUpdate(a).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}else s(l),a(u);return this}return Object.assign({},r.position,{lookAt:o()});function s(e){const{x:t,y:n,z:i}=e;void 0!==t&&(r.position.x=t),void 0!==n&&(r.position.y=n),void 0!==i&&(r.position.z=i)}function a(t){const n=new Zz.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=n:r.lookAt(n)}function o(){return Object.assign(new Zz.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e,t=0,n=10,i,r){return this.fitToBbox(this.getBbox(i),t,n,r)},fitToBbox:function(e,t,n=0,i=10,r=!1){const s=e.camera;if(t){s.updateMatrixWorld();const a=new Zz.Vector3,o=new Zz.Vector3,l=new Zz.Vector3,u=new Zz.Vector3;s.getWorldPosition(u),s.getWorldDirection(l),a.crossVectors(l,s.up).normalize(),o.crossVectors(a,l).normalize();const c=(1-2*i/e.height)*s.fov/2*(Math.PI/180),h=Math.atan(Math.tan(c)*s.aspect),d=new Zz.Vector3((t.x[0]+t.x[1])/2,(t.y[0]+t.y[1])/2,(t.z[0]+t.z[1])/2),p=r?l.clone().multiplyScalar(u.distanceTo(d)).add(u):d,f=Math.max(0,...[new Zz.Vector3(t.x[0],t.y[0],t.z[0]),new Zz.Vector3(t.x[0],t.y[0],t.z[1]),new Zz.Vector3(t.x[0],t.y[1],t.z[0]),new Zz.Vector3(t.x[0],t.y[1],t.z[1]),new Zz.Vector3(t.x[1],t.y[0],t.z[0]),new Zz.Vector3(t.x[1],t.y[0],t.z[1]),new Zz.Vector3(t.x[1],t.y[1],t.z[0]),new Zz.Vector3(t.x[1],t.y[1],t.z[1])].map(e=>{const t=e.clone().sub(p);return Math.max(Math.abs(t.dot(o))/Math.tan(c),Math.abs(t.dot(a))/Math.tan(h))-t.dot(l)})),m=l.clone().negate(),g={x:p.x+m.x*f,y:p.y+m.y*f,z:p.z+m.z*f};this.cameraPosition(g,p,n)}return this},getBbox:function(e,t=()=>!0){const n=new Zz.Box3,i=e.objects.filter(t);return i.length?(i.forEach(e=>n.expandByObject(e)),Object.assign(...["x","y","z"].map(e=>({[e]:[n.min[e],n.max[e]]})))):null},getScreenCoords:function(e,t,n,i){const r=new Zz.Vector3(t,n,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,n,i=0){const r=new Zz.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new Zz.Raycaster;return s.setFromCamera(r,e.camera),Object.assign({},s.ray.at(i,new Zz.Vector3))},intersectingObjects:function(e,t,n){const i=new Zz.Vector2(t/e.width*2-1,-n/e.height*2+1),r=new Zz.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:e=>e.renderer,scene:e=>e.scene,camera:e=>e.camera,postProcessingComposer:e=>e.postProcessingComposer,controls:e=>e.controls,tbControls:e=>e.controls,_destructor:function(e){(e=>{for(;e.children.length;){const t=e.children[0];e.remove(t),Kz(t)}})(e.scene),e.controls?.dispose(),e.renderer?.dispose(),e.postProcessingComposer?.dispose()}},stateInit:()=>({scene:new Zz.Scene,camera:new Zz.PerspectiveCamera,timer:new Zz.Timer,tweenGroup:new FB,lastRaycasterCheck:0}),init(e,t,{controlType:n="trackball",useWebGPU:i=!1,rendererConfig:r={},extraRenderers:s=[],waitForLoadComplete:a=!0}={}){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[n]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new qz(t.container),t.pointerPos=new Zz.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(e=>t.container.addEventListener(e,n=>{if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("mouse"===n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some(e=>Math.abs(e)>1))&&(t.isPointerDragging=!0),t.enablePointerInteraction){const e=function(e){const t=e.getBoundingClientRect(),n=window.pageXOffset||document.documentElement.scrollLeft,i=window.pageYOffset||document.documentElement.scrollTop;return{top:t.top+i,left:t.left+n}}(t.container);t.pointerPos.x=n.pageX-e.left,t.pointerPos.y=n.pageY-e.top}},{passive:!0})),t.container.addEventListener("pointerup",e=>{t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(()=>{0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",e=>{t.onRightClick&&e.preventDefault()}),t.renderer=new(i?vF:Zz.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},r)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=s,t.extraRenderers.forEach(e=>{e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new YO(t.renderer),t.postProcessingComposer.addPass(new KO(t.scene,t.camera)),t.controls=new{trackball:kF,orbit:_O,fly:DO}[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",()=>{t.controlsEngaged=!0}),t.controls.addEventListener("change",()=>{t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",()=>{t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer,...t.extraRenderers].forEach(e=>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 Zz.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!a,window.scene=t.scene},update(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){const t=e.width,n=e.height;e.container.style.width=`${t}px`,e.container.style.height=`${n}px`,[e.renderer,e.postProcessingComposer,...e.extraRenderers].forEach(e=>e.setSize(t,n)),e.camera.aspect=t/n;const i=e.viewOffset.slice(0,2);i.some(e=>e)&&e.camera.setViewOffset(t,n,...i,t,n),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){const t=e.width,n=e.height,i=e.viewOffset.slice(0,2);i.some(e=>e)?e.camera.setViewOffset(t,n,...i,t,n):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new Zz.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){let t=_B(e.backgroundColor).alpha;void 0===t&&(t=1),e.renderer.setClearColor(new Zz.Color(DB(1,e.backgroundColor)),t)}function n(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new Zz.TextureLoader).load(e.backgroundImageUrl,t=>{t.colorSpace=Zz.SRGBColorSpace,e.skysphere.material=new Zz.MeshBasicMaterial({map:t,side:Zz.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&n()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&n())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(t=>e.scene.remove(t)),e.lights.forEach(t=>e.scene.add(t))),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(t=>e.scene.remove(t)),e.objects.forEach(t=>e.scene.add(t)))}});function Jz(e,t){const n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange(n,i){i[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n,...i){const r=n[e],s=r[t](...i);return s===r?this:s}}}}const eV=window.THREE?window.THREE:{AmbientLight:Pa,DirectionalLight:Na,REVISION:e},tV=Jz("forceGraph",Qp),nV=Object.assign(...["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(e=>({[e]:tV.linkProp(e)}))),iV=Object.assign(...["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(e=>({[e]:tV.linkMethod(e)}))),rV=Jz("renderObjs",Qz),sV=Object.assign(...["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(e=>({[e]:rV.linkProp(e)}))),aV=Object.assign(...["lights","cameraPosition","postProcessingComposer"].map(e=>({[e]:rV.linkMethod(e)})),{graph2ScreenCoords:rV.linkMethod("getScreenCoords"),screen2GraphCoords:rV.linkMethod("getSceneCoords")});var oV=Pd({props:{nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:(e,t)=>t.renderObjs.lineHoverPrecision(e),triggerUpdate:!1},enableNavigationControls:{default:!0,onChange(e,t){const n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:()=>{},triggerUpdate:!1},onNodeDragEnd:{default:()=>{},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1},showPointerCursor:{default:!0,triggerUpdate:!1},...nV,...sV},methods:{zoomToFit:function(e,t,n,...i){return e.renderObjs.fitToBbox(e.forceGraph.getGraphBbox(...i),t,n),this},pauseAnimation:function(e){return null!==e.animationFrameRequestId&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return null===e.animationFrameRequestId&&this._animationCycle(),this},_animationCycle(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:e=>e.renderObjs.scene(),camera:e=>e.renderObjs.camera(),renderer:e=>e.renderObjs.renderer(),controls:e=>e.renderObjs.controls(),_destructor:function(e){this.pauseAnimation(),this.graphData({nodes:[],links:[]}),e.forceGraph._destructor?.(),e.renderObjs._destructor()},...iV,...aV},stateInit:({controlType:e,rendererConfig:t,extraRenderers:n})=>{const i=new Qp;return{forceGraph:i,renderObjs:Qz({controlType:e,rendererConfig:t,extraRenderers:n}).objects([i]).lights([new eV.AmbientLight(13421772,Math.PI),new eV.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";const n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);const i=t.renderObjs.camera(),r=t.renderObjs.renderer(),s=t.renderObjs.controls();let a;s.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=i.position.z,t.container.appendChild(a=document.createElement("div")),a.className="graph-info-msg",a.textContent="",t.forceGraph.onLoading(()=>{a.textContent="Loading..."}).onFinishLoading(()=>{a.textContent=""}).onUpdate(()=>{t.graphData=t.forceGraph.graphData(),0===i.position.x&&0===i.position.y&&i.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(i.lookAt(t.forceGraph.position),t.lastSetCameraZ=i.position.z=170*Math.cbrt(t.graphData.nodes.length))}).onFinishUpdate(()=>{if(t._dragControls){const e=t.graphData.nodes.find(e=>e.__initialFixedPos&&!e.__disposeControlsAfterDrag);e?e.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&"d3"===t.forceEngine){const e=t._dragControls=new rc(t.graphData.nodes.map(e=>e.__threeObj).filter(e=>e),i,r.domElement);e.addEventListener("dragstart",function(e){const t=lV(e.object);if(!t)return;s.enabled=!1,e.object.__initialPos=e.object.position.clone(),e.object.__prevPos=e.object.position.clone();const n=t.__data;!n.__initialFixedPos&&(n.__initialFixedPos={fx:n.fx,fy:n.fy,fz:n.fz}),!n.__initialPos&&(n.__initialPos={x:n.x,y:n.y,z:n.z}),["x","y","z"].forEach(e=>n[`f${e}`]=n[e]),r.domElement.classList.add("grabbable")}),e.addEventListener("drag",function(e){const n=lV(e.object);if(!n)return;if(!e.object.hasOwnProperty("__graphObjType")){const t=e.object.__initialPos,i=e.object.__prevPos,r=e.object.position;n.position.add(r.clone().sub(i)),i.copy(r),r.copy(t)}const i=n.__data,r=n.position,s={x:r.x-i.x,y:r.y-i.y,z:r.z-i.z};["x","y","z"].forEach(e=>i[`f${e}`]=i[e]=r[e]),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),i.__dragged=!0,t.onNodeDrag(i,s)}),e.addEventListener("dragend",function(n){const i=lV(n.object);if(!i)return;delete n.object.__initialPos,delete n.object.__prevPos;const a=i.__data;a.__disposeControlsAfterDrag&&(e.dispose(),delete a.__disposeControlsAfterDrag);const o=a.__initialFixedPos,l=a.__initialPos,u={x:l.x-a.x,y:l.y-a.y,z:l.z-a.z};o&&(["x","y","z"].forEach(e=>{const t=`f${e}`;void 0===o[t]&&delete a[t]}),delete a.__initialFixedPos,delete a.__initialPos,a.__dragged&&(delete a.__dragged,t.onNodeDragEnd(a,u))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls&&(s.enabled=!0,s._status&&s._onPointerCancel?.(),s.domElement&&s.domElement.ownerDocument&&s.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}))),r.domElement.classList.remove("grabbable")})}}),eV.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator((e,t)=>{const n=lV(e);if(!n)return 1;const i=lV(t);if(!i)return-1;const r=e=>"node"===e.__graphObjType;return r(i)-r(n)}).tooltipContent(e=>{const n=lV(e);return n&&Ld(t[`${n.__graphObjType}Label`])(n.__data)||""}).hoverDuringDrag(!1).onHover(e=>{const n=lV(e);if(n!==t.hoverObj){const e=t.hoverObj?t.hoverObj.__graphObjType:null,i=t.hoverObj?t.hoverObj.__data:null,s=n?n.__graphObjType:null,a=n?n.__data:null;if(e&&e!==s){const n=t[`on${"node"===e?"Node":"Link"}Hover`];n&&n(null,i)}if(s){const n=t[`on${"node"===s?"Node":"Link"}Hover`];n&&n(a,e===s?i:null)}r.domElement.classList[(n&&t[`on${"node"===s?"Node":"Link"}Click`]||!n&&t.onBackgroundClick)&&Ld(t.showPointerCursor)(a)?"add":"remove"]("clickable"),t.hoverObj=n}}).clickAfterDrag(!1).onClick((e,n)=>{const i=lV(e);if(i){const e=t[`on${"node"===i.__graphObjType?"Node":"Link"}Click`];e&&e(i.__data,n)}else t.onBackgroundClick&&t.onBackgroundClick(n)}).onRightClick((e,n)=>{const i=lV(e);if(i){const e=t[`on${"node"===i.__graphObjType?"Node":"Link"}RightClick`];e&&e(i.__data,n)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(n)}),this._animationCycle()}});function lV(e){let t=e;for(;t&&!t.hasOwnProperty("__graphObjType");)t=t.parent;return t}return oV});