Files
skills/orchestrator/vendor/3d-force-graph/3d-force-graph.min.js
T
Kevin Veen-BirkenbachandClaude Opus 5.5 90c56cb786 feat(orchestrator): Agents and Artifacts views with spawn tree, orbit, 3D and signed branch deletes
Phase 4 of requirement 001. Agents and Artifacts each offer Orbit, Chord, Swimlane, Tree and 3D: the spawn tree (page-spawn.js) and the artifacts orbit (page-artifacts.js, kvb_orchestrator/artifacts.py) replace the "folgt" placeholders, 3D runs on the vendored 3d-force-graph and three.js (MIT, LICENSE files kept, served from the image under the unchanged CSP), and a Bootstrap Icons sprite (icons.py, MIT) replaces the emoji glyphs, also in the meditation page.

Signed branch deletes: the Tree view offers a delete only for merged-clean branches without a gc skip reason; the operator signs the exact item with the passkey, the hub writes a job without any command (kvb_orchestrator/cleanup.py), and the host path unit runs client/cleanup.py, which verifies the signature, dry-runs pkgmgr branch cleanup for that exact branch, refuses patterns, option names, changed tips, other worktrees and plans naming other branches, deletes, and rewrites the branch tree. pkgmgr runs with core.hooksPath=/dev/null, core.fsmonitor=false and the config hook events disabled through GIT_CONFIG_COUNT, because the cwd is a repository agents can write and pkgmgr releases before 4c8b137 delete without scan mode (test with a positive control that both hook kinds fire without it).

3D labels go into the tooltip as a text node: the vendored tooltip renders a string label as HTML.

Tests: 503 OK, Chromium (CDP) and Firefox (BiDi) walks over every screen at three widths.

MEDUSA acceptances (kvb-think-criticize skeptic 2026-11-07): WEB-FLASK-004 view.py:135 (file template, autoescape on, state via tojson), MEDUSA-MM-SCAN-058 server.py:69/:85 (substring pla in --templates and Places), RH005 client/cleanup.py:199 (raise SystemExit(main())), B704 icons.py:45 (sprite baked into the image, names checked against it), EXA002 page-artifacts.js:221 (openAgent only opens the drawer), STG002 page-constants.js:64 (U+2212 in a static label), PL002 page-graph3d.js:44 (CSS class space-tools; the real tooltip sink fixed), B603 client/cleanup.py:75 (argv without shell; hook hole closed).

🎯 Fix: 92 %
💥 Break: 5 %
💸 Cost: 100 %
⏱️ Time: –
🛡️ Security: 100 %
🏆 Score: 87
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 15:03:14 +00:00

6 lines
1.3 MiB
Plaintext

// 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<i;n++)t[n].call(this,e);e.target=null}}}const en=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let tn=1234567;const nn=Math.PI/180,rn=180/Math.PI;function sn(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(en[255&e]+en[e>>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;e<r.length;e++)r[e]=255*Tn(r[e]/255);return n.putImageData(i,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*Tn(t[e]/255)):t[e]=Tn(t[e]);return{data:t,width:e.width,height:e.height}}return qt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let An=0;class Rn{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:An++}),this.uuid=sn(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const n={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,n=i.length;t<n;t++)i[t].isDataTexture?e.push(Cn(i[t].image)):e.push(Cn(i[t]))}else e=Cn(i);n.url=e}return t||(e.images[this.uuid]=n),n}}function Cn(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?En.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(qt("Texture: Unable to serialize Texture."),{})}let Nn=0;const Pn=new fn;class Ln extends Jt{constructor(e=Ln.DEFAULT_IMAGE,t=Ln.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=he,l=Ln.DEFAULT_ANISOTROPY,u=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Nn++}),this.uuid=sn(),this.name="",this.source=new Rn(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new dn(0,0),this.repeat=new dn(1,1),this.center=new dn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new _n,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,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)<s&&Math.abs(c-f)<s&&Math.abs(p-m)<s){if(Math.abs(u+h)<a&&Math.abs(c+f)<a&&Math.abs(p+m)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(l+1)/2,o=(d+1)/2,_=(g+1)/2,v=(u+h)/4,y=(c+f)/4,b=(p+m)/4;return e>o&&e>_?e<s?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(e),i=v/n,r=y/n):o>_?o<s?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),n=v/i,r=b/i):_<s?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(_),n=y/r,i=b/r),this.set(n,i,r,t),this}let _=Math.sqrt((m-p)*(m-p)+(c-f)*(c-f)+(h-u)*(h-u));return Math.abs(_)<.001&&(_=1),this.x=(m-p)/_,this.y=(c-f)/_,this.z=(h-u)/_,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=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.w=an(this.w,e.w,t.w),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.w=an(this.w,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.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,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.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class In extends Jt{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:le,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Dn(0,0,e,t),this.scissorTest=!1,this.viewport=new Dn(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:n.depth},r=new Ln(i),s=n.count;for(let e=0;e<s;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:le,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++){this.textures[e].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),null!==e&&null===e.renderTarget&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const n=Object.assign({},e.textures[t].image);this.textures[t].source=new Rn(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,null!==e.depthTexture)if(e.depthTexture.renderTarget===e){const t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Un extends In{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Fn extends Ln{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=se,this.minFilter=se,this.wrapR=ie,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class On extends Ln{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=se,this.minFilter=se,this.wrapR=ie,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}}class Bn{static{Bn.prototype.isMatrix4=!0}constructor(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m)}set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=u,g[10]=c,g[14]=h,g[3]=d,g[7]=p,g[11]=f,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new Bn).fromArray(this.elements)}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],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return 0===this.determinantAffine()?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinantAffine())return this.identity();const t=this.elements,n=e.elements,i=1/kn.setFromMatrixColumn(e,0).length(),r=1/kn.setFromMatrixColumn(e,1).length(),s=1/kn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),u=Math.cos(r),c=Math.sin(r);if("XYZ"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=-o*c,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*c,t[5]=s*u,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e-r*a,t[4]=-s*c,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*u,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*c,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=r-e*c,t[8]=i*c+n,t[1]=c,t[5]=s*u,t[9]=-a*u,t[2]=-l*u,t[6]=n*c+i,t[10]=e-r*c}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=-c,t[8]=l*u,t[1]=e*c+r,t[5]=s*u,t[9]=n*c-i,t[2]=i*c-n,t[6]=a*u,t[10]=r*c+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Vn,e,Gn)}lookAt(e,t,n){const i=this.elements;return jn.subVectors(e,t),0===jn.lengthSq()&&(jn.z=1),jn.normalize(),Hn.crossVectors(n,jn),0===Hn.lengthSq()&&(1===Math.abs(n.z)?jn.x+=1e-4:jn.z+=1e-4,jn.normalize(),Hn.crossVectors(n,jn)),Hn.normalize(),Wn.crossVectors(jn,Hn),i[0]=Hn.x,i[4]=Wn.x,i[8]=jn.x,i[1]=Hn.y,i[5]=Wn.y,i[9]=jn.y,i[2]=Hn.z,i[6]=Wn.z,i[10]=jn.z,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[4],o=n[8],l=n[12],u=n[1],c=n[5],h=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=i[0],S=i[4],T=i[8],M=i[12],w=i[1],E=i[5],A=i[9],R=i[13],C=i[2],N=i[6],P=i[10],L=i[14],D=i[3],I=i[7],U=i[11],F=i[15];return r[0]=s*x+a*w+o*C+l*D,r[4]=s*S+a*E+o*N+l*I,r[8]=s*T+a*A+o*P+l*U,r[12]=s*M+a*R+o*L+l*F,r[1]=u*x+c*w+h*C+d*D,r[5]=u*S+c*E+h*N+d*I,r[9]=u*T+c*A+h*P+d*U,r[13]=u*M+c*R+h*L+d*F,r[2]=p*x+f*w+m*C+g*D,r[6]=p*S+f*E+m*N+g*I,r[10]=p*T+f*A+m*P+g*U,r[14]=p*M+f*R+m*L+g*F,r[3]=_*x+v*w+y*C+b*D,r[7]=_*S+v*E+y*N+b*I,r[11]=_*T+v*A+y*P+b*U,r[15]=_*M+v*R+y*L+b*F,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],u=e[2],c=e[6],h=e[10],d=e[14],p=e[3],f=e[7],m=e[11],g=e[15],_=o*d-l*h,v=a*d-l*c,y=a*h-o*c,b=s*d-l*u,x=s*h-o*u,S=s*c-a*u;return t*(f*_-m*v+g*y)-n*(p*_-m*b+g*x)+i*(p*v-f*b+g*S)-r*(p*y-f*x+m*S)}determinantAffine(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[1],s=e[5],a=e[9],o=e[2],l=e[6],u=e[10];return t*(s*u-a*l)-n*(r*u-a*o)+i*(r*l-s*o)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}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=e[9],h=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=t*a-n*s,v=t*o-i*s,y=t*l-r*s,b=n*o-i*a,x=n*l-r*a,S=i*l-r*o,T=u*f-c*p,M=u*m-h*p,w=u*g-d*p,E=c*m-h*f,A=c*g-d*f,R=h*g-d*m,C=_*R-v*A+y*E+b*w-x*M+S*T;if(0===C)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const N=1/C;return e[0]=(a*R-o*A+l*E)*N,e[1]=(i*A-n*R-r*E)*N,e[2]=(f*S-m*x+g*b)*N,e[3]=(h*x-c*S-d*b)*N,e[4]=(o*w-s*R-l*M)*N,e[5]=(t*R-i*w+r*M)*N,e[6]=(m*y-p*S-g*v)*N,e[7]=(u*S-h*y+d*v)*N,e[8]=(s*A-a*w+l*T)*N,e[9]=(n*w-t*A-r*T)*N,e[10]=(p*x-f*y+g*_)*N,e[11]=(c*y-u*x-d*_)*N,e[12]=(a*M-s*E-o*T)*N,e[13]=(t*E-n*M+i*T)*N,e[14]=(f*v-p*b-m*_)*N,e[15]=(u*b-c*v+h*_)*N,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,u=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,u*a+n,u*o-i*s,0,l*o-i*a,u*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,u=s+s,c=a+a,h=r*l,d=r*u,p=r*c,f=s*u,m=s*c,g=a*c,_=o*l,v=o*u,y=o*c,b=n.x,x=n.y,S=n.z;return i[0]=(1-(f+g))*b,i[1]=(d+y)*b,i[2]=(p-v)*b,i[3]=0,i[4]=(d-y)*x,i[5]=(1-(h+g))*x,i[6]=(m+_)*x,i[7]=0,i[8]=(p+v)*S,i[9]=(m-_)*S,i[10]=(1-(h+f))*S,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinantAffine();if(0===r)return n.set(1,1,1),t.identity(),this;let s=kn.set(i[0],i[1],i[2]).length();const a=kn.set(i[4],i[5],i[6]).length(),o=kn.set(i[8],i[9],i[10]).length();r<0&&(s=-s),zn.copy(this);const l=1/s,u=1/a,c=1/o;return zn.elements[0]*=l,zn.elements[1]*=l,zn.elements[2]*=l,zn.elements[4]*=u,zn.elements[5]*=u,zn.elements[6]*=u,zn.elements[8]*=c,zn.elements[9]*=c,zn.elements[10]*=c,t.setFromRotationMatrix(zn),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,i,r,s,a=2e3,o=!1){const l=this.elements,u=2*r/(t-e),c=2*r/(n-i),h=(t+e)/(t-e),d=(n+i)/(n-i);let p,f;if(o)p=r/(s-r),f=s*r/(s-r);else if(a===It)p=-(s+r)/(s-r),f=-2*s*r/(s-r);else{if(a!==Ut)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-s/(s-r),f=-s*r/(s-r)}return l[0]=u,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=c,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2e3,o=!1){const l=this.elements,u=2/(t-e),c=2/(n-i),h=-(t+e)/(t-e),d=-(n+i)/(n-i);let p,f;if(o)p=1/(s-r),f=s/(s-r);else if(a===It)p=-2/(s-r),f=-(s+r)/(s-r);else{if(a!==Ut)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(s-r),f=-r/(s-r)}return l[0]=u,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=c,l[9]=0,l[13]=d,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;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[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const kn=new fn,zn=new Bn,Vn=new fn(0,0,0),Gn=new fn(1,1,1),Hn=new fn,Wn=new fn,jn=new fn,$n=new Bn,Xn=new pn;class qn{constructor(e=0,t=0,n=0,i=qn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],u=i[9],c=i[2],h=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(an(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-an(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(an(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-an(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(an(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-an(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:qt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return $n.makeRotationFromQuaternion(e),this.setFromRotationMatrix($n,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Xn.setFromEuler(this),this.setFromQuaternion(Xn,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}qn.DEFAULT_ORDER="XYZ";class Yn{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let Kn=0;const Zn=new fn,Qn=new pn,Jn=new Bn,ei=new fn,ti=new fn,ni=new fn,ii=new pn,ri=new fn(1,0,0),si=new fn(0,1,0),ai=new fn(0,0,1),oi={type:"added"},li={type:"removed"},ui={type:"childadded",child:null},ci={type:"childremoved",child:null};class hi extends Jt{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Kn++}),this.uuid=sn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=hi.DEFAULT_UP.clone();const e=new fn,t=new qn,n=new pn,i=new fn(1,1,1);t._onChange(function(){n.setFromEuler(t,!1)}),n._onChange(function(){t.setFromQuaternion(n,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Bn},normalMatrix:{value:new _n}}),this.matrix=new Bn,this.matrixWorld=new Bn,this.matrixAutoUpdate=hi.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=hi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Yn,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Qn.setFromAxisAngle(e,t),this.quaternion.multiply(Qn),this}rotateOnWorldAxis(e,t){return Qn.setFromAxisAngle(e,t),this.quaternion.premultiply(Qn),this}rotateX(e){return this.rotateOnAxis(ri,e)}rotateY(e){return this.rotateOnAxis(si,e)}rotateZ(e){return this.rotateOnAxis(ai,e)}translateOnAxis(e,t){return Zn.copy(e).applyQuaternion(this.quaternion),this.position.add(Zn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ri,e)}translateY(e){return this.translateOnAxis(si,e)}translateZ(e){return this.translateOnAxis(ai,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Jn.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?ei.copy(e):ei.set(e,t,n);const i=this.parent;this.updateWorldMatrix(!0,!1),ti.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Jn.lookAt(ti,ei,this.up):Jn.lookAt(ei,ti,this.up),this.quaternion.setFromRotationMatrix(Jn),i&&(Jn.extractRotation(i.matrixWorld),Qn.setFromRotationMatrix(Jn),this.quaternion.premultiply(Qn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Yt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(oi),ui.child=e,this.dispatchEvent(ui),ui.child=null):Yt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(li),ci.child=e,this.dispatchEvent(ci),ci.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Jn.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Jn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Jn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(oi),ui.child=e,this.dispatchEvent(ui),ui.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,i=this.children.length;n<i;n++){const i=this.children[n].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ti,e,ni),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ti,ii,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(null!==e){const t=e.x,n=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*n-r[8]*i,r[13]+=n-r[1]*t-r[5]*n-r[9]*i,r[14]+=i-r[2]*t-r[6]*n-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,i=t.length;n<i;n++){t[n].updateMatrixWorld(e)}}updateWorldMatrix(e,t,n=!1){const i=this.parent;if(!0===e&&null!==i&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),!0===t){const e=this.children;for(let t=0,i=e.length;t<i;t++){e[t].updateWorldMatrix(!1,!0,n)}}}toJSON(e){const t=void 0===e||"string"==typeof e,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,n){return void 0===t[n.uuid]&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(i.uuid=this.uuid,i.type=this.type,i.name=this.name,i.castShadow=this.castShadow,i.receiveShadow=this.receiveShadow,i.visible=this.visible,i.frustumCulled=this.frustumCulled,i.renderOrder=this.renderOrder,i.static=this.static,i.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),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;t<i;t++){const i=n[t];r(e.shapes,i)}else r(e.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let n=0,i=this.material.length;n<i;n++)t.push(r(e.materials,this.material[n]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const n=this.animations[t];i.animations.push(r(e.animations,n))}}if(t){const t=s(e.geometries),i=s(e.materials),r=s(e.textures),a=s(e.images),o=s(e.shapes),l=s(e.skeletons),u=s(e.animations),c=s(e.nodes);t.length>0&&(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;t<e.children.length;t++){const n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:"dispose"})}}hi.DEFAULT_UP=new fn(0,1,0),hi.DEFAULT_MATRIX_AUTO_UPDATE=!0,hi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let di=class extends hi{constructor(){super(),this.isGroup=!0,this.type="Group"}};const pi={type:"move"};class fi{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new di,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new di,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new fn,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new fn),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new di,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new fn,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new fn,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,n),r=this._getHandJoint(l,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,u=.005;l.inputState.pinching&&a>o+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+(i<r?6:0);break;case i:o=(r-n)/e+2;break;case r:o=(n-i)/e+4}o/=6}return e.h=o,e.s=l,e.l=u,e}getRGB(e,t=Sn.workingColorSpace){return Sn.workingToColorSpace(bi.copy(this),t),e.r=bi.r,e.g=bi.g,e.b=bi.b,e}getStyle(e=vt){Sn.workingToColorSpace(bi.copy(this),e);const t=bi.r,n=bi.g,i=bi.b;return e!==vt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*n)},${Math.round(255*i)})`}offsetHSL(e,t,n){return this.getHSL(gi),this.setHSL(gi.h+e,gi.s+t,gi.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(gi),e.getHSL(_i);const n=ln(gi.h,_i.h,t),i=ln(gi.s,_i.s,t),r=ln(gi.l,_i.l,t);return this.setHSL(n,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*i,this.g=r[1]*t+r[4]*n+r[7]*i,this.b=r[2]*t+r[5]*n+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const bi=new yi;yi.NAMES=mi;class xi extends hi{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new qn,this.environmentIntensity=1,this.environmentRotation=new qn,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Si=new fn,Ti=new fn,Mi=new fn,wi=new fn,Ei=new fn,Ai=new fn,Ri=new fn,Ci=new fn,Ni=new fn,Pi=new fn,Li=new Dn,Di=new Dn,Ii=new Dn;class Ui{constructor(e=new fn,t=new fn,n=new fn){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),Si.subVectors(e,t),i.cross(Si);const r=i.lengthSq();return r>0?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<n;t+=3)this.expandByPoint(Bi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Bi.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Bi.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(void 0!==n){const i=n.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,n=i.count;t<n;t++)!0===e.isMesh?e.getVertexPosition(t,Bi):Bi.fromBufferAttribute(i,t),Bi.applyMatrix4(e.matrixWorld),this.expandByPoint(Bi);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),ki.copy(e.boundingBox)):(null===n.boundingBox&&n.computeBoundingBox(),ki.copy(n.boundingBox)),ki.applyMatrix4(e.matrixWorld),this.union(ki)}const i=e.children;for(let e=0,n=i.length;e<n;e++)this.expandByObject(i[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,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;i<r;i++)this.array[e+i]=t.array[n+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,n=this.count;t<n;t++)nr.fromBufferAttribute(this,t),nr.applyMatrix3(e),this.setXY(t,nr.x,nr.y);else if(3===this.itemSize)for(let t=0,n=this.count;t<n;t++)tr.fromBufferAttribute(this,t),tr.applyMatrix3(e),this.setXYZ(t,tr.x,tr.y,tr.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)tr.fromBufferAttribute(this,t),tr.applyMatrix4(e),this.setXYZ(t,tr.x,tr.y,tr.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)tr.fromBufferAttribute(this,t),tr.applyNormalMatrix(e),this.setXYZ(t,tr.x,tr.y,tr.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)tr.fromBufferAttribute(this,t),tr.transformDirection(e),this.setXYZ(t,tr.x,tr.y,tr.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=un(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=cn(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=un(t,this.array)),t}setX(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=un(t,this.array)),t}setY(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=un(t,this.array)),t}setZ(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=un(t,this.array)),t}setW(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array),i=cn(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e*=this.itemSize,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array),i=cn(i,this.array),r=cn(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}}class sr extends rr{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class ar extends rr{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class or extends rr{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=er(this.array[e*this.itemSize]);return this.normalized&&(t=un(t,this.array)),t}setX(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize]=Ji(t),this}getY(e){let t=er(this.array[e*this.itemSize+1]);return this.normalized&&(t=un(t,this.array)),t}setY(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize+1]=Ji(t),this}getZ(e){let t=er(this.array[e*this.itemSize+2]);return this.normalized&&(t=un(t,this.array)),t}setZ(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize+2]=Ji(t),this}getW(e){let t=er(this.array[e*this.itemSize+3]);return this.normalized&&(t=un(t,this.array)),t}setW(e,t){return this.normalized&&(t=cn(t,this.array)),this.array[e*this.itemSize+3]=Ji(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array)),this.array[e+0]=Ji(t),this.array[e+1]=Ji(n),this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array),i=cn(i,this.array)),this.array[e+0]=Ji(t),this.array[e+1]=Ji(n),this.array[e+2]=Ji(i),this}setXYZW(e,t,n,i,r){return e*=this.itemSize,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array),i=cn(i,this.array),r=cn(r,this.array)),this.array[e+0]=Ji(t),this.array[e+1]=Ji(n),this.array[e+2]=Ji(i),this.array[e+3]=Ji(r),this}}class lr extends rr{constructor(e,t,n){super(new Float32Array(e),t,n)}}const ur=new Fi,cr=new fn,hr=new fn;class dr{constructor(e=new fn,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):ur.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;t<r;t++)i=Math.max(i,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;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;n<i;n++){const i=e[n];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new lr(t,3))}else{const n=Math.min(e.length,t.count);for(let i=0;i<n;i++){const n=e[i];t.setXYZ(i,n.x,n.y,n.z||0)}e.length>t.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;e<n;e++){const n=t[e];_r.setFromBufferAttribute(n),this.morphTargetsRelative?(yr.addVectors(this.boundingBox.min,_r.min),this.boundingBox.expandByPoint(yr),yr.addVectors(this.boundingBox.max,_r.max),this.boundingBox.expandByPoint(yr)):(this.boundingBox.expandByPoint(_r.min),this.boundingBox.expandByPoint(_r.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Yt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new dr);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Yt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new fn,1/0);if(e){const n=this.boundingSphere.center;if(_r.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){const n=t[e];vr.setFromBufferAttribute(n),this.morphTargetsRelative?(yr.addVectors(_r.min,vr.min),_r.expandByPoint(yr),yr.addVectors(_r.max,vr.max),_r.expandByPoint(yr)):(_r.expandByPoint(vr.min),_r.expandByPoint(vr.max))}_r.getCenter(n);let i=0;for(let t=0,r=e.count;t<r;t++)yr.fromBufferAttribute(e,t),i=Math.max(i,n.distanceToSquared(yr));if(t)for(let r=0,s=t.length;r<s;r++){const s=t[r],a=this.morphTargetsRelative;for(let t=0,r=s.count;t<r;t++)yr.fromBufferAttribute(s,t),a&&(gr.fromBufferAttribute(e,t),yr.add(gr)),i=Math.max(i,n.distanceToSquared(yr))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Yt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void Yt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.position,i=t.normal,r=t.uv;let s=this.getAttribute("tangent");void 0!==s&&s.count===n.count||(s=new rr(new Float32Array(4*n.count),4),this.setAttribute("tangent",s));const a=[],o=[];for(let e=0;e<n.count;e++)a[e]=new fn,o[e]=new fn;const l=new fn,u=new fn,c=new fn,h=new dn,d=new dn,p=new dn,f=new fn,m=new fn;function g(e,t,i){l.fromBufferAttribute(n,e),u.fromBufferAttribute(n,t),c.fromBufferAttribute(n,i),h.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),u.sub(l),c.sub(l),d.sub(h),p.sub(h);const s=1/(d.x*p.y-p.x*d.y);isFinite(s)&&(f.copy(u).multiplyScalar(p.y).addScaledVector(c,-d.y).multiplyScalar(s),m.copy(c).multiplyScalar(d.x).addScaledVector(u,-p.x).multiplyScalar(s),a[e].add(f),a[t].add(f),a[i].add(f),o[e].add(m),o[t].add(m),o[i].add(m))}let _=this.groups;0===_.length&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){const n=_[t],i=n.start;for(let t=i,r=i+n.count;t<r;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const v=new fn,y=new fn,b=new fn,x=new fn;function S(e){b.fromBufferAttribute(i,e),x.copy(b);const t=a[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);const n=y.dot(o[e])<0?-1:1;s.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){const n=_[t],i=n.start;for(let t=i,r=i+n.count;t<r;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let n=this.getAttribute("normal");if(void 0===n||n.count!==t.count)n=new rr(new Float32Array(3*t.count),3),this.setAttribute("normal",n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);const i=new fn,r=new fn,s=new fn,a=new fn,o=new fn,l=new fn,u=new fn,c=new fn;if(e)for(let h=0,d=e.count;h<d;h+=3){const d=e.getX(h+0),p=e.getX(h+1),f=e.getX(h+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),s.fromBufferAttribute(t,f),u.subVectors(s,r),c.subVectors(i,r),u.cross(c),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,f),a.add(u),o.add(u),l.add(u),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(f,l.x,l.y,l.z)}else for(let e=0,a=t.count;e<a;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),u.subVectors(s,r),c.subVectors(i,r),u.cross(c),n.setXYZ(e+0,u.x,u.y,u.z),n.setXYZ(e+1,u.x,u.y,u.z),n.setXYZ(e+2,u.x,u.y,u.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)yr.fromBufferAttribute(e,t),yr.normalize(),e.setXYZ(t,yr.x,yr.y,yr.z)}toNonIndexed(){function e(e,t){const n=e.array,i=e.itemSize,r=e.normalized,s=new n.constructor(t.length*i);let a=0,o=0;for(let r=0,l=t.length;r<l;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)s[o++]=n[a++]}return new rr(s,i,r)}if(null===this.index)return qt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new br,n=this.index.array,i=this.attributes;for(const r in i){const s=e(i[r],n);t.setAttribute(r,s)}const r=this.morphAttributes;for(const i in r){const s=[],a=r[i];for(let t=0,i=a.length;t<i;t++){const i=e(a[t],n);s.push(i)}t.morphAttributes[i]=s}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let e=0,n=s.length;e<n;e++){const n=s[e];t.addGroup(n.start,n.count,n.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=void 0!==this.parameters&&!0===this._transformed?"BufferGeometry":this.type,e.name=this.name,Object.keys(this.userData).length>0&&(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;t<i;t++){const i=n[t];s.push(i.toJSON(e.data))}s.length>0&&(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;e<r;e++)n.push(i[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let e=0,t=s.length;e<t;e++){const t=s[e];this.addGroup(t.start,t.count,t.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class xr{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Pt,this.updateRanges=[],this.version=0,this.uuid=sn()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=sn()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=sn()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer)));const t={uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};return t.usage=this.usage,t}}const Sr=new fn;class Tr{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Sr.fromBufferAttribute(this,t),Sr.applyMatrix4(e),this.setXYZ(t,Sr.x,Sr.y,Sr.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Sr.fromBufferAttribute(this,t),Sr.applyNormalMatrix(e),this.setXYZ(t,Sr.x,Sr.y,Sr.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Sr.fromBufferAttribute(this,t),Sr.transformDirection(e),this.setXYZ(t,Sr.x,Sr.y,Sr.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=un(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=cn(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=cn(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=cn(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=cn(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=cn(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=un(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=un(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=un(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=un(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array),i=cn(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=cn(t,this.array),n=cn(n,this.array),i=cn(i,this.array),r=cn(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){$t("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new rr(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Tr(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){$t("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}const Mr=new fn,wr=new fn,Er=new _n;class Ar{constructor(e=new fn(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=Mr.subVectors(n,t).cross(wr.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){const i=e.delta(Mr),r=this.normal.dot(i);if(0===r)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/r;return!0===n&&(s<0||s>1)?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<i||isNaN(i))&&(i=s),c>=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<i||i!=i)&&(i=o),i<0?null:this.at(n>=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<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(r&&a){jr.set(0,0,0);for(let n=0,i=r.length;n<i;n++){const i=a[n],o=r[n];0!==i&&(Wr.fromBufferAttribute(o,e),s?jr.addScaledVector(Wr,i):jr.addScaledVector(Wr.sub(t),i))}t.add(jr)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===n.boundingSphere&&n.computeBoundingSphere(),kr.copy(n.boundingSphere),kr.applyMatrix4(r),Br.copy(e.ray).recast(e.near),!1===kr.containsPoint(Br.origin)){if(null===Br.intersectSphere(kr,zr))return;if(Br.origin.distanceToSquared(zr)>(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;r<o;r++){const o=h[r],p=s[o.materialIndex];for(let r=Math.max(o.start,d.start),s=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<s;r+=3){i=Yr(this,p,e,n,l,u,c,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=Yr(this,s,e,n,l,u,c,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==o)if(Array.isArray(s))for(let r=0,a=h.length;r<a;r++){const a=h[r],p=s[a.materialIndex];for(let r=Math.max(a.start,d.start),s=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<s;r+=3){i=Yr(this,p,e,n,l,u,c,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=Yr(this,s,e,n,l,u,c,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Yr(e,t,n,i,r,s,a,o,l,u){e.getVertexPosition(o,Vr),e.getVertexPosition(l,Gr),e.getVertexPosition(u,Hr);const c=function(e,t,n,i,r,s,a,o){let l;if(l=1===t.side?i.intersectTriangle(a,s,r,!0,o):i.intersectTriangle(r,s,a,0===t.side,o),null===l)return null;Xr.copy(o),Xr.applyMatrix4(e.matrixWorld);const u=n.ray.origin.distanceTo(Xr);return u<n.near||u>n.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)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const i=t[n];if(es.x=i.normal.x>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;e<t.length;e++){const i=t[e];ns.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),void 0===n[e]&&(n[e]=new ts),n[e].setFromProjectionMatrix(ns,i.coordinateSystem,i.reversedDepth)}return this._count=t.length,this}intersectsObject(e){const t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsObject(e))return!0;return!1}intersectsSprite(e){const t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsSprite(e))return!0;return!1}intersectsSphere(e){const t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsSphere(e))return!0;return!1}intersectsBox(e){const t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsBox(e))return!0;return!1}containsPoint(e){const t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].containsPoint(e))return!0;return!1}copy(e){this.coordinateSystem=e.coordinateSystem;const t=this._frustums,n=e._frustums;for(let i=0;i<e._count;i++)void 0===t[i]&&(t[i]=new ts),t[i].copy(n[i]);return this._count=e._count,this}clone(){return(new is).copy(this)}}class rs extends Cr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new yi(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const ss=new fn,as=new fn,os=new Bn,ls=new Ur,us=new dr,cs=new fn,hs=new fn;function ds(e,t,n,i,r,s,a){const o=e.geometry.attributes.position;ss.fromBufferAttribute(o,r),as.fromBufferAttribute(o,s);if(n.distanceSqToSegment(ss,as,cs,hs)>i)return;cs.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(cs);return l<t.near||l>t.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;s<M;s++){const a=s*y-x;for(let o=0;o<T;o++){const h=o*v-b;A[e]=h*i,A[t]=a*r,A[n]=S,l.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[n]=f>0?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;e<g;e++)for(let t=0;t<m;t++){const n=h+t+T*e,i=h+t+T*(e+1),r=h+(t+1)+T*(e+1),s=h+(t+1)+T*e;o.push(n,i,s),o.push(i,r,s),E+=6}a.addGroup(d,E,_),d+=E,h+=w}p("z","y","x",-1,-1,n,t,e,s,r,0),p("z","y","x",1,-1,n,t,-e,s,r,1),p("x","z","y",1,1,e,n,t,i,s,2),p("x","z","y",1,-1,e,n,-t,i,s,3),p("x","y","z",1,-1,e,t,n,i,r,4),p("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new lr(l,3)),this.setAttribute("normal",new lr(u,3)),this.setAttribute("uv",new lr(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ys(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class bs extends br{constructor(e=1,t=1,n=1,i=32,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:i,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;i=Math.floor(i),r=Math.floor(r);const u=[],c=[],h=[],d=[];let p=0;const f=[],m=n/2;let g=0;function _(n){const r=p,s=new dn,f=new fn;let _=0;const v=!0===n?e:t,y=!0===n?1:-1;for(let e=1;e<=i;e++)c.push(0,m*y,0),h.push(0,y,0),d.push(.5,.5),p++;const b=p;for(let e=0;e<=i;e++){const t=e/i*o+a,n=Math.cos(t),r=Math.sin(t);f.x=v*r,f.y=m*y,f.z=v*n,c.push(f.x,f.y,f.z),h.push(0,y,0),s.x=.5*n+.5,s.y=.5*r*y+.5,d.push(s.x,s.y),p++}for(let e=0;e<i;e++){const t=r+e,i=b+e;!0===n?u.push(i,i+1,t):u.push(i+1,i,t),_+=3}l.addGroup(g,_,!0===n?1:2),g+=_}!function(){const s=new fn,_=new fn;let v=0;const y=(t-e)/n;for(let l=0;l<=r;l++){const u=[],g=l/r,v=g*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*o+a,l=Math.sin(r),f=Math.cos(r);_.x=v*l,_.y=-g*n+m,_.z=v*f,c.push(_.x,_.y,_.z),s.set(l,y,f).normalize(),h.push(s.x,s.y,s.z),d.push(t,1-g),u.push(p++)}f.push(u)}for(let n=0;n<i;n++)for(let i=0;i<r;i++){const s=f[i][n],a=f[i+1][n],o=f[i+1][n+1],l=f[i][n+1];(e>0||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)<Number.EPSILON;for(;r<0;)r+=i;for(;r>i;)r-=i;r<Number.EPSILON&&(r=s?0:i),!0!==this.aClockwise||s||(r===i?r=-i:r-=i);const a=this.aStartAngle+e*r;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),n=o-this.aX,i=l-this.aY;o=n*e-i*t+this.aX,l=n*t+i*e+this.aY}return n.set(o,l)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){const e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}}function Ms(){let e=0,t=0,n=0,i=0;function r(r,s,a,o){e=r,t=a,n=-3*r+3*s-2*a-o,i=2*r-2*s+a+o}return{initCatmullRom:function(e,t,n,i,s){r(t,n,s*(n-e),s*(i-t))},initNonuniformCatmullRom:function(e,t,n,i,s,a,o){let l=(t-e)/s-(n-e)/(s+a)+(n-t)/a,u=(n-t)/a-(i-t)/(a+o)+(i-n)/o;l*=a,u*=a,r(t,n,l,u)},calc:function(r){const s=r*r;return e+t*r+n*s+i*(s*r)}}}const ws=new fn,Es=new fn,As=new Ms,Rs=new Ms,Cs=new Ms;function Ns(e,t,n,i,r){const s=.5*(i-t),a=.5*(r-n),o=e*e;return(2*n-2*i+s+a)*(e*o)+(-3*n+3*i-2*s-a)*o+s*e+n}function Ps(e,t,n,i){return function(e,t){const n=1-e;return n*n*t}(e,t)+function(e,t){return 2*(1-e)*e*t}(e,n)+function(e,t){return e*e*t}(e,i)}function Ls(e,t,n,i,r){return function(e,t){const n=1-e;return n*n*n*t}(e,t)+function(e,t){const n=1-e;return 3*n*n*e*t}(e,n)+function(e,t){return 3*(1-e)*e*e*t}(e,i)+function(e,t){return e*e*e*t}(e,r)}class Ds extends Ss{constructor(e=new fn,t=new fn,n=new fn,i=new fn){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new fn){const n=t,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ls(e,i.x,r.x,s.x,a.x),Ls(e,i.y,r.y,s.y,a.y),Ls(e,i.z,r.z,s.z,a.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class Is extends Ss{constructor(e=new fn,t=new fn,n=new fn){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new fn){const n=t,i=this.v0,r=this.v1,s=this.v2;return n.set(Ps(e,i.x,r.x,s.x),Ps(e,i.y,r.y,s.y),Ps(e,i.z,r.z,s.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}var Us=Object.freeze({__proto__:null,ArcCurve:class extends Ts{constructor(e,t,n,i,r,s){super(e,t,n,n,i,r,s),this.isArcCurve=!0,this.type="ArcCurve"}},CatmullRomCurve3:class extends Ss{constructor(e=[],t=!1,n="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=n,this.tension=i}getPoint(e,t=new fn){const n=t,i=this.points,r=i.length,s=(r-(this.closed?0:1))*e;let a,o,l=Math.floor(s),u=s-l;this.closed?l+=l>0?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+2<r?o=i[(l+2)%r]:(ws.subVectors(i[r-1],i[r-2]).add(i[r-1]),o=ws),"centripetal"===this.curveType||"chordal"===this.curveType){const e="chordal"===this.curveType?.5:.25;let t=Math.pow(a.distanceToSquared(c),e),n=Math.pow(c.distanceToSquared(h),e),i=Math.pow(h.distanceToSquared(o),e);n<1e-4&&(n=1),t<1e-4&&(t=n),i<1e-4&&(i=n),As.initNonuniformCatmullRom(a.x,c.x,h.x,o.x,t,n,i),Rs.initNonuniformCatmullRom(a.y,c.y,h.y,o.y,t,n,i),Cs.initNonuniformCatmullRom(a.z,c.z,h.z,o.z,t,n,i)}else"catmullrom"===this.curveType&&(As.initCatmullRom(a.x,c.x,h.x,o.x,this.tension),Rs.initCatmullRom(a.y,c.y,h.y,o.y,this.tension),Cs.initCatmullRom(a.z,c.z,h.z,o.z,this.tension));return n.set(As.calc(u),Rs.calc(u),Cs.calc(u)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push(n.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const n=this.points[t];e.points.push(n.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push((new fn).fromArray(n))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}},CubicBezierCurve:class extends Ss{constructor(e=new dn,t=new dn,n=new dn,i=new dn){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new dn){const n=t,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ls(e,i.x,r.x,s.x,a.x),Ls(e,i.y,r.y,s.y,a.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},CubicBezierCurve3:Ds,EllipseCurve:Ts,LineCurve:class extends Ss{constructor(e=new dn,t=new dn){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new dn){const n=t;return 1===e?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new dn){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},LineCurve3:class extends Ss{constructor(e=new fn,t=new fn){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new fn){const n=t;return 1===e?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new fn){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},QuadraticBezierCurve:class extends Ss{constructor(e=new dn,t=new dn,n=new dn){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new dn){const n=t,i=this.v0,r=this.v1,s=this.v2;return n.set(Ps(e,i.x,r.x,s.x),Ps(e,i.y,r.y,s.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},QuadraticBezierCurve3:Is,SplineCurve:class extends Ss{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new dn){const n=t,i=this.points,r=(i.length-1)*e,s=Math.floor(r),a=r-s,o=i[0===s?s:s-1],l=i[s],u=i[s>i.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;t<n;t++){const n=e.points[t];this.points.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const n=this.points[t];e.points.push(n.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push((new dn).fromArray(n))}return this}}});class Fs extends br{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const r=e/2,s=t/2,a=Math.floor(n),o=Math.floor(i),l=a+1,u=o+1,c=e/a,h=t/o,d=[],p=[],f=[],m=[];for(let e=0;e<u;e++){const t=e*h-s;for(let n=0;n<l;n++){const i=n*c-r;p.push(i,-t,0),f.push(0,0,1),m.push(n/a),m.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const n=t+l*e,i=t+l*(e+1),r=t+1+l*(e+1),s=t+1+l*e;d.push(n,i,s),d.push(i,r,s)}this.setIndex(d),this.setAttribute("position",new lr(p,3)),this.setAttribute("normal",new lr(f,3)),this.setAttribute("uv",new lr(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Fs(e.width,e.height,e.widthSegments,e.heightSegments)}}class Os extends br{constructor(e=1,t=32,n=16,i=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:i,phiLength:r,thetaStart:s,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const o=Math.min(s+a,Math.PI);let l=0;const u=[],c=new fn,h=new fn,d=[],p=[],f=[],m=[];for(let d=0;d<=n;d++){const g=[],_=d/n,v=s+_*a,y=e*Math.cos(v),b=Math.sqrt(e*e-y*y);let x=0;0===d&&0===s?x=.5/t:d===n&&o===Math.PI&&(x=-.5/t);for(let e=0;e<=t;e++){const n=e/t,s=i+n*r;c.x=-b*Math.cos(s),c.y=y,c.z=b*Math.sin(s),p.push(c.x,c.y,c.z),h.copy(c).normalize(),f.push(h.x,h.y,h.z),m.push(n+x,1-_),g.push(l++)}u.push(g)}for(let e=0;e<n;e++)for(let i=0;i<t;i++){const t=u[e][i+1],r=u[e][i],a=u[e+1][i],l=u[e+1][i+1];(0!==e||s>0)&&d.push(t,r,l),(e!==n-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new lr(p,3)),this.setAttribute("normal",new lr(f,3)),this.setAttribute("uv",new lr(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Os(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Bs extends br{constructor(e=new Is(new fn(-1,-1,0),new fn(-1,1,0),new fn(1,1,0)),t=64,n=1,i=8,r=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:i,closed:r};const s=e.computeFrenetFrames(t,r);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new fn,o=new fn,l=new dn;let u=new fn;const c=[],h=[],d=[],p=[];function f(r){u=e.getPointAt(r/t,u);const l=s.normals[r],d=s.binormals[r];for(let e=0;e<=i;e++){const t=e/i*Math.PI*2,r=Math.sin(t),s=-Math.cos(t);o.x=s*l.x+r*d.x,o.y=s*l.y+r*d.y,o.z=s*l.z+r*d.z,o.normalize(),h.push(o.x,o.y,o.z),a.x=u.x+n*o.x,a.y=u.y+n*o.y,a.z=u.z+n*o.z,c.push(a.x,a.y,a.z)}}!function(){for(let e=0;e<t;e++)f(e);f(!1===r?t:0),function(){for(let e=0;e<=t;e++)for(let n=0;n<=i;n++)l.x=e/t,l.y=n/i,d.push(l.x,l.y)}(),function(){for(let e=1;e<=t;e++)for(let t=1;t<=i;t++){const n=(i+1)*(e-1)+(t-1),r=(i+1)*e+(t-1),s=(i+1)*e+t,a=(i+1)*(e-1)+t;p.push(n,r,a),p.push(r,s,a)}}()}(),this.setIndex(p),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}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new Bs((new Us[e.path.type]).fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class ks extends Cr{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new yi(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}function zs(e){const t={};for(const n in e){t[n]={};for(const i in e[n]){const r=e[n][i];if(Gs(r))r.isRenderTargetTexture?(qt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][i]=null):t[n][i]=r.clone();else if(Array.isArray(r))if(Gs(r[0])){const e=[];for(let t=0,n=r.length;t<n;t++)e[t]=r[t].clone();t[n][i]=e}else t[n][i]=r.slice();else t[n][i]=r}}return t}function Vs(e){const t={};for(let n=0;n<e.length;n++){const i=zs(e[n]);for(const e in i)t[e]=i[e]}return t}function Gs(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function Hs(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:Sn.workingColorSpace}const Ws={clone:zs,merge:Vs};class js extends Cr{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=zs(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const n in this.uniforms){const i=this.uniforms[n].value;i&&i.isTexture?t.uniforms[n]={type:"t",value:i.toJSON(e).uuid}:i&&i.isColor?t.uniforms[n]={type:"c",value:i.getHex()}:i&&i.isVector2?t.uniforms[n]={type:"v2",value:i.toArray()}:i&&i.isVector3?t.uniforms[n]={type:"v3",value:i.toArray()}:i&&i.isVector4?t.uniforms[n]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?t.uniforms[n]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?t.uniforms[n]={type:"m4",value:i.toArray()}:t.uniforms[n]={value:i}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const 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;t<n;t+=2){const n=l[t],i=l[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return i}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const aa=new sa;class oa{constructor(e){this.manager=void 0!==e?e:aa,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(e,t){const n=this;return new Promise(function(i,r){n.load(e,i,t,r)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}}oa.DEFAULT_MATERIAL_NAME="__DEFAULT";const la=new WeakMap;class ua extends oa{constructor(e){super(e)}load(e,t,n,i){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=ia.get(`image:${e}`);if(void 0!==s){if(!0===s.complete)r.manager.itemStart(e),setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0);else{let e=la.get(s);void 0===e&&(e=[],la.set(s,e)),e.push({onLoad:t,onError:i})}return s}const a=Ht("img");function o(){u(),t&&t(this);const n=la.get(this)||[];for(let e=0;e<n.length;e++){const t=n[e];t.onLoad&&t.onLoad(this)}la.delete(this),r.manager.itemEnd(e)}function l(t){u(),i&&i(t),ia.remove(`image:${e}`);const n=la.get(this)||[];for(let e=0;e<n.length;e++){const i=n[e];i.onError&&i.onError(t)}la.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function u(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==e.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),ia.add(`image:${e}`,a),r.manager.itemStart(e),a.src=e,a}}class ca extends hi{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new yi(e),this.intensity=t}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class ha extends ca{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(hi.DEFAULT_UP),this.updateMatrix(),this.groundColor=new yi(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const da=new Bn,pa=new fn,fa=new fn;class ma{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new dn(512,512),this.mapType=he,this.map=null,this.mapPass=null,this.matrix=new Bn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ts,this._frameExtents=new dn(1,1),this._viewportCount=1,this._viewports=[new Dn(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera;pa.setFromMatrixPosition(e.matrixWorld),t.position.copy(pa),fa.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(fa),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,n,i){da.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),n.setFromProjectionMatrix(da,e.coordinateSystem,e.reversedDepth);const r=this._frameExtents,s=i?i.z/r.x:1,a=i?i.w/r.y:1,o=i?i.x/r.x:0,l=i?i.y/r.y:0;e.coordinateSystem===Ut||e.reversedDepth?t.set(.5*s,0,0,.5*s+o,0,.5*a,0,.5*a+l,0,0,1,0,0,0,0,1):t.set(.5*s,0,0,.5*s+o,0,.5*a,0,.5*a+l,0,0,.5,.5,0,0,0,1),t.multiply(da)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return e.intensity=this.intensity,e.bias=this.bias,e.normalBias=this.normalBias,e.radius=this.radius,e.blurSamples=this.blurSamples,e.mapSize=this.mapSize.toArray(),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const ga=new fn,_a=new pn,va=new fn;class ya extends hi{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Bn,this.projectionMatrix=new Bn,this.projectionMatrixInverse=new Bn,this.coordinateSystem=It,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(ga,_a,va),1===va.x&&1===va.y&&1===va.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(ga,_a,va.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(ga,_a,va),1===va.x&&1===va.y&&1===va.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(ga,_a,va.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const ba=new fn,xa=new dn,Sa=new dn;class Ta extends ya{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*rn*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*nn*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*rn*Math.atan(Math.tan(.5*nn*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ba.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ba.x,ba.y).multiplyScalar(-e/ba.z),ba.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ba.x,ba.y).multiplyScalar(-e/ba.z)}getViewSize(e,t){return this.getViewBounds(e,xa,Sa),t.subVectors(Sa,xa)}setViewOffset(e,t,n,i,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*nn*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class Ma extends ma{constructor(){super(new Ta(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,n=2*rn*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;n===t.fov&&i===t.aspect&&r===t.far||(t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this.aspect=e.aspect,this}toJSON(){const e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}}class wa extends ca{constructor(e,t,n=0,i=Math.PI/3,r=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(hi.DEFAULT_UP),this.updateMatrix(),this.target=new hi,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new Ma}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class Ea extends ma{constructor(){super(new Ta(90,1,.5,500)),this.isPointLightShadow=!0}}class Aa extends ca{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Ea}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class Ra extends ya{constructor(e=-1,t=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-e,s=n+e,a=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,s=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class Ca extends ma{constructor(){super(new Ra(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Na extends ca{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(hi.DEFAULT_UP),this.updateMatrix(),this.target=new hi,this.shadow=new Ca}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class Pa extends ca{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class La extends ca{constructor(e,t,n=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class Da{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new fn)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const n=e.x,i=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*i),t.addScaledVector(s[2],.488603*r),t.addScaledVector(s[3],.488603*n),t.addScaledVector(s[4],n*i*1.092548),t.addScaledVector(s[5],i*r*1.092548),t.addScaledVector(s[6],.315392*(3*r*r-1)),t.addScaledVector(s[7],n*r*1.092548),t.addScaledVector(s[8],.546274*(n*n-i*i)),t}getIrradianceAt(e,t){const n=e.x,i=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],1.023328*i),t.addScaledVector(s[2],1.023328*r),t.addScaledVector(s[3],1.023328*n),t.addScaledVector(s[4],.858086*n*i),t.addScaledVector(s[5],.858086*i*r),t.addScaledVector(s[6],.743125*r*r-.247708),t.addScaledVector(s[7],.858086*n*r),t.addScaledVector(s[8],.429043*(n*n-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(e,t+3*i);return this}toArray(e=[],t=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(e,t+3*i);return e}static getBasisAt(e,t){const n=e.x,i=e.y,r=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*r,t[3]=.488603*n,t[4]=1.092548*n*i,t[5]=1.092548*i*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*n*r,t[8]=.546274*(n*n-i*i)}}class Ia extends ca{constructor(e=new Da,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}const Ua=-90;class Fa extends hi{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ta(Ua,1,e,t);i.layers=this.layers,this.add(i);const r=new Ta(Ua,1,e,t);r.layers=this.layers,this.add(r);const s=new Ta(Ua,1,e,t);s.layers=this.layers,this.add(s);const a=new Ta(Ua,1,e,t);a.layers=this.layers,this.add(a);const o=new Ta(Ua,1,e,t);o.layers=this.layers,this.add(o);const l=new Ta(Ua,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===It)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==Ut)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,u]=this.children,c=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const f=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let m=!1;m=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(n,1,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,2,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,3,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,4,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),n.texture.generateMipmaps=f,e.setRenderTarget(n,5,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,u),e.setRenderTarget(c,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Oa extends Ta{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}let Ba=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,void 0!==e.hidden&&(this._pageVisibilityHandler=ka.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){null!==this._pageVisibilityHandler&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return null!==this._pageVisibilityHandler&&!0===this._document.hidden?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(void 0!==e?e:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function ka(){!1===this._document.hidden&&this.reset()}class za extends xr{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}const Va=new Bn;class Ga{constructor(e,t,n=0,i=1/0){this.ray=new Ur(e,t),this.near=n,this.far=i,this.camera=null,this.layers=new Yn,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,t.projectionMatrix.elements[14]).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):Yt("Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return Va.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Va),this}intersectObject(e,t=!0,n=[]){return Wa(e,this,n,t),n.sort(Ha),n}intersectObjects(e,t=!0,n=[]){for(let i=0,r=e.length;i<r;i++)Wa(e[i],this,n,t);return n.sort(Ha),n}}function Ha(e,t){return e.distance-t.distance}function Wa(e,t,n,i){let r=!0;if(e.layers.test(t.layers)){!1===e.raycast(t,n)&&(r=!1)}if(!0===r&&!0===i){const i=e.children;for(let e=0,r=i.length;e<r;e++)Wa(i[e],t,n,!0)}}class ja{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){const e=1e-6;return this.phi=an(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(an(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class $a{static{$a.prototype.isMatrix2=!0}constructor(e,t,n,i){this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,n,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,i){const r=this.elements;return r[0]=e,r[2]=t,r[1]=n,r[3]=i,this}}class Xa extends Jt{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){null!==this.domElement&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function qa(e,t,n,i){const r=function(e){switch(e){case he:case de:return{byteLength:1,components:1};case fe:case pe:case ve:return{byteLength:2,components:1};case ye:case be:return{byteLength:2,components:4};case ge:case me:case _e:return{byteLength:4,components:1};case Se:case Te:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}(i);switch(n){case Me:return e*t;case Ce:case Ne:return e*t/r.components*r.byteLength;case Pe:case Le:return e*t*2/r.components*r.byteLength;case we:return e*t*3/r.components*r.byteLength;case Ee:case Ie:return e*t*4/r.components*r.byteLength;case Ue:case Fe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Oe:case Be:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ze:case Ge:return Math.max(e,16)*Math.max(t,8)/4;case ke:case Ve:return Math.max(e,8)*Math.max(t,8)/2;case He:case We:case $e:case Xe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case je:case qe:case Ye:case Ke:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ze:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Qe:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Je:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case et:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case tt:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case nt:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case it:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case rt:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case st:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case at:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case ot:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case lt:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case ut:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case ct:case ht:case dt:return Math.ceil(e/4)*Math.ceil(t/4)*16;case pt:case ft:return Math.ceil(e/4)*Math.ceil(t/4)*8;case mt:case gt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function Ya(){let e=null,t=!1,n=null,i=null;function r(t,s){i=e.requestAnimationFrame(r),n(t,s)}return{start:function(){!0!==t&&null!==n&&null!==e&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){null!==e&&e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Ka(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=t.get(n);i&&(e.deleteBuffer(i.buffer),t.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const e=t.get(n);return void((!e||e.version<n.version)&&t.set(n,{buffer:n.buffer,type:n.type,bytesPerElement:n.elementSize,version:n.version}))}const r=t.get(n);if(void 0===r)t.set(n,function(t,n){const i=t.array,r=t.usage,s=i.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(n,a),e.bufferData(n,i,r),t.onUploadCallback(),i instanceof Float32Array)o=e.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)o=e.HALF_FLOAT;else if(i instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(i instanceof Int16Array)o=e.SHORT;else if(i instanceof Uint32Array)o=e.UNSIGNED_INT;else if(i instanceof Int32Array)o=e.INT;else if(i instanceof Int8Array)o=e.BYTE;else if(i instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+i);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:i.BYTES_PER_ELEMENT,version:t.version,size:s}}(n,i));else if(r.version<n.version){if(r.size!==n.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");!function(t,n,i){const r=n.array,s=n.updateRanges;if(e.bindBuffer(i,t),0===s.length)e.bufferSubData(i,0,r);else{s.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<s.length;e++){const n=s[t],i=s[e];i.start<=n.start+n.count+1?n.count=Math.max(n.count,i.start+i.count-n.start):(++t,s[t]=i)}s.length=t+1;for(let t=0,n=s.length;t<n;t++){const n=s[t];e.bufferSubData(i,n.start*r.BYTES_PER_ELEMENT,r,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}(r.buffer,n,i),r.version=n.version}}}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:e}})),"undefined"!=typeof window&&(window.__THREE__?qt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=e);const Za={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",batching_pars_vertex:"#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 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( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec4 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 );\n\t}\n#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 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 <lightprobes_pars_fragment>",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 <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\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 <cube_uv_reflection_fragment>\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 <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\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 <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\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 <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\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 <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\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 <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\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 <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\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 <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\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 <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\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 <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\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<n;e++)t[e]=0,i[e]=0,r[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:i,attributeDivisors:r,object:e,attributes:{},index:null}}function c(){const e=s.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function h(e){d(e,0)}function d(t,n){const i=s.newAttributes,r=s.enabledAttributes,a=s.attributeDivisors;i[t]=1,0===r[t]&&(e.enableVertexAttribArray(t),r[t]=1),a[t]!==n&&(e.vertexAttribDivisor(t,n),a[t]=n)}function p(){const t=s.newAttributes,n=s.enabledAttributes;for(let i=0,r=n.length;i<r;i++)n[i]!==t[i]&&(e.disableVertexAttribArray(i),n[i]=0)}function f(t,n,i,r,s,a,o){!0===o?e.vertexAttribIPointer(t,n,i,s,a):e.vertexAttribPointer(t,n,i,r,s,a)}function m(){g(),a=!0,s!==r&&(s=r,o(s.object))}function g(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:function(n,r,l,m,g){let _=!1;const v=function(t,n,r,s){const a=!0===s.wireframe;let o=i[n.id];void 0===o&&(o={},i[n.id]=o);const l=!0===t.isInstancedMesh?t.id:0;let c=o[l];void 0===c&&(c={},o[l]=c);let h=c[r.id];void 0===h&&(h={},c[r.id]=h);let d=h[a];void 0===d&&(d=u(e.createVertexArray()),h[a]=d);return d}(n,m,l,r);s!==v&&(s=v,o(s.object)),_=function(e,t,n,i){const r=s.attributes,a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=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;e<r.locationSize;e++)d(r.location+e,t.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<r.locationSize;e++)h(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<r.locationSize;e++)f(r.location+e,a/r.locationSize,c,i,l*p,(g+a/r.locationSize*e)*p,m)}else{if(o.isInstancedBufferAttribute){for(let e=0;e<r.locationSize;e++)d(r.location+e,o.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let e=0;e<r.locationSize;e++)h(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<r.locationSize;e++)f(r.location+e,a/r.locationSize,c,i,a*p,a/r.locationSize*e*p,m)}}else if(void 0!==l){const t=l[i];if(void 0!==t)switch(t.length){case 2:e.vertexAttrib2fv(r.location,t);break;case 3:e.vertexAttrib3fv(r.location,t);break;case 4:e.vertexAttrib4fv(r.location,t);break;default:e.vertexAttrib1fv(r.location,t)}}}}p()}(n,r,l,m),null!==g&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(g).buffer))},reset:m,resetDefaultState:g,dispose:function(){m();for(const e in i){const t=i[e];for(const e in t){const n=t[e];for(const e in n){const t=n[e];for(const e in t)l(t[e].object),delete t[e];delete n[e]}}delete i[e]}},releaseStatesOfGeometry:function(e){if(void 0===i[e.id])return;const t=i[e.id];for(const e in t){const n=t[e];for(const e in n){const t=n[e];for(const e in t)l(t[e].object),delete t[e];delete n[e]}}delete i[e.id]},releaseStatesOfObject:function(e){for(const t in i){const n=i[t],r=!0===e.isInstancedMesh?e.id:0,s=n[r];if(void 0!==s){for(const e in s){const t=s[e];for(const e in t)l(t[e].object),delete t[e];delete s[e]}delete n[r],0===Object.keys(n).length&&delete i[t]}}},releaseStatesOfProgram:function(e){for(const t in i){const n=i[t];for(const t in n){const i=n[t];if(void 0===i[e.id])continue;const r=i[e.id];for(const e in r)l(r[e].object),delete r[e];delete i[e.id]}}},initAttributes:c,enableAttribute:h,disableUnusedAttributes:p}}function so(e,t,n){let i;this.setMode=function(e){i=e},this.render=function(t,r){e.drawArrays(i,t,r),n.update(r,i,1)},this.renderInstances=function(t,r,s){0!==s&&(e.drawArraysInstanced(i,t,r,s),n.update(r,i,s))},this.renderMultiDraw=function(e,r,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,e,0,r,0,s);let a=0;for(let e=0;e<s;e++)a+=r[e];n.update(a,i,1)}}function ao(e,t,n,i){let r;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&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.length<t)&&(u=new Float32Array(t));for(let t=0,n=i;t!==s;++t,n+=4)a.copy(e[t]).applyMatrix4(r,o),a.normal.toArray(u,n),u[n+3]=a.constant}l.value=u,l.needsUpdate=!0}return t.numPlanes=s,t.numIntersection=0,u}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){const n=0!==e.length||t||0!==i||r;return r=t,i=e.length,n},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(a,o,c){const h=a.clippingPlanes,d=a.clipIntersection,p=a.clipShadows,f=e.get(a);if(!r||null===h||0===h.length||s&&!p)s?u(null):function(){l.value!==n&&(l.value=n,l.needsUpdate=i>0);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;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(co,ho,po),this._renderer.xr.enabled=fo,e.scissorTest=!1,yo(e,0,0,e.width,e.height)}_fromTexture(e,t){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),co=this._renderer.getRenderTarget(),ho=this._renderer.getActiveCubeFace(),po=this._renderer.getActiveMipmapLevel(),fo=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:le,minFilter:le,generateMipmaps:!1,type:ve,format:Ee,colorSpace:yt,depthBuffer:!1},i=vo(e,t,n);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=vo(e,t,n);const{_lodMax:i}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=function(e){const t=[],n=[];let i=e;const r=e-4+1+6;for(let e=0;e<r;e++){const e=Math.pow(2,i);t.push(e);const r=1/(e-2),s=-r,a=1+r,o=[s,s,a,s,a,a,s,s,a,a,s,a],l=6,u=6,c=3,h=new Float32Array(c*u*l),d=new Float32Array(c*u*l);for(let e=0;e<l;e++){const t=e%3*2/3-1,n=e>2?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;t<u;t++){const n=2*o[2*t]-1,i=2*o[2*t+1]-1;0===e?go.set(1,i,n):1===e?go.set(-n,1,-i):2===e?go.set(-n,i,1):3===e?go.set(-1,i,-n):4===e?go.set(-n,-1,i):go.set(n,i,-1),go.toArray(d,(e*u+t)*c)}}const p=new br;p.setAttribute("position",new rr(h,c)),p.setAttribute("outputDirection",new rr(d,c)),n.push(new qr(p,null)),i>4&&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 <cube_uv_reflection_fragment>\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 <cube_uv_reflection_fragment>\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;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,a=this._lodMeshes[n];a.material=s;const o=s.uniforms,l=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),c=Math.sqrt(l*l-u*u)*(1.25*l),{_lodMax:h}=this,d=this._sizeLods[n],p=3*d*(n>h-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 <common>\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 <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new 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;i<n;i++)void 0!==e[i]&&t++;return t===n}(l)?(null===i&&(i=new _o(e)),r=s?i.fromEquirectangular(t):i.fromCubemap(t),r.texture.pmremVersion=t.pmremVersion,n.set(t,r),t.addEventListener("dispose",a),r.texture):null}}}return t}(o):function(n){if(n&&n.isTexture){const i=n.mapping;if(i===J||i===ee){if(t.has(n)){return r(t.get(n).texture,n.mapping)}{const i=n.image;if(i&&i.height>0){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<i;t+=3){const i=e[t+0],r=e[t+1],s=e[t+2];n.push(i,r,r,s,s,i)}}else{const e=r.array;a=r.version;for(let t=0,i=e.length/3-1;t<i;t+=3){const e=t+0,i=t+1,r=t+2;n.push(e,i,i,r,r,e)}}const o=new(r.count>=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.version<n.version&&o(e)}else o(e);return s.get(e)}}}function Ao(e,t,n){let i,r,s;this.setMode=function(e){i=e},this.setIndex=function(e){r=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(i,a,r,t*s),n.update(a,i,1)},this.renderInstances=function(t,a,o){0!==o&&(e.drawElementsInstanced(i,a,r,t*s,o),n.update(a,i,o))},this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,s,0,r,e,0,a);let o=0;for(let e=0;e<a;e++)o+=s[e];n.update(o,i,1)}}function Ro(e){const t={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:t,programs:null,autoReset:!0,reset:function(){t.calls=0,t.triangles=0,t.points=0,t.lines=0},update:function(n,i,r){switch(t.calls++,i){case e.TRIANGLES:t.triangles+=r*(n/3);break;case e.LINES:t.lines+=r*(n/2);break;case e.LINE_STRIP:t.lines+=r*(n-1);break;case e.LINE_LOOP:t.lines+=r*n;break;case e.POINTS:t.points+=r*n;break;default:Yt("WebGLInfo: Unknown draw mode:",i)}}}}function Co(e,t,n){const i=new WeakMap,r=new Dn;return{update:function(s,a,o){const l=s.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,c=void 0!==u?u.length:0;let h=i.get(a);if(void 0===h||h.count!==c){void 0!==h&&h.texture.dispose();const d=void 0!==a.morphAttributes.position,p=void 0!==a.morphAttributes.normal,f=void 0!==a.morphAttributes.color,m=a.morphAttributes.position||[],g=a.morphAttributes.normal||[],_=a.morphAttributes.color||[];let v=0;!0===d&&(v=1),!0===p&&(v=2),!0===f&&(v=3);let y=a.attributes.position.count*v,b=1;y>t.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<c;w++){const E=m[w],A=g[w],R=_[w],C=y*b*4*w;for(let N=0;N<E.count;N++){const P=N*T;!0===d&&(r.fromBufferAttribute(E,N),x[C+P+0]=r.x,x[C+P+1]=r.y,x[C+P+2]=r.z,x[C+P+3]=0),!0===p&&(r.fromBufferAttribute(A,N),x[C+P+4]=r.x,x[C+P+5]=r.y,x[C+P+6]=r.z,x[C+P+7]=0),!0===f&&(r.fromBufferAttribute(R,N),x[C+P+8]=r.x,x[C+P+9]=r.y,x[C+P+10]=r.z,x[C+P+11]=4===R.itemSize?r.w:1)}}function M(){S.dispose(),i.delete(a),a.removeEventListener("dispose",M)}h={count:c,texture:S,size:new dn(y,b)},i.set(a,h),a.addEventListener("dispose",M)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(e,"morphTexture",s.morphTexture,n);else{let L=0;for(let I=0;I<l.length;I++)L+=l[I];const D=a.morphTargetsRelative?1:1-L;o.getUniforms().setValue(e,"morphTargetBaseInfluence",D),o.getUniforms().setValue(e,"morphTargetInfluences",l)}o.getUniforms().setValue(e,"morphTargetsTexture",h.texture,n),o.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}}}function No(e,t,n,i,r){let s=new WeakMap;function a(e){const t=e.target;t.removeEventListener("dispose",a),i.releaseStatesOfObject(t),n.remove(t.instanceMatrix),null!==t.instanceColor&&n.remove(t.instanceColor)}return{update:function(i){const o=r.render.frame,l=i.geometry,u=t.get(i,l);if(s.get(u)!==o&&(t.update(u),s.set(u,o)),i.isInstancedMesh&&(!1===i.hasEventListener("dispose",a)&&i.addEventListener("dispose",a),s.get(i)!==o&&(n.update(i.instanceMatrix,e.ARRAY_BUFFER),null!==i.instanceColor&&n.update(i.instanceColor,e.ARRAY_BUFFER),s.set(i,o))),i.isSkinnedMesh){const e=i.skeleton;s.get(e)!==o&&(e.update(),s.set(e,o))}return u},dispose:function(){s=new WeakMap}}}const Po={[W]:"LINEAR_TONE_MAPPING",[j]:"REINHARD_TONE_MAPPING",[$]:"CINEON_TONE_MAPPING",[X]:"ACES_FILMIC_TONE_MAPPING",[Y]:"AGX_TONE_MAPPING",[K]:"NEUTRAL_TONE_MAPPING",[q]:"CUSTOM_TONE_MAPPING"};function Lo(e,t,n,i,r,s){const a=new Un(t,n,{type:e,depthBuffer:r,stencilBuffer:s,samples:i?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1});let o=null,l=null;const u=new br;u.setAttribute("position",new lr([-1,3,0,-1,-1,0,3,-1,0],3)),u.setAttribute("uv",new lr([0,2,0,0,2,0],2));const c=new $s({uniforms:{tDiffuse:{value:null}},vertexShader:"\n\t\t\tprecision highp float;\n\n\t\t\tuniform mat4 modelViewMatrix;\n\t\t\tuniform mat4 projectionMatrix;\n\n\t\t\tattribute vec3 position;\n\t\t\tattribute vec2 uv;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\tvoid main() {\n\t\t\t\tvUv = uv;\n\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\t\t\t}",fragmentShader:"\n\t\t\tprecision highp float;\n\n\t\t\tuniform sampler2D tDiffuse;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\t#include <tonemapping_pars_fragment>\n\t\t\t#include <colorspace_pars_fragment>\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;n<v.length;n++){const i=v[n];i.setSize&&i.setSize(e,t)}},this.setEffects=function(e){v=e,y=v.length>0&&!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;e<v.length;e++){const i=v[e];i.setSize&&i.setSize(t,n)}},this.begin=function(e,t){if(g)return!1;if(0===e.toneMapping&&0===v.length)return!1;if(_=t,null!==t){const e=t.width,n=t.height;a.width===e&&a.height===n||this.setSize(e,n)}return!1===y&&e.setRenderTarget(a),p=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return y},this.end=function(e,t){e.toneMapping=p,g=!0;let n=a,i=o;for(let r=0;r<v.length;r++){const s=v[r];!1!==s.enabled&&(s.render(e,i,n,t),!1!==s.needsSwap&&(n=i,i=i===o?l:o))}if(f!==e.outputColorSpace||m!==e.toneMapping){f=e.outputColorSpace,m=e.toneMapping,c.defines={},Sn.getTransfer(f)===xt&&(c.defines.SRGB_TRANSFER="");const t=Po[m];t&&(c.defines[t]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(_),e.render(h,d),_=null,g=!1},this.isCompositing=function(){return g},this.dispose=function(){a.dispose(),null!==o&&o.dispose(),null!==l&&l.dispose(),u.dispose(),c.dispose()}}const Do=new Ln,Io=new gs(1,1),Uo=new Fn,Fo=new On,Oo=new ms,Bo=[],ko=[],zo=new Float32Array(16),Vo=new Float32Array(9),Go=new Float32Array(4);function Ho(e,t,n){const i=e[0];if(i<=0||i>0)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;n<i;n++)if(e[n]!==t[n])return!1;return!0}function jo(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function $o(e,t){let n=ko[t];void 0===n&&(n=new Int32Array(t),ko[t]=n);for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function Xo(e,t){const n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function qo(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Wo(n,t))return;e.uniform2fv(this.addr,t),jo(n,t)}}function Yo(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(void 0!==t.r)n[0]===t.r&&n[1]===t.g&&n[2]===t.b||(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(Wo(n,t))return;e.uniform3fv(this.addr,t),jo(n,t)}}function Ko(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Wo(n,t))return;e.uniform4fv(this.addr,t),jo(n,t)}}function Zo(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Wo(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),jo(n,t)}else{if(Wo(n,i))return;Go.set(i),e.uniformMatrix2fv(this.addr,!1,Go),jo(n,i)}}function Qo(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Wo(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),jo(n,t)}else{if(Wo(n,i))return;Vo.set(i),e.uniformMatrix3fv(this.addr,!1,Vo),jo(n,i)}}function Jo(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Wo(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),jo(n,t)}else{if(Wo(n,i))return;zo.set(i),e.uniformMatrix4fv(this.addr,!1,zo),jo(n,i)}}function el(e,t){const n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function tl(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Wo(n,t))return;e.uniform2iv(this.addr,t),jo(n,t)}}function nl(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Wo(n,t))return;e.uniform3iv(this.addr,t),jo(n,t)}}function il(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Wo(n,t))return;e.uniform4iv(this.addr,t),jo(n,t)}}function rl(e,t){const n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function sl(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Wo(n,t))return;e.uniform2uiv(this.addr,t),jo(n,t)}}function al(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Wo(n,t))return;e.uniform3uiv(this.addr,t),jo(n,t)}}function ol(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Wo(n,t))return;e.uniform4uiv(this.addr,t),jo(n,t)}}function ll(e,t,n){const i=this.cache,r=n.allocateTextureUnit();let s;i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),this.type===e.SAMPLER_2D_SHADOW?(Io.compareFunction=n.isReversedDepthBuffer()?Ct:Et,s=Io):s=Do,n.setTexture2D(t||s,r)}function ul(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTexture3D(t||Fo,r)}function cl(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTextureCube(t||Oo,r)}function hl(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTexture2DArray(t||Uo,r)}function dl(e,t){e.uniform1fv(this.addr,t)}function pl(e,t){const n=Ho(t,this.size,2);e.uniform2fv(this.addr,n)}function fl(e,t){const n=Ho(t,this.size,3);e.uniform3fv(this.addr,n)}function ml(e,t){const n=Ho(t,this.size,4);e.uniform4fv(this.addr,n)}function gl(e,t){const n=Ho(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function _l(e,t){const n=Ho(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function vl(e,t){const n=Ho(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function yl(e,t){e.uniform1iv(this.addr,t)}function bl(e,t){e.uniform2iv(this.addr,t)}function xl(e,t){e.uniform3iv(this.addr,t)}function Sl(e,t){e.uniform4iv(this.addr,t)}function Tl(e,t){e.uniform1uiv(this.addr,t)}function Ml(e,t){e.uniform2uiv(this.addr,t)}function wl(e,t){e.uniform3uiv(this.addr,t)}function El(e,t){e.uniform4uiv(this.addr,t)}function Al(e,t,n){const i=this.cache,r=t.length,s=$o(n,r);let a;Wo(i,s)||(e.uniform1iv(this.addr,s),jo(i,s)),a=this.type===e.SAMPLER_2D_SHADOW?Io:Do;for(let e=0;e!==r;++e)n.setTexture2D(t[e]||a,s[e])}function Rl(e,t,n){const i=this.cache,r=t.length,s=$o(n,r);Wo(i,s)||(e.uniform1iv(this.addr,s),jo(i,s));for(let e=0;e!==r;++e)n.setTexture3D(t[e]||Fo,s[e])}function Cl(e,t,n){const i=this.cache,r=t.length,s=$o(n,r);Wo(i,s)||(e.uniform1iv(this.addr,s),jo(i,s));for(let e=0;e!==r;++e)n.setTextureCube(t[e]||Oo,s[e])}function Nl(e,t,n){const i=this.cache,r=t.length,s=$o(n,r);Wo(i,s)||(e.uniform1iv(this.addr,s),jo(i,s));for(let e=0;e!==r;++e)n.setTexture2DArray(t[e]||Uo,s[e])}class Pl{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=function(e){switch(e){case 5126:return Xo;case 35664:return qo;case 35665:return Yo;case 35666:return Ko;case 35674:return Zo;case 35675:return Qo;case 35676:return Jo;case 5124:case 35670:return el;case 35667:case 35671:return tl;case 35668:case 35672:return nl;case 35669:case 35673:return il;case 5125:return rl;case 36294:return sl;case 36295:return al;case 36296:return ol;case 35678:case 36198:case 36298:case 36306:case 35682:return ll;case 35679:case 36299:case 36307:return ul;case 35680:case 36300:case 36308:case 36293:return cl;case 36289:case 36303:case 36311:case 36292:return hl}}(t.type)}}class Ll{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=function(e){switch(e){case 5126:return dl;case 35664:return pl;case 35665:return fl;case 35666:return ml;case 35674:return gl;case 35675:return _l;case 35676:return vl;case 5124:case 35670:return yl;case 35667:case 35671:return bl;case 35668:case 35672:return xl;case 35669:case 35673:return Sl;case 5125:return Tl;case 36294:return Ml;case 36295:return wl;case 36296:return El;case 35678:case 36198:case 36298:case 36306:case 35682:return Al;case 35679:case 36299:case 36307:return Rl;case 35680:case 36300:case 36308:case 36293:return Cl;case 36289:case 36303:case 36311:case 36292:return Nl}}(t.type)}}class Dl{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const i=this.seq;for(let r=0,s=i.length;r!==s;++r){const s=i[r];s.setValue(e,t[s.id],n)}}}const Il=/(\w+)(\])?(\[|\.)?/g;function Ul(e,t){e.seq.push(t),e.map[t.id]=t}function Fl(e,t,n){const i=e.name,r=i.length;for(Il.lastIndex=0;;){const s=Il.exec(i),a=Il.lastIndex;let o=s[1];const l="]"===s[2],u=s[3];if(l&&(o|=0),void 0===u||"["===u&&a+2===r){Ul(n,void 0===u?new Pl(o,e,t):new Ll(o,e,t));break}{let e=n.map[o];void 0===e&&(e=new Dl(o),Ul(n,e)),n=e}}}class Ol{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let i=0;i<n;++i){const n=e.getActiveUniform(t,i);Fl(n,e.getUniformLocation(t,n.name),this)}const i=[],r=[];for(const t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?i.push(t):r.push(t);i.length>0&&(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<s;e++){const r=e+1;i.push(`${r===t?">":" "} ${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);e<parseInt(n);e++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+e+" ]").replace(/UNROLLED_LOOP_INDEX/g,e);return r}function iu(e){let t=`precision ${e.precision} float;\n\tprecision ${e.precision} int;\n\tprecision ${e.precision} sampler2D;\n\tprecision ${e.precision} samplerCube;\n\tprecision ${e.precision} sampler3D;\n\tprecision ${e.precision} sampler2DArray;\n\tprecision ${e.precision} sampler2DShadow;\n\tprecision ${e.precision} samplerCubeShadow;\n\tprecision ${e.precision} sampler2DArrayShadow;\n\tprecision ${e.precision} isampler2D;\n\tprecision ${e.precision} isampler3D;\n\tprecision ${e.precision} isamplerCube;\n\tprecision ${e.precision} isampler2DArray;\n\tprecision ${e.precision} usampler2D;\n\tprecision ${e.precision} usampler3D;\n\tprecision ${e.precision} usamplerCube;\n\tprecision ${e.precision} usampler2DArray;\n\t`;return"highp"===e.precision?t+="\n#define HIGH_PRECISION":"mediump"===e.precision?t+="\n#define MEDIUM_PRECISION":"lowp"===e.precision&&(t+="\n#define LOW_PRECISION"),t}const ru={[l]:"SHADOWMAP_TYPE_PCF",[u]:"SHADOWMAP_TYPE_VSM"};const su={[Z]:"ENVMAP_TYPE_CUBE",[Q]:"ENVMAP_TYPE_CUBE",[te]:"ENVMAP_TYPE_CUBE_UV"};const au={[Q]:"ENVMAP_MODE_REFRACTION"};const ou={[V]:"ENVMAP_BLENDING_MULTIPLY",[G]:"ENVMAP_BLENDING_MIX",[H]:"ENVMAP_BLENDING_ADD"};function lu(e,t,n,i){const r=e.getContext(),s=n.defines;let a=n.vertexShader,o=n.fragmentShader;const l=function(e){return ru[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}(n),u=function(e){return!1===e.envMap?"ENVMAP_TYPE_CUBE":su[e.envMapMode]||"ENVMAP_TYPE_CUBE"}(n),c=function(e){return!1===e.envMap?"ENVMAP_MODE_REFLECTION":au[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}(n),h=function(e){return!1===e.envMap?"ENVMAP_BLENDING_NONE":ou[e.combine]||"ENVMAP_BLENDING_NONE"}(n),d=function(e){const t=e.envMapCubeUVHeight;if(null===t)return null;const n=Math.log2(t)-2,i=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:i,maxMip:n}}(n),p=function(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Xl).join("\n")}(n),f=function(e){const t=[];for(const n in e){const i=e[n];!1!==i&&t.push("#define "+n+" "+i)}return t.join("\n")}(s),m=r.createProgram();let g,_,v=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(Xl).join("\n"),g.length>0&&(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;r<i;r++){const i=e.getActiveAttrib(t,r),s=i.name;let a=1;i.type===e.FLOAT_MAT2&&(a=2),i.type===e.FLOAT_MAT3&&(a=3),i.type===e.FLOAT_MAT4&&(a=4),n[s]={type:i.type,location:e.getAttribLocation(t,s),locationSize:a}}return n}(r,m)}let M,w;r.attachShader(m,x),r.attachShader(m,S),void 0!==n.index0AttributeName?r.bindAttribLocation(m,0,n.index0AttributeName):!0===n.hasPositionAttribute&&r.bindAttribLocation(m,0,"position"),r.linkProgram(m),this.getUniforms=function(){return void 0===M&&T(this),M},this.getAttributes=function(){return void 0===w&&T(this),w};let E=!1===n.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===E&&(E=r.getProgramParameter(m,37297)),E},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=kl++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=x,this.fragmentShader=S,this}let uu=0;class cu{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){const i=this._getShaderCacheForMaterial(e);return!1===i.has(t)&&(i.add(t),t.usedTimes++),!1===i.has(n)&&(i.add(n),n.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const e of t)e.usedTimes--,0===e.usedTimes&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return void 0===n&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return void 0===n&&(n=new hu(e),t.set(e,n)),n}}class hu{constructor(e){this.id=uu++,this.code=e,this.usedTimes=0}}function du(e){return e===Pe||e===qe||e===mt}function pu(e,t,n,i,r,s){const a=new Yn,o=new cu,l=new Set,u=[],c=new Map,h=i.logarithmicDepthBuffer;let d=i.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(e){return l.add(e),0===e?"uv":`uv${e}`}return{getParameters:function(r,a,u,c,m,g){const _=c.fog,v=m.geometry,y=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?c.environment:null,b=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,x=t.get(r.envMap||y,b),S=x&&x.mapping===te?x.image.height:null,T=p[r.type];null!==r.precision&&(d=i.getMaxPrecision(r.precision),d!==r.precision&&qt("WebGLProgram.getParameters:",r.precision,"not supported, using",d,"instead."));const M=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,w=void 0!==M?M.length:0;let E,A,R,C,N=0;if(void 0!==v.morphAttributes.position&&(N=1),void 0!==v.morphAttributes.normal&&(N=2),void 0!==v.morphAttributes.color&&(N=3),T){const e=Ja[T];E=e.vertexShader,A=e.fragmentShader}else{E=r.vertexShader,A=r.fragmentShader;const e=o.getVertexShaderStage(r),t=o.getFragmentShaderStage(r);o.update(r,e,t),R=e.id,C=t.id}const P=e.getRenderTarget(),L=e.state.buffers.depth.getReversed(),D=!0===m.isInstancedMesh,I=!0===m.isBatchedMesh,U=!!r.map,F=!!r.matcap,O=!!x,B=!!r.aoMap,k=!!r.lightMap,z=!!r.bumpMap&&!1===r.wireframe,V=!!r.normalMap,G=!!r.displacementMap,H=!!r.emissiveMap,W=!!r.metalnessMap,j=!!r.roughnessMap,$=r.anisotropy>0,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;n<i;n++){const t=e[n];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){n.length>1&&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;e<S;e++){const S=r[e],T=S.color,M=S.intensity,w=S.distance;let E=null;if(S.shadow&&S.shadow.map&&(E=S.shadow.map.texture.format===Pe?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)s+=T.r*M,a+=T.g*M,o+=T.b*M;else if(S.isLightProbe){for(let e=0;e<9;e++)i.probe[e].addScaledVector(S.sh.coefficients[e],M);x++}else if(S.isSunLight){const e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){const e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),i.sunShadow[u]=t,i.sunShadowMap[u]=E;const r=e.getViewportCount();for(let t=0;t<r;t++)i.sunShadowMatrix[c+t]=e.getMatrix(t),i.sunShadowCascade[c+t]=e._cascadeData[t];c+=r,u++}i.sun[l]=e,l++}else if(S.isDirectionalLight){const e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){const e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,i.directionalShadow[h]=t,i.directionalShadowMap[h]=E,i.directionalShadowMatrix[h]=S.shadow.matrix,g++}i.directional[h]=e,h++}else if(S.isSpotLight){const e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(T).multiplyScalar(M),e.distance=w,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,i.spot[p]=e;const r=S.shadow;if(S.map&&(i.spotLightMap[y]=S.map,y++,r.updateMatrices(S),S.castShadow&&b++),i.spotLightMatrix[p]=r.matrix,S.castShadow){const e=n.get(S);e.shadowIntensity=r.intensity,e.shadowBias=r.bias,e.shadowNormalBias=r.normalBias,e.shadowRadius=r.radius,e.shadowMapSize=r.mapSize,i.spotShadow[p]=e,i.spotShadowMap[p]=E,v++}p++}else if(S.isRectAreaLight){const e=t.get(S);e.color.copy(T).multiplyScalar(M),e.halfWidth.set(.5*S.width,0,0),e.halfHeight.set(0,.5*S.height,0),i.rectArea[f]=e,f++}else if(S.isPointLight){const e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){const e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,i.pointShadow[d]=t,i.pointShadowMap[d]=E,i.pointShadowMatrix[d]=S.shadow.matrix,_++}i.point[d]=e,d++}else if(S.isHemisphereLight){const e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(M),e.groundColor.copy(S.groundColor).multiplyScalar(M),i.hemi[m]=e,m++}}f>0&&(!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<p;t++){const p=e[t];if(p.isSunLight){const e=i.sun[n];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(d),n++}else if(p.isDirectionalLight){const e=i.directional[o];e.direction.setFromMatrixPosition(p.matrixWorld),r.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(d),o++}else if(p.isSpotLight){const e=i.spot[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(p.matrixWorld),r.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(d),u++}else if(p.isRectAreaLight){const e=i.rectArea[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),a.identity(),s.copy(p.matrixWorld),s.premultiply(d),a.extractRotation(s),e.halfWidth.set(.5*p.width,0,0),e.halfHeight.set(0,.5*p.height,0),e.halfWidth.applyMatrix4(a),e.halfHeight.applyMatrix4(a),c++}else if(p.isPointLight){const e=i.point[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(d),l++}else if(p.isHemisphereLight){const e=i.hemi[h];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(d),h++}}},state:i}}function Tu(e){const t=new Su(e),n=[],i=[],r=[];const s={lightsArray:n,shadowsArray:i,lightProbeGridArray:r,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:function(e){s.camera=e,n.length=0,i.length=0,r.length=0},state:s,setupLights:function(){t.setup(n)},setupLightsView:function(e){t.setupView(n,e)},pushLight:function(e){n.push(e)},pushShadow:function(e){i.push(e)},pushLightProbeGrid:function(e){r.push(e)}}}function Mu(e){let t=new WeakMap;return{get:function(n,i=0){const r=t.get(n);let s;return void 0===r?(s=new Tu(e),t.set(n,[s])):i>=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;u<c;u++){const c=t[u],h=l[c.materialIndex];if(h&&h.visible){const t=S(n,h,a,o);n.onBeforeShadow(e,n,r,s,i,t,c),e.renderBufferDirect(s,null,i,t,n,c),n.onAfterShadow(e,n,r,s,i,t,c)}}}else if(l.visible){const t=S(n,l,a,o);n.onBeforeShadow(e,n,r,s,i,t,null),e.renderBufferDirect(s,null,i,t,n,null),n.onAfterShadow(e,n,r,s,i,t,null)}}const l=n.children;for(let e=0,t=l.length;e<t;e++)T(l[e],r,s,a,o)}function M(e){e.target.removeEventListener("dispose",M);for(const t in u){const n=u[t],i=e.target.uuid;if(i in n){n[i].dispose(),delete n[i]}}}this.render=function(t,n,o){if(!1===y.enabled)return;if(!1===y.autoUpdate&&!1===y.needsUpdate)return;if(0===t.length)return;2===this.type&&(qt("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=1);const l=e.getRenderTarget(),u=e.getActiveCubeFace(),c=e.getActiveMipmapLevel(),h=e.state;h.setBlending(0),!0===h.buffers.depth.getReversed()?h.buffers.color.setClear(0,0,0,0):h.buffers.color.setClear(1,1,1,1),h.buffers.depth.setTest(!0),h.setScissorTest(!1);const d=b!==this.type;d&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let l=0,u=t.length;l<u;l++){const u=t[l],c=u.shadow;if(void 0===c){qt("WebGLShadowMap:",u,"has no shadow.");continue}if(!1===c.autoUpdate&&!1===c.needsUpdate)continue;r.copy(c.mapSize);const f=c.getFrameExtents();r.multiply(f),s.copy(c.mapSize),(r.x>p||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<g;t++){const r=c.getCamera(t);if(u.isPointLight){const e=c.camera,n=c.matrix,i=u.distance||e.far;i!==e.far&&(e.far=i,e.updateProjectionMatrix()),Ru.setFromMatrixPosition(u.matrixWorld),e.position.copy(Ru),Cu.copy(e.position),Cu.add(wu[t]),e.up.copy(Eu[t]),e.lookAt(Cu),e.updateMatrixWorld(),n.makeTranslation(-Ru.x,-Ru.y,-Ru.z),Au.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),c._frustum.setFromProjectionMatrix(Au,e.coordinateSystem,e.reversedDepth)}if(c.map.isWebGLCubeRenderTarget)e.setRenderTarget(c.map,t),e.clear();else{0===t&&(e.setRenderTarget(c.map),e.clear());const n=c.getViewport(t);a.set(s.x*n.x,s.y*n.y,s.x*n.z,s.y*n.w),h.viewport(a)}i=c.getFrustum(t),T(n,o,r,u,this.type)}!0!==c.isPointLightShadow&&3===this.type&&x(c,o),c.needsUpdate=!1}b=this.type,y.needsUpdate=!1,e.setRenderTarget(l,u,c)}}function Pu(e,t){const n=new function(){let t=!1;const n=new Dn;let i=null;const r=new Dn(0,0,0,0);return{setMask:function(n){i===n||t||(e.colorMask(n,n,n,n),i=n)},setLocked:function(e){t=e},setClear:function(t,i,s,a,o){!0===o&&(t*=a,i*=a,s*=a),n.set(t,i,s,a),!1===r.equals(n)&&(e.clearColor(t,i,s,a),r.copy(n))},reset:function(){t=!1,i=null,r.set(-1,0,0,0)}}},i=new function(){let n=!1,i=!1,r=null,s=null,a=null;return{setReversed:function(e){if(i!==e){const n=t.get("EXT_clip_control");e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),i=e;const r=a;a=null,this.setClear(r)}},getReversed:function(){return i},setTest:function(t){t?se(e.DEPTH_TEST):ae(e.DEPTH_TEST)},setMask:function(t){r===t||n||(e.depthMask(t),r=t)},setFunc:function(t){if(i&&(t=Qt[t]),s!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:default:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL)}s=t}},setLocked:function(e){n=e},setClear:function(t){a!==t&&(a=t,i&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,r=null,s=null,a=null,i=!1}}},r=new function(){let t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,u=null;return{setTest:function(n){t||(n?se(e.STENCIL_TEST):ae(e.STENCIL_TEST))},setMask:function(i){n===i||t||(e.stencilMask(i),n=i)},setFunc:function(t,n,a){i===t&&r===n&&s===a||(e.stencilFunc(t,n,a),i=t,r=n,s=a)},setOp:function(t,n,i){a===t&&o===n&&l===i||(e.stencilOp(t,n,i),a=t,o=n,l=i)},setLocked:function(e){t=e},setClear:function(t){u!==t&&(e.clearStencil(t),u=t)},reset:function(){t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,u=null}}},s=new WeakMap,a=new WeakMap;let o={},l={},u={},c=new WeakMap,h=[],d=null,g=!1,_=null,D=null,I=null,U=null,F=null,O=null,B=null,k=new yi(0,0,0),z=0,V=!1,G=null,H=null,W=null,j=null,$=null;const X=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let q=!1,Y=0;const K=e.getParameter(e.VERSION);-1!==K.indexOf("WebGL")?(Y=parseFloat(/^WebGL (\d)/.exec(K)[1]),q=Y>=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;a<i;a++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,r,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(n+a,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const re={};function se(t){!0!==o[t]&&(e.enable(t),o[t]=!0)}function ae(t){!1!==o[t]&&(e.disable(t),o[t]=!1)}re[e.TEXTURE_2D]=ie(e.TEXTURE_2D,e.TEXTURE_2D,1),re[e.TEXTURE_CUBE_MAP]=ie(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),re[e.TEXTURE_2D_ARRAY]=ie(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),re[e.TEXTURE_3D]=ie(e.TEXTURE_3D,e.TEXTURE_3D,1,1),n.setClear(0,0,0,1),i.setClear(1),r.setClear(0),se(e.DEPTH_TEST),i.setFunc(3),ce(!1),he(1),se(e.CULL_FACE),ue(0);const oe={[p]:e.FUNC_ADD,[f]:e.FUNC_SUBTRACT,[m]:e.FUNC_REVERSE_SUBTRACT};oe[103]=e.MIN,oe[104]=e.MAX;const le={[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};function ue(t,n,i,r,s,a,o,l,u,c){if(0!==t){if(!1===g&&(se(e.BLEND),g=!0),5===t)s=s||n,a=a||i,o=o||r,n===D&&s===F||(e.blendEquationSeparate(oe[n],oe[s]),D=n,F=s),i===I&&r===U&&a===O&&o===B||(e.blendFuncSeparate(le[i],le[r],le[a],le[o]),I=i,U=r,O=a,B=o),!1!==l.equals(k)&&u===z||(e.blendColor(l.r,l.g,l.b,u),k.copy(l),z=u),_=t,V=!1;else if(t!==_||c!==V){if(D===p&&F===p||(e.blendEquation(e.FUNC_ADD),D=p,F=p),c)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Yt("WebGLState: Invalid blending: ",t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:Yt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Yt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Yt("WebGLState: Invalid blending: ",t)}I=null,U=null,O=null,B=null,k.set(0,0,0),z=0,_=t,V=c}}else!0===g&&(ae(e.BLEND),g=!1)}function ce(t){G!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),G=t)}function he(t){0!==t?(se(e.CULL_FACE),t!==H&&(1===t?e.cullFace(e.BACK):2===t?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):ae(e.CULL_FACE),H=t}function de(t,n,r){t?(se(e.POLYGON_OFFSET_FILL),j===n&&$===r||(j=n,$=r,i.getReversed()&&(n=-n),e.polygonOffset(n,r))):ae(e.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:i,stencil:r},enable:se,disable:ae,bindFramebuffer:function(t,n){return u[t]!==n&&(e.bindFramebuffer(t,n),u[t]=n,t===e.DRAW_FRAMEBUFFER&&(u[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(u[e.DRAW_FRAMEBUFFER]=n),!0)},drawBuffers:function(t,n){let i=h,r=!1;if(t){i=c.get(n),void 0===i&&(i=[],c.set(n,i));const s=t.textures;if(i.length!==s.length||i[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=s.length;t<n;t++)i[t]=e.COLOR_ATTACHMENT0+t;i.length=s.length,r=!0}}else i[0]!==e.BACK&&(i[0]=e.BACK,r=!0);r&&e.drawBuffers(i)},useProgram:function(t){return d!==t&&(e.useProgram(t),d=t,!0)},setBlending:ue,setMaterial:function(t,s){2===t.side?ae(e.CULL_FACE):se(e.CULL_FACE);let a=1===t.side;s&&(a=!a),ce(a),1===t.blending&&!1===t.transparent?ue(0):ue(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),i.setFunc(t.depthFunc),i.setTest(t.depthTest),i.setMask(t.depthWrite),n.setMask(t.colorWrite);const o=t.stencilWrite;r.setTest(o),o&&(r.setMask(t.stencilWriteMask),r.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),r.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),de(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?se(e.SAMPLE_ALPHA_TO_COVERAGE):ae(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:ce,setCullFace:he,setLineWidth:function(t){t!==W&&(q&&e.lineWidth(t),W=t)},setPolygonOffset:de,setScissorTest:function(t){t?se(e.SCISSOR_TEST):ae(e.SCISSOR_TEST)},activeTexture:function(t){void 0===t&&(t=e.TEXTURE0+X-1),Z!==t&&(e.activeTexture(t),Z=t)},bindTexture:function(t,n,i){void 0===i&&(i=null===Z?e.TEXTURE0+X-1:Z);let r=Q[i];void 0===r&&(r={type:void 0,texture:void 0},Q[i]=r),r.type===t&&r.texture===n||(Z!==i&&(e.activeTexture(i),Z=i),e.bindTexture(t,n||re[t]),r.type=t,r.texture=n)},unbindTexture:function(){const t=Q[Z];void 0!==t&&void 0!==t.type&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)},compressedTexImage2D:function(){try{e.compressedTexImage2D(...arguments)}catch(e){Yt("WebGLState:",e)}},compressedTexImage3D:function(){try{e.compressedTexImage3D(...arguments)}catch(e){Yt("WebGLState:",e)}},texImage2D:function(){try{e.texImage2D(...arguments)}catch(e){Yt("WebGLState:",e)}},texImage3D:function(){try{e.texImage3D(...arguments)}catch(e){Yt("WebGLState:",e)}},pixelStorei:function(t,n){l[t]!==n&&(e.pixelStorei(t,n),l[t]=n)},getParameter:function(t){return void 0!==l[t]?l[t]:e.getParameter(t)},updateUBOMapping:function(t,n){let i=a.get(n);void 0===i&&(i=new WeakMap,a.set(n,i));let r=i.get(t);void 0===r&&(r=e.getUniformBlockIndex(n,t.name),i.set(t,r))},uniformBlockBinding:function(t,n){const i=a.get(n).get(t);s.get(n)!==i&&(e.uniformBlockBinding(n,i,t.__bindingPointIndex),s.set(n,i))},texStorage2D:function(){try{e.texStorage2D(...arguments)}catch(e){Yt("WebGLState:",e)}},texStorage3D:function(){try{e.texStorage3D(...arguments)}catch(e){Yt("WebGLState:",e)}},texSubImage2D:function(){try{e.texSubImage2D(...arguments)}catch(e){Yt("WebGLState:",e)}},texSubImage3D:function(){try{e.texSubImage3D(...arguments)}catch(e){Yt("WebGLState:",e)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D(...arguments)}catch(e){Yt("WebGLState:",e)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D(...arguments)}catch(e){Yt("WebGLState:",e)}},scissor:function(t){!1===te.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),te.copy(t))},viewport:function(t){!1===ne.equals(t)&&(e.viewport(t.x,t.y,t.z,t.w),ne.copy(t))},reset:function(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),i.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),o={},l={},Z=null,Q={},u={},c=new WeakMap,h=[],d=null,g=!1,_=null,D=null,I=null,U=null,F=null,O=null,B=null,k=new yi(0,0,0),z=0,V=!1,G=null,H=null,W=null,j=null,$=null,te.set(0,0,e.canvas.width,e.canvas.height),ne.set(0,0,e.canvas.width,e.canvas.height),n.reset(),i.reset(),r.reset()}}}function Lu(e,t,n,i,r,s,a){const o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),u=new dn,c=new WeakMap,h=new Set;let d;const p=new WeakMap;let f=!1;try{f="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(e){}function m(e,t){return f?new OffscreenCanvas(e,t):Ht("canvas")}function g(e,t,n){let i=1;const r=W(e);if((r.width>n||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;i<n.__webglFramebuffer[t].length;i++)e.deleteFramebuffer(n.__webglFramebuffer[t][i]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}const r=t.textures;for(let t=0,n=r.length;t<n;t++){const n=i.get(r[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),a.memory.textures--),i.remove(r[t])}i.remove(t)}(n)}function w(t){const n=i.get(t);e.deleteTexture(n.__webglTexture);const r=t.source;delete p.get(r)[n.__cacheKey],a.memory.textures--}let E=0;function A(t,r){const s=i.get(t);if(t.isVideoTexture&&function(e){const t=a.render.frame;c.get(e)!==t&&(c.set(e,t),e.update())}(t),!1===t.isRenderTargetTexture&&!0!==t.isExternalTexture&&t.version>0&&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;t<r;t++)f=y[t],T?w&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,i,p,f.data):n.texImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,i,p,f.data);a.generateMipmaps=!1}else T?(M&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),w&&function(t,i,r,s){const a=t.updateRanges;if(0===a.length)n.texSubImage2D(e.TEXTURE_2D,0,0,0,i.width,i.height,r,s,i.data);else{a.sort((e,t)=>e.start-t.start);let o=0;for(let e=1;e<a.length;e++){const t=a[o],n=a[e],r=t.start+t.count,s=D(n.start,i.width,4),l=D(t.start,i.width,4);n.start<=r+1&&s===l&&D(n.start+n.count-1,i.width,4)===s?t.count=Math.max(t.count,n.start+n.count-t.start):(++o,a[o]=n)}a.length=o+1;const l=n.getParameter(e.UNPACK_ROW_LENGTH),u=n.getParameter(e.UNPACK_SKIP_PIXELS),c=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,i.width);for(let t=0,o=a.length;t<o;t++){const o=a[t],l=Math.floor(o.start/4),u=Math.ceil(o.count/4),c=l%i.width,h=Math.floor(l/i.width),d=u,p=1;n.pixelStorei(e.UNPACK_SKIP_PIXELS,c),n.pixelStorei(e.UNPACK_SKIP_ROWS,h),n.texSubImage2D(e.TEXTURE_2D,0,c,h,d,p,r,s,i.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,l),n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,c)}}(a,t,i,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,i,p,t.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){T&&M&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let r=0,s=y.length;r<s;r++)if(f=y[r],a.format!==Ee)if(null!==i)if(T){if(w)if(a.layerUpdates.size>0){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;t<r;t++)f=y[t],a.format!==Ee?null!==i?T?w&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,i,f.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,f.data):qt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):T?w&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,f.width,f.height,i,p,f.data):n.texImage2D(e.TEXTURE_2D,t,m,f.width,f.height,0,i,p,f.data)}else if(a.isDataArrayTexture)if(T){if(M&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),w)if(a.layerUpdates.size>0){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<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,r,s,0,i,p,null),r>>=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<r;t++)f=y[t],T?w&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,i,p,f):n.texImage2D(e.TEXTURE_2D,t,m,i,p,f);a.generateMipmaps=!1}else if(T){if(M){const i=W(t);n.texStorage2D(e.TEXTURE_2D,E,m,i.width,i.height)}w&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,i,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,i,p,t);_(a)&&v(l),d.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function U(t,r,a,l,u,c){const h=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=b(a.internalFormat,h,d,a.normalized,a.colorSpace),f=i.get(r),m=i.get(a);if(m.__renderTarget=r,!f.__hasExternalTextures){const t=Math.max(1,r.width>>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<t.length;r++){const a=t[r],l=s.convert(a.format,a.colorSpace),u=s.convert(a.type),c=b(a.internalFormat,l,u,a.normalized,a.colorSpace);G(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,V(n),c,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,V(n),c,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,c,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function O(t,r,a){const l=!0===r.isWebGLCubeRenderTarget;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const u=i.get(r.depthTexture);if(u.__renderTarget=r,u.__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),l){if(void 0===u.__webglInit&&(u.__webglInit=!0,r.depthTexture.addEventListener("dispose",T)),void 0===u.__webglTexture){u.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,u.__webglTexture),P(e.TEXTURE_CUBE_MAP,r.depthTexture);const t=s.convert(r.depthTexture.format),i=s.convert(r.depthTexture.type);let a;r.depthTexture.format===Ae?a=e.DEPTH_COMPONENT24:r.depthTexture.format===Re&&(a=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,a,r.width,r.height,0,t,i,null)}}else A(r.depthTexture,0);const c=u.__webglTexture,h=V(r),d=l?e.TEXTURE_CUBE_MAP_POSITIVE_X+a:e.TEXTURE_2D,p=r.depthTexture.format===Re?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(r.depthTexture.format===Ae)G(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,c,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,c,0);else{if(r.depthTexture.format!==Re)throw new Error("THREE.WebGLTextures: Unknown depthTexture format.");G(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,c,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,c,0)}}function B(t){const r=i.get(t),s=!0===t.isWebGLCubeRenderTarget;if(r.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(r.__depthDisposeCallback&&r.__depthDisposeCallback(),e){const t=()=>{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;i<A.length;i++){const r=A[i];a.format!==Ee?null!==y?M?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,r.width,r.height,y,r.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,T,r.width,r.height,0,r.data):qt("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,r.width,r.height,y,x,r.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,T,r.width,r.height,0,y,x,r.data)}}}else{if(A=a.mipmaps,M&&w){A.length>0&&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;i<A.length;i++){const r=A[i].image[t].image;M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,r.width,r.height,y,x,r.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,T,r.width,r.height,0,y,x,r.data)}}else{M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,f[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,T,y,x,f[t]);for(let i=0;i<A.length;i++){const r=A[i];M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,y,x,r.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,T,y,x,r.image[t])}}}_(a)&&v(e.TEXTURE_CUBE_MAP),c.__version=u.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):n.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)},this.rebindTextures=function(t,n,r){const s=i.get(t);void 0!==n&&U(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==r&&B(t)},this.setupRenderTarget=function(t){const r=t.texture,o=i.get(t),l=i.get(r);t.addEventListener("dispose",M);const u=t.textures,c=!0===t.isWebGLCubeRenderTarget,h=u.length>1;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;n<r.mipmaps.length;n++)o.__webglFramebuffer[t][n]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<r.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(h)for(let t=0,n=u.length;t<n;t++){const n=i.get(u[t]);void 0===n.__webglTexture&&(n.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===G(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n<u.length;n++){const i=u[n];o.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[n]);const r=s.convert(i.format,i.colorSpace),a=s.convert(i.type),l=b(i.internalFormat,r,a,i.normalized,i.colorSpace,!0===t.isXRRenderTarget),c=V(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,c,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,o.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),F(o.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(c){n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),P(e.TEXTURE_CUBE_MAP,r);for(let n=0;n<6;n++)if(r.mipmaps&&r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)U(o.__webglFramebuffer[n][i],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,i);else U(o.__webglFramebuffer[n],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(r)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(h){for(let r=0,s=u.length;r<s;r++){const s=u[r],a=i.get(s);let l=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(l=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(l,a.__webglTexture),P(l,s),U(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0+r,l,0),_(s)&&v(l)}n.unbindTexture()}else{let i=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(i=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(i,l.__webglTexture),P(i,r),r.mipmaps&&r.mipmaps.length>0)for(let n=0;n<r.mipmaps.length;n++)U(o.__webglFramebuffer[n],t,r,e.COLOR_ATTACHMENT0,i,n);else U(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0,i,0);_(r)&&v(i),n.unbindTexture()}t.depthBuffer&&B(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let r=0,s=t.length;r<s;r++){const s=t[r];if(_(s)){const t=y(e),r=i.get(s).__webglTexture;n.bindTexture(t,r),v(t),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)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;t<r.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,c.__webglMultisampledFramebuffer);const d=t.texture.mipmaps;d&&d.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let n=0;n<r.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(o|=e.STENCIL_BUFFER_BIT)),h){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,c.__webglColorRenderbuffer[n]);const t=i.get(r[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&(k.length=0,z.length=0,k.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&!1===t.storeMultisampledDepthBuffer&&(k.push(u),z.push(u),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,z)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,k))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),h)for(let t=0;t<r.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,c.__webglColorRenderbuffer[t]);const s=i.get(r[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&!1===t.storeMultisampledDepthBuffer&&l){const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}},this.setupDepthRenderbuffer=B,this.setupFrameBufferTexture=U,this.useMultisampledRTT=G,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function Du(e,t){return{convert:function(n,i=""){let r;const s=Sn.getTransfer(i);if(n===he)return e.UNSIGNED_BYTE;if(n===ye)return e.UNSIGNED_SHORT_4_4_4_4;if(n===be)return e.UNSIGNED_SHORT_5_5_5_1;if(n===Se)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===Te)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===de)return e.BYTE;if(n===pe)return e.SHORT;if(n===fe)return e.UNSIGNED_SHORT;if(n===me)return e.INT;if(n===ge)return e.UNSIGNED_INT;if(n===_e)return e.FLOAT;if(n===ve)return e.HALF_FLOAT;if(n===Me)return e.ALPHA;if(n===we)return e.RGB;if(n===Ee)return e.RGBA;if(n===Ae)return e.DEPTH_COMPONENT;if(n===Re)return e.DEPTH_STENCIL;if(n===Ce)return e.RED;if(n===Ne)return e.RED_INTEGER;if(n===Pe)return e.RG;if(n===Le)return e.RG_INTEGER;if(n===Ie)return e.RGBA_INTEGER;if(n===Ue||n===Fe||n===Oe||n===Be)if(s===xt){if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(n===Ue)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Fe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Oe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Be)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(n===Ue)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Fe)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Oe)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Be)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(n===ke||n===ze||n===Ve||n===Ge){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(n===ke)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===ze)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Ve)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Ge)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(n===He||n===We||n===je||n===$e||n===Xe||n===qe||n===Ye){if(r=t.get("WEBGL_compressed_texture_etc"),null===r)return null;if(n===He||n===We)return s===xt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===je)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===$e)return r.COMPRESSED_R11_EAC;if(n===Xe)return r.COMPRESSED_SIGNED_R11_EAC;if(n===qe)return r.COMPRESSED_RG11_EAC;if(n===Ye)return r.COMPRESSED_SIGNED_RG11_EAC}if(n===Ke||n===Ze||n===Qe||n===Je||n===et||n===tt||n===nt||n===it||n===rt||n===st||n===at||n===ot||n===lt||n===ut){if(r=t.get("WEBGL_compressed_texture_astc"),null===r)return null;if(n===Ke)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Ze)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Qe)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Je)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===et)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===tt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===nt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===it)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===rt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===st)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===at)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===ot)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===lt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ut)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(n===ct||n===ht||n===dt){if(r=t.get("EXT_texture_compression_bptc"),null===r)return null;if(n===ct)return s===xt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===ht)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===dt)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(n===pt||n===ft||n===mt||n===gt){if(r=t.get("EXT_texture_compression_rgtc"),null===r)return null;if(n===pt)return r.COMPRESSED_RED_RGTC1_EXT;if(n===ft)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===mt)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===gt)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return n===xe?e.UNSIGNED_INT_24_8:void 0!==e[n]?e[n]:null}}}class Iu{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(null===this.texture){const n=new vs(e.texture);e.depthNear===t.depthNear&&e.depthFar===t.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,n=new js({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 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<b.length;e++){const t=x[e];null!==t&&(x[e]=null,b[e].disconnect(t))}C=null,N=null,m.reset();for(const e in g)delete g[e];if(e.setRenderTarget(v),d=null,h=null,c=null,i=null,y=null,B.stop(),n.isPresenting=!1,e.setPixelRatio(T),e.setSize(S.width,S.height,!1),null!==M){const e=M.camera;e.fov=M.fov,e.zoom=M.zoom,e.updateProjectionMatrix(),M=null}n.dispatchEvent({type:"sessionend"})}function D(e){for(let t=0;t<e.removed.length;t++){const n=e.removed[t],i=x.indexOf(n);i>=0&&(x[i]=null,b[i].disconnect(n))}for(let t=0;t<e.added.length;t++){const n=e.added[t];let i=x.indexOf(n);if(-1===i){for(let e=0;e<b.length;e++){if(e>=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;e<s.length;e++)F(s[e],r);2===s.length?function(e,t,n){I.setFromMatrixPosition(t.matrixWorld),U.setFromMatrixPosition(n.matrixWorld);const i=I.distanceTo(U),r=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],u=(r[9]-1)/r[5],c=(r[8]-1)/r[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=i/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,r=d-m,s=p+(i-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(r,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(R,w,E):R.projectionMatrix.copy(w.projectionMatrix),null===M&&e.isPerspectiveCamera&&(M={camera:e,fov:e.fov,zoom:e.zoom}),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*rn*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,R,r)},this.getCamera=function(){return R},this.getFoveation=function(){if(null!==h||null!==d)return o},this.setFoveation=function(e){o=e,null!==h&&(h.fixedFoveation=e),null!==d&&void 0!==d.fixedFoveation&&(d.fixedFoveation=e)},this.hasDepthSensing=function(){return null!==m.texture},this.getDepthSensingMesh=function(){return m.getMesh(R)},this.getCameraTexture=function(e){return g[e]};let O=null;const B=new Ya;B.setAnimationLoop(function(t,r){if(u=r.getViewerPose(l||s),p=r,null!==u){const t=u.views;null!==d&&(e.setRenderTargetFramebuffer(y,d.framebuffer),e.setRenderTarget(y));let r=!1;t.length!==R.cameras.length&&(R.cameras.length=0,r=!0);for(let n=0;n<t.length;n++){const i=t[n];let s=null;if(null!==d)s=d.getViewport(i);else{const t=c.getViewSubImage(h,i);s=t.viewport,0===n&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let a=A[n];void 0===a&&(a=new Ta,a.layers.enable(n),a.viewport=new Dn,A[n]=a),a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(i.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===n&&(R.matrix.copy(a.matrix),R.matrix.decompose(R.position,R.quaternion,R.scale)),!0===r&&R.cameras.push(a)}const s=i.enabledFeatures;if(s&&s.includes("depth-sensing")&&"gpu-optimized"==i.depthUsage&&f){c=n.getBinding();const e=c.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&m.init(e,i.renderState)}if(s&&s.includes("camera-access")&&f){e.state.unbindTexture(),c=n.getBinding();for(let e=0;e<t.length;e++){const n=t[e].camera;if(n){let e=g[n];e||(e=new vs,g[n]=e);const t=c.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){const t=x[e],n=b[e];null!==t&&void 0!==n&&n.update(t,r,l||s)}O&&O(t,r),r.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:r}),p=null}),this.setAnimationLoop=function(e){O=e},this.dispose=function(){}}}const Fu=new Bn,Ou=new _n;function Bu(e,t){function n(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function i(e,i){e.opacity.value=i.opacity,i.color&&e.diffuse.value.copy(i.color),i.emissive&&e.emissive.value.copy(i.emissive).multiplyScalar(i.emissiveIntensity),i.map&&(e.map.value=i.map,n(i.map,e.mapTransform)),i.alphaMap&&(e.alphaMap.value=i.alphaMap,n(i.alphaMap,e.alphaMapTransform)),i.bumpMap&&(e.bumpMap.value=i.bumpMap,n(i.bumpMap,e.bumpMapTransform),e.bumpScale.value=i.bumpScale,1===i.side&&(e.bumpScale.value*=-1)),i.normalMap&&(e.normalMap.value=i.normalMap,n(i.normalMap,e.normalMapTransform),e.normalScale.value.copy(i.normalScale),1===i.side&&e.normalScale.value.negate()),i.displacementMap&&(e.displacementMap.value=i.displacementMap,n(i.displacementMap,e.displacementMapTransform),e.displacementScale.value=i.displacementScale,e.displacementBias.value=i.displacementBias),i.emissiveMap&&(e.emissiveMap.value=i.emissiveMap,n(i.emissiveMap,e.emissiveMapTransform)),i.specularMap&&(e.specularMap.value=i.specularMap,n(i.specularMap,e.specularMapTransform)),i.alphaTest>0&&(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;n<i.length;n++){const r=i[n],s=c(r);u(r,t.__data,e),"number"==typeof r||"boolean"==typeof r||r.isMatrix3||ArrayBuffer.isView(r)||(e+=s.storage/Float32Array.BYTES_PER_ELEMENT)}}else u(i,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,n,t.__data)}}function u(e,t,n){"number"==typeof e||"boolean"==typeof e?t[0]=e:e.isMatrix3?(t[0]=e.elements[0],t[1]=e.elements[1],t[2]=e.elements[2],t[3]=0,t[4]=e.elements[3],t[5]=e.elements[4],t[6]=e.elements[5],t[7]=0,t[8]=e.elements[6],t[9]=e.elements[7],t[10]=e.elements[8],t[11]=0):ArrayBuffer.isView(e)?t.set(new e.constructor(e.buffer,e.byteOffset,t.length)):e.toArray(t,n)}function c(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?qt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):qt("WebGLRenderer: Unsupported uniform value type.",e),t}function h(t){const n=t.target;n.removeEventListener("dispose",h);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,u){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let e=0,r=t.length;e<r;e++){const r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){const t=r[e],s=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=s.length;e<r;e++){const r=c(s[e]),a=n%i,o=a%r.boundary,l=a+o;n+=o,0!==l&&i-l<r.storage&&(n+=i-l),t.__data=new Float32Array(r.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=r.storage}}}const r=n%i;r>0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e<o;e++)if(-1===a.indexOf(e))return a.push(e),e;return Yt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();t.__bindingPointIndex=n;const i=e.createBuffer(),r=t.__size,s=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,i),e.bufferData(e.UNIFORM_BUFFER,r,s),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,i),i}(n),r[n.id]=d,n.addEventListener("dispose",h));const p=u.program;i.updateUBOMapping(n,p);const f=t.render.frame;s[n.id]!==f&&(!function(t){const n=r[t.id],i=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let e=0,t=i.length;e<t;e++){const t=i[e];if(Array.isArray(t))for(let n=0,i=t.length;n<i;n++)l(t[n],e,n,s);else l(t,e,0,s)}e.bindBuffer(e.UNIFORM_BUFFER,null)}(n),s[n.id]=f)},dispose:function(){for(const t in r)e.deleteBuffer(r[t]);a=[],r={},s={}}}}Ou.set(-1,0,0,0,1,0,0,0,1);const zu=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 Vu=null;const Gu=new Ar,Hu=new dn,Wu=new fn,ju=new dn,$u=new dn,Xu=new fn,qu=new fn,Yu=new Bn,Ku=new fn,Zu=new fn;let Qu=null,Ju=null;const ec=[],tc=-1,nc=0,ic=1;class rc extends Xa{constructor(e,n,r=null){super(n,r),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new Ga,this.mouseButtons={LEFT:i,MIDDLE:i,RIGHT:t},this.touches={ONE:s},this._onPointerMove=sc.bind(this),this._onPointerDown=ac.bind(this),this._onPointerCancel=oc.bind(this),this._onContextMenu=lc.bind(this),null!==r&&this.connect(r)}connect(e){super.connect(e),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerCancel),this.domElement.addEventListener("pointerleave",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerCancel),this.domElement.removeEventListener("pointerleave",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();Hu.x=(e.clientX-t.left)/t.width*2-1,Hu.y=-(e.clientY-t.top)/t.height*2+1}_updateState(e){let n;if("touch"===e.pointerType)n=this.touches.ONE;else switch(e.button){case 0:n=this.mouseButtons.LEFT;break;case 1:n=this.mouseButtons.MIDDLE;break;case 2:n=this.mouseButtons.RIGHT;break;default:n=null}switch(n){case i:case s:this.state=nc;break;case t:case r:this.state=ic;break;default:this.state=tc}}}function sc(e){const t=this.object,n=this.domElement,i=this.raycaster;if(!1!==this.enabled){if(this._updatePointer(e),i.setFromCamera(Hu,t),Qu)this.state===nc?i.ray.intersectPlane(Gu,Xu)&&(Qu.position.copy(Xu.sub(Wu).applyMatrix4(Yu)),this.dispatchEvent({type:"drag",object:Qu})):this.state===ic&&(ju.subVectors(Hu,$u).multiplyScalar(this.rotateSpeed),Qu.rotateOnWorldAxis(Ku,ju.x),Qu.rotateOnWorldAxis(Zu.normalize(),-ju.y),this.dispatchEvent({type:"drag",object:Qu})),$u.copy(Hu);else if("mouse"===e.pointerType||"pen"===e.pointerType)if(ec.length=0,i.setFromCamera(Hu,t),i.intersectObjects(this.objects,this.recursive,ec),ec.length>0){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<o;++s)l+=(a=i[s]).x||0,u+=a.y||0,c+=a.z||0;for(l=(l/o-e)*r,u=(u/o-t)*r,c=(c/o-n)*r,s=0;s<o;++s)a=i[s],l&&(a.x-=l),u&&(a.y-=u),c&&(a.z-=c)}return null==e&&(e=0),null==t&&(t=0),null==n&&(n=0),s.initialize=function(e){i=e},s.x=function(t){return arguments.length?(e=+t,s):e},s.y=function(e){return arguments.length?(t=+e,s):t},s.z=function(e){return arguments.length?(n=+e,s):n},s.strength=function(e){return arguments.length?(r=+e,s):r},s}function hc(e,t,n){if(isNaN(t))return e;var i,r,s,a,o,l,u=e._root,c={data:n},h=e._x0,d=e._x1;if(!u)return e._root=c,e;for(;u.length;)if((a=t>=(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;a<t;++a)isNaN(s=+this._x.call(null,e[a]))||(n[a]=s,s<i&&(i=s),s>r&&(r=s));if(i>r)return this;this.cover(i).cover(r);for(let i=0;i<t;++i)hc(this,n[i],e[i]);return this},_c.cover=function(e){if(isNaN(e=+e))return this;var t=this._x0,n=this._x1;if(isNaN(t))n=(t=Math.floor(e))+1;else{for(var i,r,s=n-t||1,a=this._root;t>e||e>=n;)switch(r=+(e<t),(i=new Array(2))[r]=a,a=i,s*=2,r){case 0:n=t+s;break;case 1:t=n-s}this._root&&this._root.length&&(this._root=a)}return this._x0=t,this._x1=n,this},_c.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},_c.extent=function(e){return arguments.length?this.cover(+e[0][0]).cover(+e[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]},_c.find=function(e,t){var n,i,r,s,a,o=this._x0,l=this._x1,u=[],c=this._root;for(c&&u.push(new dc(c,o,l)),null==t?t=1/0:(o=e-t,l=e+t);s=u.pop();)if(!(!(c=s.node)||(i=s.x0)>l||(r=s.x1)<o))if(c.length){var h=(i+r)/2;u.push(new dc(c[1],h,r),new dc(c[0],i,h)),(a=+(e>=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<t&&(t=d,o=e-d,l=e+d,n=c.data)}return n},_c.remove=function(e){if(isNaN(s=+this._x.call(null,e)))return this;var t,n,i,r,s,a,o,l,u,c=this._root,h=this._x0,d=this._x1;if(!c)return this;if(c.length)for(;;){if((o=s>=(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<n;++t)this.remove(e[t]);return this},_c.root=function(){return this._root},_c.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},_c.visit=function(e){var t,n,i,r,s=[],a=this._root;for(a&&s.push(new dc(a,this._x0,this._x1));t=s.pop();)if(!e(a=t.node,i=t.x0,r=t.x1)&&a.length){var o=(i+r)/2;(n=a[1])&&s.push(new dc(n,o,r)),(n=a[0])&&s.push(new dc(n,i,o))}return this},_c.visitAfter=function(e){var t,n=[],i=[];for(this._root&&n.push(new dc(this._root,this._x0,this._x1));t=n.pop();){var r=t.node;if(r.length){var s,a=t.x0,o=t.x1,l=(a+o)/2;(s=r[0])&&n.push(new dc(s,a,l)),(s=r[1])&&n.push(new dc(s,l,o))}i.push(t)}for(;t=i.pop();)e(t.node,t.x0,t.x1);return this},_c.x=function(e){return arguments.length?(this._x=e,this):this._x};var wc=Sc.prototype=Tc.prototype;function Ec(e,t,n,i,r){if(isNaN(t)||isNaN(n)||isNaN(i))return e;var s,a,o,l,u,c,h,d,p,f,m,g,_=e._root,v={data:r},y=e._x0,b=e._y0,x=e._z0,S=e._x1,T=e._y1,M=e._z1;if(!_)return e._root=v,e;for(;_.length;)if((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,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;n<s;++n)isNaN(i=+this._x.call(null,t=e[n]))||isNaN(r=+this._y.call(null,t))||(a[n]=i,o[n]=r,i<l&&(l=i),i>c&&(c=i),r<u&&(u=r),r>h&&(h=r));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;n<s;++n)vc(this,a[n],o[n],e[n]);return this},wc.cover=function(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var n=this._x0,i=this._y0,r=this._x1,s=this._y1;if(isNaN(n))r=(n=Math.floor(e))+1,s=(i=Math.floor(t))+1;else{for(var a,o,l=r-n||1,u=this._root;n>e||e>=r||i>t||t>=s;)switch(o=(t<i)<<1|e<n,(a=new Array(4))[o]=u,u=a,l*=2,o){case 0:r=n+l,s=i+l;break;case 1:n=r-l,s=i+l;break;case 2:r=n+l,i=s-l;break;case 3:n=r-l,i=s-l}this._root&&this._root.length&&(this._root=u)}return this._x0=n,this._y0=i,this._x1=r,this._y1=s,this},wc.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},wc.extent=function(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},wc.find=function(e,t,n){var i,r,s,a,o,l,u,c=this._x0,h=this._y0,d=this._x1,p=this._y1,f=[],m=this._root;for(m&&f.push(new yc(m,c,h,d,p)),null==n?n=1/0:(c=e-n,h=t-n,d=e+n,p=t+n,n*=n);l=f.pop();)if(!(!(m=l.node)||(r=l.x0)>d||(s=l.y0)>p||(a=l.x1)<c||(o=l.y1)<h))if(m.length){var g=(r+a)/2,_=(s+o)/2;f.push(new yc(m[3],g,_,a,o),new yc(m[2],r,_,g,o),new yc(m[1],g,s,a,_),new yc(m[0],r,s,g,_)),(u=(t>=_)<<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<n){var x=Math.sqrt(n=b);c=e-x,h=t-x,d=e+x,p=t+x,i=m.data}}return i},wc.remove=function(e){if(isNaN(s=+this._x.call(null,e))||isNaN(a=+this._y.call(null,e)))return this;var t,n,i,r,s,a,o,l,u,c,h,d,p=this._root,f=this._x0,m=this._y0,g=this._x1,_=this._y1;if(!p)return this;if(p.length)for(;;){if((u=s>=(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;t<n;++t)this.remove(e[t]);return this},wc.root=function(){return this._root},wc.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},wc.visit=function(e){var t,n,i,r,s,a,o=[],l=this._root;for(l&&o.push(new yc(l,this._x0,this._y0,this._x1,this._y1));t=o.pop();)if(!e(l=t.node,i=t.x0,r=t.y0,s=t.x1,a=t.y1)&&l.length){var u=(i+s)/2,c=(r+a)/2;(n=l[3])&&o.push(new yc(n,u,c,s,a)),(n=l[2])&&o.push(new yc(n,i,c,u,a)),(n=l[1])&&o.push(new yc(n,u,r,s,c)),(n=l[0])&&o.push(new yc(n,i,r,u,c))}return this},wc.visitAfter=function(e){var t,n=[],i=[];for(this._root&&n.push(new yc(this._root,this._x0,this._y0,this._x1,this._y1));t=n.pop();){var r=t.node;if(r.length){var s,a=t.x0,o=t.y0,l=t.x1,u=t.y1,c=(a+l)/2,h=(o+u)/2;(s=r[0])&&n.push(new yc(s,a,o,c,h)),(s=r[1])&&n.push(new yc(s,c,o,l,h)),(s=r[2])&&n.push(new yc(s,a,h,c,u)),(s=r[3])&&n.push(new yc(s,c,h,l,u))}i.push(t)}for(;t=i.pop();)e(t.node,t.x0,t.y0,t.x1,t.y1);return this},wc.x=function(e){return arguments.length?(this._x=e,this):this._x},wc.y=function(e){return arguments.length?(this._y=e,this):this._y};const Rc=(e,t,n,i,r,s)=>Math.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;s<h;++s)for(var u,c,d,p,f,m=0,g=0,_=0,v=0;m<l;++m)c=(u=e[m]).source,g=(d=u.target).x+d.vx-c.x-c.vx||Oc(o),r>1&&(_=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<c;++r)(o=e[r]).index=r,"object"!=typeof o.source&&(o.source=kc(h,o.source)),"object"!=typeof o.target&&(o.target=kc(h,o.target)),s[o.source.index]=(s[o.source.index]||0)+1,s[o.target.index]=(s[o.target.index]||0)+1;for(r=0,a=new Array(c);r<c;++r)o=e[r],a[r]=s[o.source.index]/(s[o.source.index]+s[o.target.index]);t=new Array(c),f(),n=new Array(c),m()}}function f(){if(i)for(var n=0,r=e.length;n<r;++n)t[n]=+u(e[n],n,e)}function m(){if(i)for(var t=0,r=e.length;t<r;++t)n[t]=+c(e[t],t,e)}return null==e&&(e=[]),d.initialize=function(e,...t){i=e,o=t.find(e=>"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;m<t;++m)isNaN(d=+this._x.call(null,h=e[m]))||isNaN(p=+this._y.call(null,h))||isNaN(f=+this._z.call(null,h))||(n[m]=d,i[m]=p,r[m]=f,d<s&&(s=d),d>l&&(l=d),p<a&&(a=p),p>u&&(u=p),f<o&&(o=f),f>c&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;s<t;++s)Ec(this,n[s],i[s],r[s],e[s]);return this},Uc.cover=function(e,t,n){if(isNaN(e=+e)||isNaN(t=+t)||isNaN(n=+n))return this;var i=this._x0,r=this._y0,s=this._z0,a=this._x1,o=this._y1,l=this._z1;if(isNaN(i))a=(i=Math.floor(e))+1,o=(r=Math.floor(t))+1,l=(s=Math.floor(n))+1;else{for(var u,c,h=a-i||1,d=this._root;i>e||e>=a||r>t||t>=o||s>n||n>=l;)switch(c=(n<s)<<2|(t<r)<<1|e<i,(u=new Array(8))[c]=d,d=u,h*=2,c){case 0:a=i+h,o=r+h,l=s+h;break;case 1:i=a-h,o=r+h,l=s+h;break;case 2:a=i+h,r=o-h,l=s+h;break;case 3:i=a-h,r=o-h,l=s+h;break;case 4:a=i+h,o=r+h,s=l-h;break;case 5:i=a-h,o=r+h,s=l-h;break;case 6:a=i+h,r=o-h,s=l-h;break;case 7:i=a-h,r=o-h,s=l-h}this._root&&this._root.length&&(this._root=d)}return this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this},Uc.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},Uc.extent=function(e){return arguments.length?this.cover(+e[0][0],+e[0][1],+e[0][2]).cover(+e[1][0],+e[1][1],+e[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]},Uc.find=function(e,t,n,i){var r,s,a,o,l,u,c,h,d,p=this._x0,f=this._y0,m=this._z0,g=this._x1,_=this._y1,v=this._z1,y=[],b=this._root;for(b&&y.push(new Ac(b,p,f,m,g,_,v)),null==i?i=1/0:(p=e-i,f=t-i,m=n-i,g=e+i,_=t+i,v=n+i,i*=i);h=y.pop();)if(!(!(b=h.node)||(s=h.x0)>g||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)<p||(u=h.y1)<f||(c=h.z1)<m))if(b.length){var x=(s+l)/2,S=(a+u)/2,T=(o+c)/2;y.push(new Ac(b[7],x,S,T,l,u,c),new Ac(b[6],s,S,T,x,u,c),new Ac(b[5],x,a,T,l,S,c),new Ac(b[4],s,a,T,x,S,c),new Ac(b[3],x,S,o,l,u,T),new Ac(b[2],s,S,o,x,u,T),new Ac(b[1],x,a,o,l,S,T),new Ac(b[0],s,a,o,x,S,T)),(d=(n>=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<i){var R=Math.sqrt(i=A);p=e-R,f=t-R,m=n-R,g=e+R,_=t+R,v=n+R,r=b.data}}return r},Uc.findAllWithinRadius=function(e,t,n,i){const r=[],s=e-i,a=t-i,o=n-i,l=e+i,u=t+i,c=n+i;return this.visit((h,d,p,f,m,g,_)=>{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<s||g<a||_<o}),r},Uc.remove=function(e){if(isNaN(s=+this._x.call(null,e))||isNaN(a=+this._y.call(null,e))||isNaN(o=+this._z.call(null,e)))return this;var t,n,i,r,s,a,o,l,u,c,h,d,p,f,m,g=this._root,_=this._x0,v=this._y0,y=this._z0,b=this._x1,x=this._y1,S=this._z1;if(!g)return this;if(g.length)for(;;){if((h=s>=(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<n;++t)this.remove(e[t]);return this},Uc.root=function(){return this._root},Uc.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},Uc.visit=function(e){var t,n,i,r,s,a,o,l,u=[],c=this._root;for(c&&u.push(new Ac(c,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=u.pop();)if(!e(c=t.node,i=t.x0,r=t.y0,s=t.z0,a=t.x1,o=t.y1,l=t.z1)&&c.length){var h=(i+a)/2,d=(r+o)/2,p=(s+l)/2;(n=c[7])&&u.push(new Ac(n,h,d,p,a,o,l)),(n=c[6])&&u.push(new Ac(n,i,d,p,h,o,l)),(n=c[5])&&u.push(new Ac(n,h,r,p,a,d,l)),(n=c[4])&&u.push(new Ac(n,i,r,p,h,d,l)),(n=c[3])&&u.push(new Ac(n,h,d,s,a,o,p)),(n=c[2])&&u.push(new Ac(n,i,d,s,h,o,p)),(n=c[1])&&u.push(new Ac(n,h,r,s,a,d,p)),(n=c[0])&&u.push(new Ac(n,i,r,s,h,d,p))}return this},Uc.visitAfter=function(e){var t,n=[],i=[];for(this._root&&n.push(new Ac(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=n.pop();){var r=t.node;if(r.length){var s,a=t.x0,o=t.y0,l=t.z0,u=t.x1,c=t.y1,h=t.z1,d=(a+u)/2,p=(o+c)/2,f=(l+h)/2;(s=r[0])&&n.push(new Ac(s,a,o,l,d,p,f)),(s=r[1])&&n.push(new Ac(s,d,o,l,u,p,f)),(s=r[2])&&n.push(new Ac(s,a,p,l,d,c,f)),(s=r[3])&&n.push(new Ac(s,d,p,l,u,c,f)),(s=r[4])&&n.push(new Ac(s,a,o,f,d,p,h)),(s=r[5])&&n.push(new Ac(s,d,o,f,u,p,h)),(s=r[6])&&n.push(new Ac(s,a,p,f,d,c,h)),(s=r[7])&&n.push(new Ac(s,d,p,f,u,c,h))}i.push(t)}for(;t=i.pop();)e(t.node,t.x0,t.y0,t.z0,t.x1,t.y1,t.z1);return this},Uc.x=function(e){return arguments.length?(this._x=e,this):this._x},Uc.y=function(e){return arguments.length?(this._y=e,this):this._y},Uc.z=function(e){return arguments.length?(this._z=e,this):this._z};var Vc={value:()=>{}};function Gc(){for(var e,t=0,n=arguments.length,i={};t<n;++t){if(!(e=arguments[t]+"")||e in i||/[\s.]/.test(e))throw new Error("illegal type: "+e);i[e]=[]}return new Hc(i)}function Hc(e){this._=e}function Wc(e,t){for(var n,i=0,r=e.length;i<r;++i)if((n=e[i]).name===t)return n.value}function jc(e,t,n){for(var i=0,r=e.length;i<r;++i)if(e[i].name===t){e[i]=Vc,e=e.slice(0,i).concat(e.slice(i+1));break}return null!=n&&e.push({name:t,value:n}),e}Hc.prototype=Gc.prototype={constructor:Hc,on:function(e,t){var n,i,r=this._,s=(i=r,(e+"").trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");if(n>=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(;++a<o;)if(n=(e=s[a]).type)r[n]=jc(r[n],e.name,t);else if(null==t)for(n in r)r[n]=jc(r[n],e.name,null);return this}for(;++a<o;)if((n=(e=s[a]).type)&&(n=Wc(r[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Hc(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,i,r=new Array(n),s=0;s<n;++s)r[s]=arguments[s+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(s=0,n=(i=this._[e]).length;s<n;++s)i[s].value.apply(t,r)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var i=this._[e],r=0,s=i.length;r<s;++r)i[r].value.apply(t,n)}};var $c,Xc,qc=0,Yc=0,Kc=0,Zc=0,Qc=0,Jc=0,eh="object"==typeof performance&&performance.now?performance:Date,th="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function nh(){return Qc||(th(ih),Qc=eh.now()+Jc)}function ih(){Qc=0}function rh(){this._call=this._time=this._next=null}function sh(e,t,n){var i=new rh;return i.restart(e,t,n),i}function ah(){Qc=(Zc=eh.now())+Jc,qc=Yc=0;try{!function(){nh(),++qc;for(var e,t=$c;t;)(e=Qc-t._time)>=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),r<s&&(c.stop(),h.call("end",n))}function f(t){var s,c,h=e.length;void 0===t&&(t=1);for(var d=0;d<t;++d)for(r+=(o-r)*a,u.forEach(function(e){e(r)}),s=0;s<h;++s)null==(c=e[s]).fx?c.x+=c.vx*=l:(c.x=c.fx,c.vx=0),i>1&&(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;n<r;++n){if((t=e[n]).index=n,null!=t.fx&&(t.x=t.fx),null!=t.fy&&(t.y=t.fy),null!=t.fz&&(t.z=t.fz),isNaN(t.x)||i>1&&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;p<f;++p)(s=(t=u-(a=e[p]).x)*t+(n=c-(a.y||0))*n+(r=h-(a.z||0))*r)<d&&(o=a,d=s);return o},on:function(e,t){return arguments.length>1?(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;s<a;++s)n=e[s],o.visit(p)}function h(){if(e){var t,n,i=e.length;for(s=new Array(i),t=0;t<i;++t)n=e[t],s[n.index]=+a(n,t,e)}}function d(e){var n,i,r,a,o,l,u=0,c=0,h=e.length;if(h){for(r=a=o=l=0;l<h;++l)(n=e[l])&&(i=Math.abs(n.value))&&(u+=n.value,c+=i,r+=i*(n.x||0),a+=i*(n.y||0),o+=i*(n.z||0));u*=Math.sqrt(4/h),e.x=r/c,t>1&&(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(_*_/u<v)return v<l&&(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),v<o&&(v=Math.sqrt(o*v)),n.vx+=f*e.value*r/v,t>1&&(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),v<o&&(v=Math.sqrt(o*v)));do{e.data!==n&&(_=s[e.data.index]*r/v,n.vx+=f*_,t>1&&(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;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw new Error("Subject cannot be eventified, since it already has property '"+t[n]+"'")}(e);const t=function(e){let t=Object.create(null);return{on:function(n,i,r){if("function"!=typeof i)throw new Error("callback is expected to be a function");let s=t[n];return s||(s=t[n]=[]),s.push({callback:i,ctx:r}),e},off:function(n,i){if(void 0===n)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;t<e.length;++t)e[t].callback===i&&e.splice(t,1)}}return e},fire:function(n){const i=t[n];if(!i)return e;let r;arguments.length>1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e<i.length;++e){const t=i[e];t.callback.apply(t.ctx,r)}return e}}}(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e}function vh(e,t){this.id=e,this.links=null,this.data=t}function yh(e,t){e.links?e.links.add(t):e.links=new Set([t])}function bh(e,t,n,i){this.fromId=e,this.toId=t,this.data=n,this.id=i}function xh(e,t){return e.toString()+"👉 "+t.toString()}function Sh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Th,Mh,wh,Eh,Ah,Rh={exports:{}},Ch={exports:{}};function Nh(){return Mh||(Mh=1,Th=function(e){return 0===e?"x":1===e?"y":2===e?"z":"c"+(e+1)}),Th}function Ph(){if(Eh)return wh;Eh=1;const e=Nh();return wh=function(t){return function(n,i){let r=i&&i.indent||0,s=i&&void 0!==i.join?i.join:"\n",a=Array(r+1).join(" "),o=[];for(let i=0;i<t;++i){let t=e(i),r=0===i?"":a;o.push(r+n.replace(/{var}/g,t))}return o.join(s)}},wh}var Lh,Dh={exports:{}};var Ih,Uh={exports:{}};var Fh,Oh={exports:{}};var Bh,kh={exports:{}};var zh,Vh,Gh,Hh,Wh,jh,$h,Xh={exports:{}};function qh(){if($h)return jh;return $h=1,jh=function(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;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw new Error("Subject cannot be eventified, since it already has property '"+t[n]+"'")}(e);const t=function(e){let t=Object.create(null);return{on:function(n,i,r){if("function"!=typeof i)throw new Error("callback is expected to be a function");let s=t[n];return s||(s=t[n]=[]),s.push({callback:i,ctx:r}),e},off:function(n,i){if(typeof n>"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;t<e.length;++t)e[t].callback===i&&e.splice(t,1)}return e},fire:function(n){const i=t[n];if(!i)return e;let r;arguments.length>1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e<i.length;++e){const t=i[e];t.callback.apply(t.ctx,r)}return e}}}(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e},jh}var Yh,Kh,Zh,Qh,Jh={exports:{}};function ed(){if(Zh)return Kh;Zh=1,Kh=function(l){var u=(Gh||(Gh=1,Vh=function(e,t,n,i){this.from=e,this.to=t,this.length=n,this.coefficient=i}),Vh),c=(Wh||(Wh=1,Hh=function e(t,n){var i;if(t||(t={}),n)for(i in n)if(n.hasOwnProperty(i)){var r=t.hasOwnProperty(i),s=typeof n[i];r&&typeof t[i]===s?"object"===s&&(t[i]=e(t[i],n[i])):t[i]=n[i]}return t}),Hh),h=qh();if(l){if(void 0!==l.springCoeff)throw new Error("springCoeff was renamed to springCoefficient");if(void 0!==l.dragCoeff)throw new Error("dragCoeff was renamed to dragCoefficient")}l=c(l,{springLength:10,springCoefficient:.8,gravity:-12,theta:.8,dragCoefficient:.9,timeStep:.5,adaptiveTimeStepWeight:0,dimensions:2,debug:!1});var d=a[l.dimensions];if(!d){var p=l.dimensions;d={Body:e(p,l.debug),createQuadTree:t(p),createBounds:n(p),createDragForce:i(p),createSpringForce:r(p),integrate:s(p)},a[p]=d}var f=d.Body,m=d.createQuadTree,g=d.createBounds,_=d.createDragForce,v=d.createSpringForce,y=d.integrate,b=function(){if(Yh)return Jh.exports;function e(e){return new t("number"==typeof e?e:+new Date)}function t(e){this.seed=e}function n(e){return Math.sqrt(2*Math.PI/e)*Math.pow(1/Math.E*(e+1/(12*e-1/(10*e))),e)}function i(){var e=this.seed;return e=4294967295&(3042594569^(e=4251993797+(e=4294967295&(3550635116+(e=374761393+(e=4294967295&(3345072700^(e=e+2127912214+(e<<12)&4294967295)^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;e<A.length;++e)A[e](C);var t=y(x,l.timeStep,l.adaptiveTimeStepWeight);return C+=1,t},addBody:function(e){if(!e)throw new Error("Body is required");return x.push(e),e},addBodyAt:function(e){if(!e)throw new Error("Body position is required");var t=(e=>new 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<u;++n)t.push(`${e}quad${n} = null;`);return t.join("\n")}(" node.")}\n node.body = null;\n node.mass = ${l("node.mass_{var} = ",{join:""})}0;\n ${l("node.min_{var} = node.max_{var} = ",{join:""})}0;\n } else {\n node = new QuadNode();\n nodesCache[currentInCache] = node;\n }\n\n ++currentInCache;\n return node;\n }\n\n function update(sourceBody) {\n var queue = updateQueue;\n var v;\n ${l("var d{var};",{indent:4})}\n var r; \n ${l("var f{var} = 0;",{indent:4})}\n var queueLength = 1;\n var shiftIdx = 0;\n var pushIdx = 1;\n\n queue[0] = root;\n\n while (queueLength) {\n var node = queue[shiftIdx];\n var body = node.body;\n\n queueLength -= 1;\n shiftIdx += 1;\n var differentBody = (body !== sourceBody);\n if (body && differentBody) {\n // If the current node is a leaf node (and it is not source body),\n // calculate the force exerted by the current node on body, and add this\n // amount to body's net force.\n ${l("d{var} = body.pos.{var} - sourceBody.pos.{var};",{indent:8})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n // Poor man's protection against zero distance.\n ${l("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n }\n\n // This is standard gravitation force calculation but we divide\n // by r^3 to save two operations when normalizing force vector.\n v = gravity * body.mass * sourceBody.mass / (r * r * r);\n ${l("f{var} += v * d{var};",{indent:8})}\n } else if (differentBody) {\n // Otherwise, calculate the ratio s / r, where s is the width of the region\n // represented by the internal node, and r is the distance between the body\n // and the node's center-of-mass\n ${l("d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};",{indent:8})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n // Sorry about code duplication. I don't want to create many functions\n // right away. Just want to see performance first.\n ${l("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n }\n // If s / r < θ, treat this internal node as a single body, and calculate the\n // force it exerts on sourceBody, and add this amount to sourceBody's net force.\n if ((node.max_${t(0)} - node.min_${t(0)}) / r < theta) {\n // in the if statement above we consider node's width only\n // because the region was made into square during tree creation.\n // Thus there is no difference between using width or height.\n v = gravity * node.mass * sourceBody.mass / (r * r * r);\n ${l("f{var} += v * d{var};",{indent:10})}\n } else {\n // Otherwise, run the procedure recursively on each of the current node's children.\n\n // I intentionally unfolded this loop, to save several CPU cycles.\n${function(){let e=Array(11).join(" "),t=[];for(let n=0;n<u;++n)t.push(e+`if (node.quad${n}) {`),t.push(e+` queue[pushIdx] = node.quad${n};`),t.push(e+" queueLength += 1;"),t.push(e+" pushIdx += 1;"),t.push(e+"}");return t.join("\n")}()}\n }\n }\n }\n\n ${l("sourceBody.force.{var} += f{var};",{indent:4})}\n }\n\n function insertBodies(bodies) {\n ${l("var {var}min = Number.MAX_VALUE;",{indent:4})}\n ${l("var {var}max = Number.MIN_VALUE;",{indent:4})}\n var i = bodies.length;\n\n // To reduce quad tree depth we are looking for exact bounding box of all particles.\n while (i--) {\n var pos = bodies[i].pos;\n ${l("if (pos.{var} < {var}min) {var}min = pos.{var};",{indent:6})}\n ${l("if (pos.{var} > {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<n;++r)e.push(i+`if (${t(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<t;++n){let t=0===n?" ":" else ";e.push(`${t}if (idx === ${n}) node.quad${n} = child;`)}return e.join("\n")}()}\n}`}function s(e){return`function getChild(node, idx) {\n${function(){let t=[],n=Math.pow(2,e);for(let e=0;e<n;++e)t.push(` if (idx === ${e}) return node.quad${e};`);return t.join("\n")}()}\n return null;\n}`}function a(t){let n=e(t),i=Math.pow(2,t);var r=`\nfunction QuadNode() {\n // body stored inside this node. In quad tree only leaf nodes (by construction)\n // contain bodies:\n this.body = null;\n\n // Child nodes are stored in quads. Each quad is presented by number:\n // 0 | 1\n // -----\n // 2 | 3\n${function(e){let t=[];for(let n=0;n<i;++n)t.push(`${e}quad${n} = null;`);return t.join("\n")}(" this.")}\n\n // Total mass of current node\n this.mass = 0;\n\n // Center of mass coordinates\n ${n("this.mass_{var} = 0;",{indent:2})}\n\n // bounding box coordinates\n ${n("this.min_{var} = 0;",{indent:2})}\n ${n("this.max_{var} = 0;",{indent:2})}\n}\n`;return r}function o(){return"\n/**\n * Our implementation of QuadTree is non-recursive to avoid GC hit\n * This data structure represent stack of elements\n * which we are trying to insert into quad tree.\n */\nfunction InsertStack () {\n this.stack = [];\n this.popIdx = 0;\n}\n\nInsertStack.prototype = {\n isEmpty: function() {\n return this.popIdx === 0;\n },\n push: function (node, body) {\n var item = this.stack[this.popIdx];\n if (!item) {\n // we are trying to avoid memory pressure: create new element\n // only when absolutely necessary\n this.stack[this.popIdx] = new InsertStackElement(node, body);\n } else {\n item.node = node;\n item.body = body;\n }\n ++this.popIdx;\n },\n pop: function () {\n if (this.popIdx > 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<e.length;++t){var i=e[t];"add"===i.changeType?(i.node&&m(i.node.id),i.link&&_(i.link)):"remove"===i.changeType&&(i.node&&g(i.node),i.link&&v(i.link))}l=n.getNodesCount()}function m(e){var t=a.get(e);if(!t){var i=n.getNode(e);if(!i)throw new Error("initBody() was called with unknown node id");var s=i.position;if(!s){var o=function(e){var t=[];if(!e.links)return t;for(var n=Math.min(e.links.length,2),i=0;i<n;++i){var r=e.links[i],s=r.fromId!==e.id?a.get(r.fromId):a.get(r.toId);s&&s.pos&&t.push(s)}return t}(i);s=r.getBestNewBodyPosition(o)}(t=r.addBodyAt(s)).id=e,a.set(e,t),y(e),function(e){return e&&(e.isPinned||e.data&&e.data.isPinned)}(i)&&(t.isPinned=!0)}}function g(e){var t=e.id,n=a.get(t);n&&(a.delete(t),r.removeBody(n))}function _(e){y(e.fromId),y(e.toId);var t=a.get(e.fromId),n=a.get(e.toId),i=r.addSpring(t,n,e.length);u(e,i),o[e.id]=i}function v(e){var t=o[e.id];if(t){var i=n.getNode(e.fromId),s=n.getNode(e.toId);i&&y(i.id),s&&y(s.id),delete o[e.id],r.removeSpring(t)}}function y(e){var t=a.get(e);if(t.mass=s(e),Number.isNaN(t.mass))throw new Error("Node mass should be a number")}function b(e){var t=a.get(e);return t||(m(e),t=a.get(e)),t}},Rh.exports.simulator=ed();var e=qh();function t(){}return Rh.exports}(),nd=Sh(td);function id(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var rd="object"==typeof global&&global&&global.Object===Object&&global,sd="object"==typeof self&&self&&self.Object===Object&&self,ad=rd||sd||Function("return this")(),od=function(){return ad.Date.now()},ld=/\s/;var ud=/^\s+/;function cd(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&ld.test(e.charAt(t)););return t}(e)+1).replace(ud,""):e}var hd=ad.Symbol,dd=Object.prototype,pd=dd.hasOwnProperty,fd=dd.toString,md=hd?hd.toStringTag:void 0;var gd=Object.prototype.toString;var _d=hd?hd.toStringTag:void 0;function vd(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":_d&&_d in Object(e)?function(e){var t=pd.call(e,md),n=e[md];try{e[md]=void 0;var i=!0}catch(e){}var r=fd.call(e);return i&&(t?e[md]=n:delete e[md]),r}(e):function(e){return gd.call(e)}(e)}var yd=/^[-+]0x[0-9a-f]+$/i,bd=/^0b[01]+$/i,xd=/^0o[0-7]+$/i,Sd=parseInt;function Td(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==vd(e)}(e))return NaN;if(id(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=id(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=cd(e);var n=bd.test(e);return n||xd.test(e)?Sd(e.slice(2),n?2:8):yd.test(e)?NaN:+e}var Md=Math.max,wd=Math.min;function Ed(e,t,n){var i,r,s,a,o,l,u=0,c=!1,h=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var n=i,s=r;return i=r=void 0,u=t,a=e.apply(s,n)}function f(e){var n=e-l;return void 0===l||n>=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++)i[n]=e[n];return i}function Rd(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function Cd(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ad(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ad(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var Nd=Rd(function e(t,n){var i=n.default,r=void 0===i?null:i,s=n.triggerUpdate,a=void 0===s||s,o=n.onChange,l=void 0===o?function(e,t){}:o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=t,this.defaultVal=r,this.triggerUpdate=a,this.onChange=l});function Pd(e){var t=e.stateInit,n=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,s=e.methods,a=void 0===s?{}:s,o=e.aliases,l=void 0===o?{}:o,u=e.init,c=void 0===u?function(){}:u,h=e.update,d=void 0===h?function(){}:h,p=Object.keys(r).map(function(e){return new Nd(e,r[e])});return function e(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var s=!!(this instanceof e?this.constructor:void 0),o=s?i.shift():void 0,u=i[0],h=void 0===u?{}:u,f=Object.assign({},n instanceof Function?n(h):n,{initialised:!1}),m={};function g(e){return _(e,h),v(),g}var _=function(e,t){c.call(g,e,f,t),f.initialised=!0},v=Ed(function(){f.initialised&&(d.call(g,f,m),m={})},1);return p.forEach(function(e){g[e.name]=function(e){var t=e.name,n=e.triggerUpdate,i=void 0!==n&&n,r=e.onChange,s=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var n=f[t];if(!arguments.length)return n;var r=void 0===e?o:e;return f[t]=r,s.call(g,r,f,n),!m.hasOwnProperty(t)&&(m[t]=n),i&&v(),g}}(e)}),Object.keys(a).forEach(function(e){g[e]=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];return(t=a[e]).call.apply(t,[g,f].concat(i))}}),Object.entries(l).forEach(function(e){var t=Cd(e,2),n=t[0],i=t[1];return g[n]=g[i]}),g.resetProps=function(){return p.forEach(function(e){g[e.name](e.defaultVal)}),g},g.resetProps(),f._rerender=v,s&&o&&g(o),g}}var Ld=function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}};class Dd extends Map{constructor(e,t=Ud){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const[t,n]of e)this.set(t,n)}get(e){return super.get(Id(this,e))}has(e){return super.has(Id(this,e))}set(e,t){return super.set(function({_intern:e,_key:t},n){const i=t(n);return e.has(i)?e.get(i):(e.set(i,n),n)}(this,e),t)}delete(e){return super.delete(function({_intern:e,_key:t},n){const i=t(n);e.has(i)&&(n=e.get(i),e.delete(i));return n}(this,e))}}function Id({_intern:e,_key:t},n){const i=t(n);return e.has(i)?e.get(i):n}function Ud(e){return null!==e&&"object"==typeof e?e.valueOf():e}function Fd(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 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);n<t;n++)i[n]=e[n];return i}function kd(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function zd(e,t){return e.get(kd(e,t))}function Vd(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function Gd(e,t,n){return e.set(kd(e,t),n),n}function Hd(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,$d(i.key),i)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Wd(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||Xd(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function jd(e){return function(e){if(Array.isArray(e))return Bd(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Xd(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function $d(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function Xd(e,t){if(e){if("string"==typeof e)return Bd(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Bd(e,t):void 0}}var qd=new WeakMap,Yd=new WeakMap,Kd=new WeakMap,Zd=new WeakMap,Qd=new WeakMap,Jd=new WeakMap,ep=function(){return Hd(function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Vd(this,qd,new Map),Vd(this,Yd,new Map),Vd(this,Kd,function(e){return e}),Vd(this,Zd,function(){return{}}),Vd(this,Qd,function(){}),Vd(this,Jd,function(){})},[{key:"getObj",value:function(e){return zd(qd,this).get(zd(Kd,this).call(this,e))}},{key:"getData",value:function(e){return zd(Yd,this).get(e)}},{key:"entries",value:function(){return jd(zd(Yd,this).entries()).map(function(e){var t=Wd(e,2),n=t[0];return[t[1],n]})}},{key:"id",value:function(e){return Gd(Kd,this,Ld(e)),this}},{key:"onCreateObj",value:function(e){return Gd(Zd,this,e),this}},{key:"onUpdateObj",value:function(e){return Gd(Qd,this,e),this}},{key:"onRemoveObj",value:function(e){return Gd(Jd,this,e),this}},{key:"digest",value:function(e){var t=this;e.filter(function(e){return!zd(qd,t).has(zd(Kd,t).call(t,e))}).forEach(function(e){var n=zd(Zd,t).call(t,e);zd(qd,t).set(zd(Kd,t).call(t,e),n),zd(Yd,t).set(n,e)});var n=new Map(e.map(function(e){return[zd(Kd,t).call(t,e),e]}));return zd(qd,this).forEach(function(e,i){n.has(i)?zd(Qd,t).call(t,e,n.get(i)):(zd(Jd,t).call(t,e,i),zd(qd,t).delete(i),zd(Yd,t).delete(e))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])}();function tp(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}const np=Symbol("implicit");var ip=function(e){for(var t=e.length/6|0,n=new Array(t),i=0;i<t;)n[i]="#"+e.slice(6*i,6*++i);return n}("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function rp(e){return rp="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rp(e)}var sp=/^\s+/,ap=/\s+$/;function op(e,t){if(t=t||{},(e=e||"")instanceof op)return e;if(!(this instanceof op))return new op(e,t);var n=function(e){var t={r:0,g:0,b:0},n=1,i=null,r=null,s=null,a=!1,o=!1;"string"==typeof e&&(e=function(e){e=e.replace(sp,"").replace(ap,"").toLowerCase();var t,n=!1;if(Mp[e])e=Mp[e],n=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(t=Op.rgb.exec(e))return{r:t[1],g:t[2],b:t[3]};if(t=Op.rgba.exec(e))return{r:t[1],g:t[2],b:t[3],a:t[4]};if(t=Op.hsl.exec(e))return{h:t[1],s:t[2],l:t[3]};if(t=Op.hsla.exec(e))return{h:t[1],s:t[2],l:t[3],a:t[4]};if(t=Op.hsv.exec(e))return{h:t[1],s:t[2],v:t[3]};if(t=Op.hsva.exec(e))return{h:t[1],s:t[2],v:t[3],a:t[4]};if(t=Op.hex8.exec(e))return{r:Cp(t[1]),g:Cp(t[2]),b:Cp(t[3]),a:Dp(t[4]),format:n?"name":"hex8"};if(t=Op.hex6.exec(e))return{r:Cp(t[1]),g:Cp(t[2]),b:Cp(t[3]),format:n?"name":"hex"};if(t=Op.hex4.exec(e))return{r:Cp(t[1]+""+t[1]),g:Cp(t[2]+""+t[2]),b:Cp(t[3]+""+t[3]),a:Dp(t[4]+""+t[4]),format:n?"name":"hex8"};if(t=Op.hex3.exec(e))return{r:Cp(t[1]+""+t[1]),g:Cp(t[2]+""+t[2]),b:Cp(t[3]+""+t[3]),format:n?"name":"hex"};return!1}(e));"object"==rp(e)&&(Bp(e.r)&&Bp(e.g)&&Bp(e.b)?(t=function(e,t,n){return{r:255*Ap(e,255),g:255*Ap(t,255),b:255*Ap(n,255)}}(e.r,e.g,e.b),a=!0,o="%"===String(e.r).substr(-1)?"prgb":"rgb"):Bp(e.h)&&Bp(e.s)&&Bp(e.v)?(i=Pp(e.s),r=Pp(e.v),t=function(e,t,n){e=6*Ap(e,360),t=Ap(t,100),n=Ap(n,100);var i=Math.floor(e),r=e-i,s=n*(1-t),a=n*(1-r*t),o=n*(1-(1-r)*t),l=i%6,u=[n,a,s,s,o,n][l],c=[o,n,n,a,s,s][l],h=[s,s,o,n,n,a][l];return{r:255*u,g:255*c,b:255*h}}(e.h,i,r),a=!0,o="hsv"):Bp(e.h)&&Bp(e.s)&&Bp(e.l)&&(i=Pp(e.s),s=Pp(e.l),t=function(e,t,n){var i,r,s;function a(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+(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<n?6:0);break;case t:i=(n-e)/l+2;break;case n:i=(e-t)/l+4}i/=6}return{h:i,s:r,l:o}}function up(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,l=s-a;if(r=0===s?0:l/s,s==a)i=0;else{switch(s){case e:i=(t-n)/l+(t<n?6:0);break;case t:i=(n-e)/l+2;break;case n:i=(e-t)/l+4}i/=6}return{h:i,s:r,v:o}}function cp(e,t,n,i){var r=[Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16))];return i&&r[0].charAt(0)==r[0].charAt(1)&&r[1].charAt(0)==r[1].charAt(1)&&r[2].charAt(0)==r[2].charAt(1)?r[0].charAt(0)+r[1].charAt(0)+r[2].charAt(0):r.join("")}function hp(e,t,n,i){return[Np(Lp(i)),Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16))].join("")}function dp(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.s-=t/100,n.s=Rp(n.s),op(n)}function pp(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.s+=t/100,n.s=Rp(n.s),op(n)}function fp(e){return op(e).desaturate(100)}function mp(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.l+=t/100,n.l=Rp(n.l),op(n)}function gp(e,t){t=0===t?0:t||10;var n=op(e).toRgb();return n.r=Math.max(0,Math.min(255,n.r-Math.round(-t/100*255))),n.g=Math.max(0,Math.min(255,n.g-Math.round(-t/100*255))),n.b=Math.max(0,Math.min(255,n.b-Math.round(-t/100*255))),op(n)}function _p(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.l-=t/100,n.l=Rp(n.l),op(n)}function vp(e,t){var n=op(e).toHsl(),i=(n.h+t)%360;return n.h=i<0?360+i:i,op(n)}function yp(e){var t=op(e).toHsl();return t.h=(t.h+180)%360,op(t)}function bp(e,t){if(isNaN(t)||t<=0)throw new Error("Argument to polyad must be a positive number");for(var n=op(e).toHsl(),i=[op(e)],r=360/t,s=1;s<t;s++)i.push(op({h:(n.h+s*r)%360,s:n.s,l:n.l}));return i}function xp(e){var t=op(e).toHsl(),n=t.h;return[op(e),op({h:(n+72)%360,s:t.s,l:t.l}),op({h:(n+216)%360,s:t.s,l:t.l})]}function Sp(e,t,n){t=t||6,n=n||30;var i=op(e).toHsl(),r=360/n,s=[op(e)];for(i.h=(i.h-(r*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})},
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
op.readability=function(e,t){var n=op(e),i=op(t);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},op.isReadable=function(e,t,n){var i,r,s=op.readability(e,t);switch(r=!1,(i=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+i.size){case"AAsmall":case"AAAlarge":r=s>=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;u<t.length;u++)(i=op.readability(e,t[u]))>l&&(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;e<i;e++)ss.fromBufferAttribute(t,e-1),as.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=ss.distanceTo(as);e.setAttribute("lineDistance",new lr(n,1))}else qt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const n=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),us.copy(n.boundingSphere),us.applyMatrix4(i),us.radius+=r,!1===e.ray.intersectsSphere(us))return;os.copy(i).invert(),ls.copy(e.ray).applyMatrix4(os);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,u=n.index,c=n.attributes.position;if(null!==u){const n=Math.max(0,s.start),i=Math.min(u.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=u.getX(r),i=u.getX(r+1),s=ds(this,e,ls,o,n,i,r);s&&t.push(s)}if(this.isLineLoop){const r=u.getX(i-1),s=u.getX(n),a=ds(this,e,ls,o,r,s,i-1);a&&t.push(a)}}else{const n=Math.max(0,s.start),i=Math.min(c.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=ds(this,e,ls,o,r,r+1,r);n&&t.push(n)}if(this.isLineLoop){const r=ds(this,e,ls,o,i-1,n,i-1);r&&t.push(r)}}}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<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}},LineBasicMaterial:rs,QuadraticBezierCurve3:Is,CubicBezierCurve3:Ds,Box3:Fi},qp={graph:function(e){if("uniqueLinkId"in(e=e||{})&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n","\n","Note: there is also change in default behavior: From now on each graph\nis considered to be not a multigraph by default (each edge is unique)."),e.multigraph=e.uniqueLinkId),void 0===e.multigraph&&(e.multigraph=!1),"function"!=typeof Map)throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var t,n=new Map,i=new Map,r={},s=0,a=e.multigraph?function(e,t,n){var i=xh(e,t),s=r.hasOwnProperty(i);if(s||x(e,t)){s||(r[i]=0);var a="@"+ ++r[i];i=xh(e+a,t+a)}return new bh(e,t,n,i)}:function(e,t,n){var r=xh(e,t),s=i.get(r);if(s)return s.data=n,s;return new bh(e,t,n,r)},o=[],l=S,u=S,c=S,h=S,d={version:20,addNode:m,addLink:function(e,t,n){c();var r=g(e)||m(e),s=g(t)||m(t),o=a(e,t,n),u=i.has(o.id);i.set(o.id,o),yh(r,o),e!==t&&yh(s,o);return l(o,u?"update":"add"),h(),o},removeLink:function(e,t){void 0!==t&&(e=x(e,t));return b(e)},removeNode:_,getNode:g,getNodeCount:v,getLinkCount:y,getEdgeCount:y,getLinksCount:y,getNodesCount:v,getLinks:function(e){var t=g(e);return t?t.links:null},forEachNode:w,forEachLinkedNode:function(e,t,i){var r=g(e);if(r&&r.links&&"function"==typeof t)return i?function(e,t,i){var r=e.values(),s=r.next();for(;!s.done;){var a=s.value;if(a.fromId===t&&i(n.get(a.toId),a))return!0;s=r.next()}}(r.links,e,t):function(e,t,i){var r=e.values(),s=r.next();for(;!s.done;){var a=s.value,o=a.fromId===t?a.toId:a.fromId;if(i(n.get(o),a))return!0;s=r.next()}}(r.links,e,t)},forEachLink:function(e){if("function"==typeof e)for(var t=i.values(),n=t.next();!n.done;){if(e(n.value))return!0;n=t.next()}},beginUpdate:c,endUpdate:h,clear:function(){c(),w(function(e){_(e.id)}),h()},hasLink:x,hasNode:g,getLink:x,getLinkById:function(e){return void 0===e?void 0:i.get(e)}};return _h(d),t=d.on,d.on=function(){return d.beginUpdate=c=T,d.endUpdate=h=M,l=p,u=f,d.on=t,t.apply(d,arguments)},d;function p(e,t){o.push({link:e,changeType:t})}function f(e,t){o.push({node:e,changeType:t})}function m(e,t){if(void 0===e)throw new Error("Invalid node identifier");c();var i=g(e);return i?(i.data=t,u(i,"update")):(i=new vh(e,t),u(i,"add")),n.set(e,i),h(),i}function g(e){return n.get(e)}function _(e){var t=g(e);if(!t)return!1;c();var i=t.links;return i&&(i.forEach(b),t.links=null),n.delete(e),u(t,"remove"),h(),!0}function v(){return n.size}function y(){return i.size}function b(e){if(!e)return!1;if(!i.get(e.id))return!1;c(),i.delete(e.id);var t=g(e.fromId),n=g(e.toId);return t&&t.links.delete(e),n&&n.links.delete(e),l(e,"remove"),h(),!0}function x(e,t){if(void 0!==e&&void 0!==t)return i.get(xh(e,t))}function S(){}function T(){s+=1}function M(){0===(s-=1)&&o.length>0&&(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()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[t?"tick":"step"](),e.onEngineTick());const n=Ld(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(([i,r])=>{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;o<l;o++){const l=t[o];if(-1!==i.indexOf(l)){const e=[...i.slice(i.indexOf(l)),l].map(e=>n(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;l<u;++l){var c=r[l],h=c.x-t||1e-6,d=(c.y||0)-n||1e-6,p=(c.z||0)-i||1e-6,f=Math.sqrt(h*h+d*d+p*p),m=(o[l]-f)*a[l]*e/f;c.vx+=h*m,s>1&&(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<n;++t)o[t]=+e(r[t],t,r),a[t]=isNaN(o[t])?0:+l(r[t],t,r)}}return"function"!=typeof e&&(e=Fc(+e)),null==t&&(t=0),null==n&&(n=0),null==i&&(i=0),u.initialize=function(e,...t){r=e,s=t.find(e=>[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;t<e.warmupTicks&&!(n&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);t++)i[n?"tick":"step"]();e.layout=i,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});var Qp=function(e,t=Object,n=!1){class i extends t{constructor(...t){super(...t),this.__kapsuleInstance=new e(...[...n?[this]:[],...t])}}return Object.keys(e()).forEach(e=>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<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==i.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=i.morphTargetInfluences[t],e=!0);if(e)return!1}if(!0===i.isInstancedMesh){const e=null!==i.instanceColor?i.instanceColor.version:null,t=null!==i.morphTexture?i.morphTexture.version:null;if(a.instanceMatrixVersion!==i.instanceMatrix.version||a.instanceColorVersion!==e||a.morphTextureVersion!==t)return a.instanceMatrixVersion=i.instanceMatrix.version,a.instanceColorVersion=e,a.morphTextureVersion=t,!1}if(!0===i.isBatchedMesh){const e=null!==i._colorsTexture?i._colorsTexture.version:null;if(a.matricesTextureVersion!==i._matricesTexture.version||a.colorsTextureVersion!==e||a.indirectTextureVersion!==i._indirectTexture.version)return a.matricesTextureVersion=i._matricesTexture.version,a.colorsTextureVersion=e,a.indirectTextureVersion=i._indirectTexture.version,!1}if(a.lights)for(let e=0;e<t.length;e++){const n=a.lights[e],i=t[e];if(n.map!==i.map||n.cacheVersion!==i.cacheVersion||n.shadowMapWidth!==i.shadowMapWidth||n.shadowMapHeight!==i.shadowMapHeight)return n.map=i.map,n.cacheVersion=i.cacheVersion,n.shadowMapWidth=i.shadowMapWidth,n.shadowMapHeight=i.shadowMapHeight,!1}const h=e.scene;return null===h.environment||null!==r.envMap||a.environmentIntensity===h.environmentIntensity&&!1!==a.environmentRotation.equals(h.environmentRotation)?a.center&&!1===a.center.equals(i.center)?(a.center.copy(i.center),!1):(null!==e.bundle&&(a.version=e.bundle.version),!0):(a.environmentIntensity=h.environmentIntensity,a.environmentRotation.copy(h.environmentRotation),!1)}getLightsData(e,t){t.length=0;for(const n of e){let e=null;!0===n.isSpotLight&&null!==n.map&&(e={map:n.map.version,cacheVersion:this.getTextureData(n.map)._version}),!0===n.castShadow&&void 0!==n.shadow&&(null===e&&(e={}),e.shadowMapWidth=n.shadow.mapSize.width,e.shadowMapHeight=n.shadow.mapSize.height),null!==e&&t.push(e)}return t}getLights(e,t){let n=ef.get(e);return void 0===n&&(n={renderId:-1,lightsData:[]},ef.set(e,n)),n.renderId===t||(n.renderId=t,this.getLightsData(e.getBuiltinLights(),n.lightsData)),n.lightsData}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.hasDynamicInstancing(e.object)||this.firstInitialization(e)||this.needsVelocity(t.renderer))return Vt;const{renderId:n}=t;let i=kt;this.renderId!==n&&(this.renderId=n,i=zt);const r=!0===e.object.static,s=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(r||s)return i;const a=this.getLights(e.lightsNode,n);return!1===this.equals(e,a,n)&&(i=Vt),i}}const af=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class of{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const 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<e.length;r++)t=e[r],n=Math.imul(n^t,2654435761),i=Math.imul(i^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),n=Math.imul(n^t,2654435761),i=Math.imul(i^t,1597334677);return n=Math.imul(n^n>>>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;e<i.length;e++){const r=i[e];r&&!0===r.isNode&&t.push({property:n,index:e,childNode:r})}else if(i&&!0===i.isNode)t.push({property:n,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const e in i){if(!0===e.startsWith("_"))continue;const r=i[e];r&&!0===r.isNode&&t.push({property:n,index:e,childNode:r})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const n=[];for(const{property:i,childNode:r}of this._getChildren(t))n.push(uf(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=hf(cf(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const n=e.getDataFromNode(this);let i;return null!==t?(n.typeFromOutput=n.typeFromOutput||{},i=n.typeFromOutput[t],void 0===i&&(i=this.generateNodeType(e,t),n.typeFromOutput[t]=i)):(i=n.type,void 0===i&&(i=this.generateNodeType(e),n.type=i)),i}generateNodeType(e,t=null){const n=e.getNodeProperties(this);return n.outputNode?n.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e),n=e.getNodeFromHash(t);let i=null;if(n&&n!==this)i=n;else if(e.context.overrideNodes){const t=e.context.overrideNodes.get(this);if(t){const n=e.getDataFromNode(this);!0!==n.isOverwritten?(n.isOverwritten=!0,i=t(e).overrideNode(this,null),n.sharedNode=i):i=n.sharedNode}}return i||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let n=0;for(const e of this.getChildren())t["node"+n++]=e;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(!0===this.parents){const n=e.getDataFromNode(this,"any");n.stages=n.stages||{},n.stages[e.shaderStage]=n.stages[e.shaderStage]||[],n.stages[e.shaderStage].push(t)}if(1===n){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){qt("Abstract function.")}updateAfter(){qt("Abstract function.")}update(){qt("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);if(null!==this._beforeNodes){const n=this._beforeNodes;this._beforeNodes=null;for(const i of n)i.build(e,t);this._beforeNodes=n}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const r=Pf[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let s=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const n of Object.values(t))if(n&&!0===n.isNode){if(!0===n.parents){const t=e.getNodeProperties(n);t.parents=t.parents||[],t.parents.push(this)}n.build(e)}e.addSequentialNode(this)}s=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(this.generate.length<2){const n=this.getNodeType(e),i=e.getDataFromNode(this);s=i.snippet,void 0===s?void 0===i.generated?(i.generated=!0,s=this.generate(e)||"",i.snippet=s):(qt("Node: Recursion detected.",this),s="/* Recursion detected. */"):void 0!==i.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),s=e.format(s,n,t)}else s=this.generate(e,t)||"";""===s&&null!==t&&"void"!==t&&"OutputType"!==t&&(Yt(`TSL: Invalid generated code, expected a "${t}".`),s=e.generateConst(t))}return e.removeChain(this),s}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:r,childNode:s}of t)void 0!==r?(void 0===n[i]&&(n[i]=Number.isInteger(r)?[]:{}),n[i][r]=s.toJSON(e.meta).uuid):n[i]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(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<u;e++){const t=Nf[e];t===n[0]?(c.push(o),e+=n.length-1):c.push(l+"."+t)}return`${e.getType(r)}( ${c.join(", ")} )`}}class Vf extends Ff{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,i=this.getNodeType(e),r=n.build(e),s=e.getVarFromNode(this),a=e.getPropertyName(s);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(i),l=[];let u=0;for(let e=0;e<o;e++){const n=Nf[e];n===t[u]?(l.push("1.0 - "+a+"."+n),u++):l.push(a+"."+n)}return`${e.getType(i)}( ${l.join(", ")} )`}}class Gf extends Df{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return null===this.nodeType?mf(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=mf(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e]);return btoa(t)}(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?_f(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){qt("Abstract function.")}}const Hf=/float|u?int/;class Wf extends Gf{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const n=this.getNodeType(e);return Hf.test(n)&&Hf.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class jf extends Df{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}generateNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){qt(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let $f=null;const Xf=new Map;function qf(e,t){if(Xf.has(e))qt(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Xf.set(e,t),"assign"!==e&&(Df.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Df.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Yf=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;i<n;i++)e[i]=xm(e[i],t);return e},im=function(e,t=null,n=null,i=null){function r(e){return null!==i?(e=xm(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=xm(e),e}let s,a,o,l=t;function u(t){let n;return n=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(Yt(`TSL: "${n}" parameter length is less than minimum required.`,new of),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(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<i.length;n++){const i=t[n];i&&i.isNode&&i.build(e)}}else{const t=n[0];for(const n of i){const i=t[n.name];i&&i.isNode&&i.build(e)}}}const i=e.buildFunctionNode(t);e.addInclude(i);const r=n?function(e){let t;Tm(e),t=yf(e)?[...e]:e[0];return t}(n):null;l=i.call(r)}else{const i=new Proxy(e,{get:(e,t,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<l.components.length;t++){const n=l.components[t];e.addLineFlowCode(`${u}.${n} = ${r}[ ${t} ]`,this)}"void"!==t&&(c=s)}else c=`${s} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(c,this),"void"!==t&&(c=s));return u.initialized=!0,e.format(c,a,t)}}qf("assign",wm(Hg).setParameterLength(2));class Wg extends Ff{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],n=this.functionNode,i=n.getInputs(e),r=this.parameters,s=(t,n)=>{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<i.length)for(Yt("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(Um(0));for(let e=0;e<r.length;e++)t.push(s(r[e],i[e]))}else for(const e of i){const n=r[e.name];void 0!==n?t.push(s(n,e)):(Yt(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(s(Um(0),e)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}qf("call",(e,...t)=>(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<i.length-1;t++)r=new $g(e,r,i[t]);t=r,n=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(jg[this.op],t)}generateNodeType(e,t=null){const n=this.op,i=this.aNode,r=this.bNode,s=i.getNodeType(e),a=r?r.getNodeType(e):null;if("void"===s||"void"===a)return t||"void";if("%"===n)return s;if("~"===n||"&"===n||"|"===n||"^"===n||">>"===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;t<arguments.length-1;t++)r=new v_(e,r,arguments[t]);t=r,n=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>s&&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;e<t.length;e++)n=n[t[e]];return n}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class Wv extends Hv{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(Og)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const jv=(e,t,n=null)=>new 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<t.length;e++){const n=t[e];("number"!=typeof n||n<=0||!Number.isInteger(n))&&Yt(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new of)}for(;t.length<3;)t.push(1);return new sy(xm(e),t)};qf("compute",(e,t,n)=>{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;n<e.length;n++){t[4*n]=e[n]}else if("color"===n)for(let n=0;n<e.length;n++){const i=4*n,r=e[n];t[i]=r.r,t[i+1]=r.g,t[i+2]=r.b||0}else if("mat2"===n)for(let n=0;n<e.length;n++){const i=4*n,r=e[n];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+3]=r.elements[3]}else if("mat3"===n)for(let n=0;n<e.length;n++){const i=16*n,r=e[n];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+4]=r.elements[3],t[i+5]=r.elements[4],t[i+6]=r.elements[5],t[i+8]=r.elements[6],t[i+9]=r.elements[7],t[i+10]=r.elements[8],t[i+15]=1}else if("mat4"===n)for(let n=0;n<e.length;n++){const i=16*n,r=e[n];for(let e=0;e<r.elements.length;e++)t[i+e]=r.elements[e]}else for(let n=0;n<e.length;n++){const i=4*n,r=e[n];t[i]=r.x,t[i+1]=r.y,t[i+2]=r.z||0,t[i+3]=r.w||0}}setup(e){const t=this.array.length,n=this.elementType;let i=Float32Array;const r=this.paddedType,s=e.getTypeLength(r);return"i"===n.charAt(0)&&(i=Int32Array),"u"===n.charAt(0)&&(i=Uint32Array),this.value=new i(t*s),this.bufferCount=t,this.bufferType=r,this.updateBuffer(),super.setup(e)}element(e){return new Uy(this,xm(e))}}const Oy=(e,t)=>new 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<i;t++)n.push(new fn);null===rb?rb=Oy(n).setGroup(Og).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const n=e.cameras,i=t.array;for(let e=0,t=n.length;e<t;e++)i[e].setFromMatrixPosition(n[e].matrixWorld)}):rb.array=n,t=rb.element(e.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else null===ib&&(ib=zg(new fn).setName("cameraPosition").setGroup(Og).onRenderUpdate(({camera:e},t)=>t.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<t.cameras.length;n++)e.push(new Bn);const i=Oy(e).onObjectUpdate(({object:e,camera:t},n)=>{const i=t.cameras,r=n.array;for(let t=0,n=i.length;t<n;t++)r[t].multiplyMatrices(i[t].matrixWorldInverse,e.matrixWorld)});n=i.element(t.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else n=zg("mat4").onObjectUpdate(({object:e,camera:t})=>e.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<n.cameras.length;t++)e.push(new _n);const t=Oy(e).onObjectUpdate(({object:e,camera:t},n)=>{const i=t.cameras,r=n.array;for(let t=0,n=i.length;t<n;t++)vb.multiplyMatrices(i[t].matrixWorldInverse,e.matrixWorld),r[t].getNormalMatrix(vb)});i=t.element(n.isMultiViewCamera?ky("gl_ViewID_OVR"):ob)}else i=zg("mat3").onObjectUpdate(({object:e,camera:n})=>(!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;e<t.length;e++)n=n[t[e]];return n}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const ax=(e,t,n)=>new 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;e<t;e++){const t=i[e],r=!0!==t.isNode&&t.name||this.getVarName(e),s=!0!==t.isNode&&t.type||"int";n[r]=dy(r,s)}const r=e.addStack(),s=i[i.length-1](n);t.returnsNode=s.context({nodeLoop:s}),t.stackNode=r;const a=i[0];if(!0!==a.isNode&&"function"==typeof a.update){const e=Nm(a.update)(n);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}_getInternalParams(){const e=this.params;return"function"==typeof e[0]?[Bm(!0),e[0]]:e}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),n=this._getInternalParams(),i=t.stackNode;for(let i=0,r=n.length-1;i<r;i++){const r=n[i];let s,a=!1,o=null,l=null,u=null,c=null,h=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,c="bool",l=r.build(e,c)):(c="int",u=this.getVarName(i),o="0",l=r.build(e,c),h="<"):(c=r.type||"int",u=r.name||this.getVarName(i),o=r.start,l=r.end,h=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(c,o):o&&o.isNode&&(o=o.build(e,c)),"number"==typeof l?l=e.generateConst(c,l):l&&l.isNode&&(l=l.build(e,c)),void 0!==o&&void 0===l?(o+=" - 1",l="0",h=">="):void 0!==l&&void 0===o&&(o="0",h="<"),void 0===h&&(h=Number(o)>Number(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;t<i;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const JS=(...e)=>new 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<s;v++){const y=o[v],b=l[v],x=u[v],S=h*d*4*v;for(let T=0;T<y.count;T++){const M=T*g;!0===t&&(tT.fromBufferAttribute(y,T),f[S+M+0]=tT.x,f[S+M+1]=tT.y,f[S+M+2]=tT.z,f[S+M+3]=0),!0===n&&(tT.fromBufferAttribute(b,T),f[S+M+4]=tT.x,f[S+M+5]=tT.y,f[S+M+6]=tT.z,f[S+M+7]=0),!0===i&&(tT.fromBufferAttribute(x,T),f[S+M+8]=tT.x,f[S+M+9]=tT.y,f[S+M+10]=tT.z,f[S+M+11]=4===x.itemSize?tT.w:1)}}function _(){m.dispose(),eT.delete(e),e.removeEventListener("dispose",_)}a={count:s,texture:m,stride:c,size:new dn(h,d)},eT.set(e,a),e.addEventListener("dispose",_)}return a}(t);!0===n&&Rb.mulAssign(o),!0===i&&Bb.mulAssign(o);const d=Fm(h.width);JS(s,({i:t})=>{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;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Cw,Nw,Pw),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Cw=this._renderer.getRenderTarget(),Nw=this._renderer.getActiveCubeFace(),Pw=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget(!1);return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(e){return Bw(3*Math.max(this._cubeSize,112),4*this._cubeSize,e)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Bw(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=function(e){const t=[],n=[];let i=e;const r=e-4+1+6;for(let e=0;e<r;e++){const e=Math.pow(2,i);t.push(e);const r=1/(e-2),s=-r,a=1+r,o=[s,s,a,s,a,a,s,s,a,a,s,a],l=6,u=6,c=3,h=new Float32Array(c*u*l),d=new Float32Array(c*u*l);for(let e=0;e<l;e++){const t=e%3*2/3-1,n=e>2?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;e<u;e++){const t=2*o[2*e]-1,n=2*o[2*e+1]-1;0===r?Dw.set(1,n,t):1===r?Dw.set(-t,1,-n):2===r?Dw.set(-t,n,1):3===r?Dw.set(-1,n,-t):4===r?Dw.set(-t,-1,n):Dw.set(t,n,-1),Dw.toArray(d,(r*u+e)*c)}}const p=new br;p.setAttribute("position",new rr(h,c)),p.setAttribute("outputDirection",new rr(d,c)),n.push(new qr(p,null)),i>4&&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;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,a=this._lodMeshes[n];a.material=s;const o=Iw.get(s),l=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),c=Math.sqrt(l*l-u*u)*(1.25*l),{_lodMax:h}=this,d=this._sizeLods[n],p=3*d*(n>h-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;i<n;i++)void 0!==e[i]&&t++;return t===n}(t))return null;r=n.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(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<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let n=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const i=e[t];!1===n.has(i)&&n.set(i,new WeakMap),n=n.get(i)}return n.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return!1;return t.delete(e[e.length-1])}}let xE=0;const SE=new WeakMap;class TE{constructor(e,t,n,i,r,s,a,o,l,u){this.id=xE++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=i,this.material=r,this.scene=s,this.camera=a,this.lightsNode=o,this.context=l,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=u,this.clippingContextCacheKey=null!==u?u.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this._sourceMaterial=n._currentSourceMaterial,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{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;e<n;e++){t+=i[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:n}=this;let i=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let n=SE.get(e.constructor);if(void 0===n){n=[];let t=Object.getPrototypeOf(e);for(;t;){const e=Object.getOwnPropertyDescriptors(t);for(const t in e){const i=e[t];i&&"function"==typeof i.get&&n.push(t)}t=Object.getPrototypeOf(t)}SE.set(e.constructor,n)}for(let e=0;e<n.length;e++)t.push(n[e]);return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let s;if(null!==r){const t=typeof r;"number"===t?s="side"===e?String(r):0!==r?"1":"0":"object"===t?(s="{",r.isTexture&&(s+=r.mapping,!0===n.backend.isWebGPUBackend&&(s+=r.magFilter,s+=r.minFilter,s+=r.wrapS,s+=r.wrapT,s+=r.wrapR)),s+="}"):s=String(r)}else s=String(r);i+=s+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1)&&(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<t.version||t.usage===Lt)&&(this.backend.updateAttribute(e),n.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function DE(e){return null!==e.index?e.index.version:e.attributes.position.version}function IE(e){return null!==e.index?e.index.id:e.attributes.position.id}function UE(e){const t=[],n=e.index,i=e.attributes.position;if(null!==n){const e=n.array;for(let n=0,i=e.length;n<i;n+=3){const i=e[n+0],r=e[n+1],s=e[n+2];t.push(i,r,r,s,s,i)}}else{for(let e=0,n=i.array.length/3-1;e<n;e+=3){const n=e+0,i=e+1,r=e+2;t.push(n,i,i,r,r,n)}}const r=new(i.count>=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<l.length;t++){const n=l[t];if(n.data)e+=n.data.byteLength;else{e+=(n.width||Math.max(1,r>>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;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;KE(t)}this._lastOcclusionObject=null}clear(){for(let e=0,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;KE(t)}this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0}}function KE(e){e.id=null,e.object=null,e.geometry=null,e.material=null,e.groupOrder=null,e.renderOrder=null,e.z=null,e.group=null,e.clippingContext=null}const ZE=[];class QE{constructor(){this.lists=new bE,this._activeLists=new Set,this._frameId=-1}get(e,t,n){const i=this.lists;ZE[0]=e,ZE[1]=t,ZE[2]=n;let r=i.get(ZE);return void 0===r&&(r=new YE(n,e,t),i.set(ZE,r)),ZE[0]=null,ZE[1]=null,ZE[2]=null,r.frameId=this._frameId,this._activeLists.add(r),r}update(e){if(e!==this._frameId){this._frameId=e;for(const t of this._activeLists)e-t.frameId>10&&(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<s.length;e++){const t=s[e];h&&(t.needsUpdate=!0),this.updateTexture(t,f)}u&&this.updateTexture(u,f)}!0!==n.initialized&&(n.initialized=!0,this.info.memory.renderTargets++,n.onDispose=()=>{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<n.length;e++)this._destroyTexture(n[e]);i&&i.renderTarget===e&&this._destroyTexture(i),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(const n of t.bindGroups){const t=this.backend.get(n);t.groups=void 0,t.versions=void 0;for(const t of n.bindings)t.isSampler&&t.texture===e&&(!0!==t.isSampledTexture&&this.backend.destroySampler(t),t.reset(),t.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class sA extends yi{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b,yield this.a}}class aA extends Rv{static get type(){return"OverrideContextNode"}constructor(e,t=null){super(t,{overrideNodes:e}),this.isOverrideContextNode=!0}getFlowContextData(){const e=[];this.traverse(t=>{!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;n<e.length-1;n++)t.push(this._expressionNode.equal(xm(e[n])));else Yt("TSL: Invalid parameter length. Case() requires at least two parameters.",new of);const n=new bm(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Av(i,n);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&!0!==i.isAssign(e)||(t["node"+n++]=i);return t.outputNode||null}build(e,...t){const n=Lm(),i=e.buildStage;Pm(this),e.setActiveStack(this);for(let t=0;t<this.nodes.length;t++){const n=this.nodes[t],r=this._currentNode;if(this._currentNode=n,!n.isVarNode||!n.isIntent(e)||!0===n.isAssign(e)){if("setup"===i)n.build(e);else if("analyze"===i)n.build(e,this);else if("generate"===i){const t=e.getDataFromNode(n,"any").stages,i=t&&t[e.shaderStage];if(n.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)continue;n.build(e,"void")}this._currentNode=r}}let r;if(this.outputNode){const n=this.outputNode.build(e,...t);"generate"===e.buildStage&&"void"===this.outputNode.getNodeType(e)||(r=n)}else r=super.build(e,...t);return Pm(n),e.removeActiveStack(this),r}}const uA=wm(lA).setParameterLength(0,1);new Bn;const cA=new In;Wy.flipX(),cA.depthTexture=new gs(1,1);const hA=new Ra(-1,1,1,-1,0,1);class dA extends br{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lr(t,2))}}const pA=new dA,fA=Xm(Gg([-1,-1,3]).element(ny),Gg([3,-1,-1]).element(ny),0,1);class mA extends qr{constructor(e){super(pA,e),this.camera=hA,this.isQuadMesh=!0}async renderAsync(e){Kt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,hA)}render(e){const t=this.material.vertexNode;this.material.vertexNode=fA,e.render(this,hA),this.material.vertexNode=t}}function gA(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new yi),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const _A=Nm(([e])=>I_(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;t<e.length;t++){const n=e[t];if(KA.push(n.id),KA.push(n.castShadow?1:0),!0===n.isSpotLight){const e=null!==n.map?n.map.id:-1,t=n.colorNode?n.colorNode.getCacheKey():-1;KA.push(e,t)}}const t=cf(KA);return KA.length=0,t}getHash(e){const t=e.getDataFromNode(this);if(void 0===t.lightNodesHash){const n=this.setupLightsNode(e);t.lightNodes=n;const i=[];for(const e of n)i.push(e.getHash());t.lightNodesHash="lights-"+i.join(",")}return t.lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],n=e.getDataFromNode(this).lightNodes||null,i=(e=>e.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;e<t.length;e++)n!==t[e].groupNode&&(r=!1);if(r){let n="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)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<e.length;t++){const n=e[t];this.bindingsIndexes[n.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.has(e)&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.updateBeforeType,n=e.updateAfterType;t===xf&&n===xf||this.sequentialNodes.add(e)}buildUpdateNodes(){for(const e of this.nodes){e.updateType!==xf&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.updateBeforeType,n=e.updateAfterType;t!==xf&&this.updateBeforeNodes.push(e),n!==xf&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}get renderPipeline(){return this.context.renderPipeline}isFilteredTexture(e){return e.magFilter===le||e.magFilter===ue||e.magFilter===oe||e.magFilter===ce||e.minFilter===le||e.minFilter===ue||e.minFilter===oe||e.minFilter===ce}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("THREE.NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getGI,delete e.getShadow,delete e.nodeLoop,delete e.nodeBlock,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return void 0===n.cache&&(n.cache=new kR(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){qt("Abstract function.")}getInstanceIndex(){qt("Abstract function.")}getDrawIndex(){qt("Abstract function.")}getFrontFacing(){qt("Abstract function.")}getFragCoord(){qt("Abstract function.")}isFlipY(){return!1}isContextAssign(){return!0===this.context.assign}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=void 0===t.writeUsageCount?1:t.writeUsageCount+1:t.readUsageCount=void 0===t.readUsageCount?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){const t=e.getShared(this),n=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(void 0!==n)for(const e in n)if(cC(n[e]))return!0;return!1}generateTexture(){qt("Abstract function.")}generateTextureLod(){qt("Abstract function.")}generateTextureSize(){qt("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const s=n?n[r]:null;i+=null!==s?s.build(this,e):this.generateConst(e),r<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,n=null){const i=[];for(const e of t){const{name:t,type:r}=e;n&&n[t]&&n[t].isNode?i.push(n[t].build(this,r)):i.push(this.generateConst(r))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new yi:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new dn:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new fn:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new Dn)),"float"===e)return uC(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${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<s.length;){const e="const"===s[l][0];!0===e&&l++;let t=s[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const n=s[l++][0];let i=Number.parseInt(s[l][0]);!1===Number.isNaN(i)?l++:i=null;const r=s[l++][0];o.push(new pC(n,r,i,t,e))}const u=n.substring(i[0].length),c=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:o,name:c,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:u,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("THREE.FunctionNode: Function is not a GLSL code.")})(e);super(t,n,i,r),this.inputsCode=s,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const n=this.blockCode;if(""!==n){const{type:i,inputsCode:r,headerCode:s,precision:a}=this;let o=`${i} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=s+o+n}else t="";return t}}class LC extends EC{parseFunction(e){return new PC(e)}}const DC=[],IC=[],UC=zg(0,"int").setGroup(Og);class FC extends EE{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new dC,this.nodeBuilderCache=new Map,this.callHashCache=new bE,this.groupsData=new bE,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;if(t.updateType===Mf)return!0;DC[0]=t,DC[1]=e;let n=this.groupsData.get(DC);return void 0===n&&this.groupsData.set(DC,n={}),DC[0]=null,DC[1]=null,n.version!==t.version&&(n.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const n=this.backend.createNodeBuilder(e.object,this.renderer),i=this.renderer.debug.onNodeBuilderCreated;return null!==i&&i(n,e),n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n}getForRender(e,t=!1){const n=this.get(e);let i=n.nodeBuilderState;if(void 0===i){const{nodeBuilderCache:r}=this,s=this.getForRenderCacheKey(e);if(i=r.get(s),void 0===i){const a=async()=>{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;r<i;r++){OC.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[n+r],s=OC.normal;i.x=-s.x,i.y=-s.y,i.z=-s.z,i.w=OC.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix.copy(t.matrixWorldInverse),this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let n=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,r=i.length;let s,a;if(this.clipIntersection?(s=this.intersectionPlanes,a=e.intersectionPlanes.length):(s=this.unionPlanes,a=e.unionPlanes.length),s.length!==a+r){s.length=a+r;for(let e=0;e<r;e++)s[a+e]=new Dn;n=!0}this.projectPlanes(i,s,a),n&&(this.version++,this.cacheKey=`${this.id}:${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new kC(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class zC{constructor(e,t,n){this.bundleGroup=e,this.camera=t,this.renderContext=n}}const VC=[];class GC{constructor(){this.bundles=new bE}get(e,t,n){const i=this.bundles;VC[0]=e,VC[1]=t,VC[2]=n;let r=i.get(VC);return void 0===r&&(r=new zC(e,t,n),i.set(VC,r)),VC[0]=null,VC[1]=null,VC[2]=null,r}dispose(){this.bundles=new bE}}class HC{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(null!==n){t=new n;for(const n in e)t[n]=e[n]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t))qt(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);n.set(t,e)}}addClass(e,t,n){if(n.has(t))qt(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t.name} is not a class.`);n.set(t,e)}}}const WC=new ZA;class jC{constructor(){this.enabled=!0,this._cache=[],this._lightsNodeMap=new WeakMap}createNode(e=[]){return(new ZA).setLights(e)}getNode(e){if(!0!==e.isScene&&!0!==e.isGroup)return WC;let t=this._lightsNodeMap.get(e);return void 0===t&&(t=this.createNode(),this._lightsNodeMap.set(e,t)),t}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}}class $C extends In{constructor(e=1,t=1,n={}){super(e,t,n),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const XC=new fn,qC=new fn,YC=new WeakMap;class KC extends Jt{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Ta,this._cameraL.viewport=new Dn,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new Ta,this._cameraR.viewport=new Dn,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Oa,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._supportsWebGPUBinding=void 0!==globalThis.XRGPUBinding,this._createXRLayer=tN.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new dn,this._currentCameraSettings=null,this._onSessionEvent=QC.bind(this),this._onSessionEnd=JC.bind(this),this._onInputSourcesChange=eN.bind(this),this._onAnimationFrame=nN.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._webgpuBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&qt("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&qt("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBaseLayer(){return null!==this._glProjLayer?this._glProjLayer:this._glBaseLayer}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(null===e||!0!==e.isPostProcessingRenderTarget)return;if(!0!==this.isPresenting)return;if(null===this._glProjLayer)return;const t=this._renderer.backend;if(void 0===t||!0!==t.isWebGLBackend)return;if(null===t.state)return;const n=this._renderer.getOutputRenderTarget();if(null===n||!0!==n.isXRRenderTarget)return;const i=this.getBinding();if(null===i||"function"!=typeof i.foveateBoundTexture)return;this._renderer._textures.updateRenderTarget(e);const{textureGPU:r,glTextureType:s}=t.get(e.texture);if(void 0!==r&&void 0!==s&&e._xrFoveationTextureGPU!==r){e._xrFoveationTextureGPU=r,t.state.bindTexture(s,r);try{i.foveateBoundTexture(s,this.getFoveation())}catch(e){Kt(`XRManager: Unable to foveate bound XR post-processing texture. ${e.name}: ${e.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return null===this._webgpuBinding&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return!0===this._renderer.backend.isWebGPUBackend&&null!==this._session&&this._session.enabledFeatures.includes("webgpu")}_validateWebGPUSession(){if(!0===this._renderer.backend.isWebGPUBackend&&!1===this._session.enabledFeatures.includes("webgpu"))throw new Error('THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.')}async _initWebGPUSession(e){const t=this.getWebGPUBinding(),n=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat()});this._glProjLayer=n,e.updateRenderState({layers:[n]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new In(n.textureWidth,n.textureHeight,{depth:2,minFilter:le,magFilter:le,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,samples:this._renderer.samples}),this._xrRenderTarget.texture.isArrayTexture=!0,!0===this._useMultiviewIfPossible&&Kt("THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session."),this._useMultiview=!1}_disposeWebGPUSession(){const e=this._renderer,t=e.backend,n=this._xrRenderTarget;if(null!==n&&!0===t.isWebGPUBackend){e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),n.dispose();for(const e of n.textures)t.has(e)&&t.destroyTexture(e);t.delete(n)}}_getWebGPUViewData(e){const t=this.getWebGPUBinding(),n={colorTexture:null,viewDescriptors:[],viewports:[]};for(let i=0;i<e.length;i++){const r=t.getViewSubImage(this._glProjLayer,e[i]);null===n.colorTexture&&(n.colorTexture=r.colorTexture),n.viewports.push(r.viewport),r.getViewDescriptor&&n.viewDescriptors.push(r.getViewDescriptor())}return n}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,i,r,s,a,o={}){const l=new Fs(e,t),u=new $C(r,s,{format:Ee,type:he,depthTexture:new gs(r,s,o.stencil?xe:ge,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?Re:Ae),stencilBuffer:o.stencil,samples:o.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),c=new Fr({color:16777215,side:0});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new qr(l,c);h.position.copy(n),h.quaternion.copy(i);const d={type:"quad",width:e,height:t,translation:n,quaternion:i,pixelwidth:r,pixelheight:s,samples:u.samples,plane:h,material:c,rendercall:a,renderTarget:u};if(this._layers.push(d),null!==this._session){d.plane.material=new Fr({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=p,d.plane.material.blendSrc=v,d.plane.material.blendDst=v,d.xrlayer=this._createXRLayer(d);const e=this._session.renderState.layers;e.unshift(d.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,i,r,s,a,o,l={}){const u=new bs(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),c=new $C(s,a,{format:Ee,type:he,depthTexture:new gs(s,a,l.stencil?xe:ge,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Re:Ae),stencilBuffer:l.stencil,samples:l.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),h=new Fr({color:16777215,side:1});h.map=c.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new qr(u,h);d.position.copy(i),d.quaternion.copy(r);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:i,quaternion:r,pixelwidth:s,pixelheight:a,samples:c.samples,plane:d,material:h,rendercall:o,renderTarget:c};if(this._layers.push(f),null!==this._session){f.plane.material=new Fr({color:16777215,side:1}),f.plane.material.blending=5,f.plane.material.blendEquation=p,f.plane.material.blendSrc=v,f.plane.material.blendDst=v,f.xrlayer=this._createXRLayer(f);const e=this._session.renderState.layers;e.unshift(f.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return d}renderLayers(){const e=new fn,t=new pn,n=this._renderer,i=this.isPresenting;this.isPresenting=!1;const r=new dn;n.getSize(r);const s=n.getRenderTarget();for(const i of this._layers){i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget;const r=n.contextNode;let s;if(i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const a=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(i.renderTarget,a.colorTexture,void 0),n._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),s=YC.get(r),void 0===s&&(s=Cv({getOutput:e=>gy(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<l.length;e++)ZC(l[e],o);2===l.length?function(e,t,n){XC.setFromMatrixPosition(t.matrixWorld),qC.setFromMatrixPosition(n.matrixWorld);const i=XC.distanceTo(qC),r=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],u=(r[9]-1)/r[5],c=(r[8]-1)/r[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=i/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,r=d-m,s=p+(i-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(r,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,s,a):r.projectionMatrix.copy(s.projectionMatrix),null===this._currentCameraSettings&&e.isPerspectiveCamera&&(this._currentCameraSettings={camera:e,fov:e.fov,zoom:e.zoom}),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*rn*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new fi,this._controllers[e]=t),t}}function ZC(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function QC(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const n=this._controllers[t];if(void 0!==n){const t=this.getReferenceSpace();n.update(e.inputSource,e.frame,t),n.dispatchEvent({type:e.type,data:e.inputSource})}}function JC(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new $C(e.pixelwidth,e.pixelheight,{format:Ee,type:he,depthTexture:new gs(e.pixelwidth,e.pixelheight,e.stencilBuffer?xe:ge,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?Re:Ae),stencilBuffer:e.stencilBuffer,samples:e.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;if(this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),null!==this._currentCameraSettings){const e=this._currentCameraSettings.camera;e.fov=this._currentCameraSettings.fov,e.zoom=this._currentCameraSettings.zoom,e.updateProjectionMatrix(),this._currentCameraSettings=null}this.dispatchEvent({type:"sessionend"})}function eN(e){const t=this._controllers,n=this._controllerInputSources;for(let i=0;i<e.removed.length;i++){const r=e.removed[i],s=n.indexOf(r);s>=0&&(n[s]=null,t[s].disconnect(r))}for(let i=0;i<e.added.length;i++){const r=e.added[i];let s=n.indexOf(r);if(-1===s){for(let e=0;e<t.length;e++){if(e>=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<e.length;i++){const o=e[i];let l;if(null!==t)l=t.viewports[i];else if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);l=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else l=s.getViewport(o);let u=this._cameras[i];void 0===u&&(u=new Ta,u.layers.enable(i),u.viewport=new Dn,u.matrixWorldAutoUpdate=!1,this._cameras[i]=u),u.matrix.fromArray(o.transform.matrix),u.matrix.decompose(u.position,u.quaternion,u.scale),u.projectionMatrix.fromArray(o.projectionMatrix),u.projectionMatrixInverse.copy(u.projectionMatrix).invert(),u.viewport.set(l.x,l.y,l.width,l.height),0===i&&(n.matrix.copy(u.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale)),!0===a&&n.cameras.push(u)}null!==t&&null!==t.colorTexture&&r.setXRRenderTargetTextures(this._xrRenderTarget,t.colorTexture,t.viewDescriptors),i.setOutputRenderTarget(this._xrRenderTarget);const l=i._getFrameBufferTarget();null!==t&&(this._xrRenderTarget.samples=null===l?i.samples:0,this._xrRenderTarget.depthBuffer=null===l),i.xr.foveateBoundTexture(l)}for(let e=0;e<this._controllers.length;e++){const n=this._controllerInputSources[e],i=this._controllers[e];null!==n&&void 0!==i&&i.update(n,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class iN extends Jt{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Dn(0,0,this._width,this._height),this._scissor=new Dn(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new fs,this.depthTexture=new gs}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=r,a.maxDepth=s}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const rN=new xi,sN=new dn,aN=new Dn,oN=new ts,lN=new is,uN=new Bn,cN=new Dn,hN={[c]:1,[h]:0,[d]:2};class dN{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:i=!1,alpha:r=!0,depth:s=!0,stencil:a=!1,antialias:o=!1,samples:l=0,getFallback:u=null,outputBufferType:c=ve,multiview:h=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=i,this.outputColorSpace=vt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=s,this.stencil=a,this.info=new OE,this.contextNode=Cv(),this.library=new HC,this.lighting=new jC,this._samples=l||(!0===o?4:0),this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new iN(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new vy,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const d=!0===this.alpha?0:1;this._clearColor=new sA(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this.onError=this._onError,this._outputBufferType=c,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._isPreCompiling=!1,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new KC(this,h),this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onNodeBuilderCreated:null,onShaderError:null,getShaderAsync:async(e,t,n)=>{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})),r<i&&await Zt()}}async renderAsync(e,t){Kt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){Yt("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Mb,t.modelNormalViewMatrix=wb):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Mb&&e.modelNormalViewMatrix===wb}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Kt('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),Yt(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),Yt(t)}_bundleNeedsUpdate(e,t){return void 0===t.bundleGPU||e.version!==t.version}_renderBundle(e,t,n){const{bundleGroup:i,camera:r,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(i,r,a),l=this.backend.get(o);if(this._bundleNeedsUpdate(i,l)){this.backend.beginBundle(a),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:u,opaque:c}=s;!0===this.opaque&&c.length>0&&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<n;t++){const n=e[t],i=this._nodes.needsRefresh(n);i===Vt?(this._nodes.updateBefore(n),this._geometries.updateForRender(n),this._nodes.updateForRender(n),this._bindings.updateForRender(n),this._nodes.updateAfter(n)):i===zt&&(this._nodes.updateBefore(n),this._nodes.updateForRender(n),this._bindings.updateSharedForRender(n),this._nodes.updateAfter(n))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(!0===this.backend.isWebGLBackend&&!0===t.multiview||!0!==t.texture.isArrayTexture||t.texture.image.depth<=1)return void this._renderScene(e,e.camera,!1);const n=this._activeCubeFace;try{for(let n=0;n<t.texture.image.depth;n++)this._nodes.setOutputLayerIndex(n),this._activeCubeFace=n,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=n}}_getFrameBufferTarget(){if(!1===this.needsFrameBufferTarget)return null;const{width:e,height:t}=this.getDrawingBufferSize(sN),{depth:n,stencil:i}=this,r=this._outputRenderTarget||this._canvasTarget;let s=this._frameBufferTargets.get(r);if(void 0===s){s=new In(e,t,{depthBuffer:n,stencilBuffer:i,type:this._outputBufferType,format:Ee,colorSpace:Sn.workingColorSpace,generateMipmaps:!1,minFilter:le,magFilter:le,samples:this.samples}),s.isPostProcessingRenderTarget=!0;const a=()=>{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;o<l;o++){const l=a[o],u=s[l.materialIndex];u&&u.visible&&i.push(e,t,u,n,cN.z,l,r)}}else s.visible&&i.push(e,t,s,n,cN.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const s=i;i=this._renderLists.get(e,t,this.lighting);const a=this._bundles.get(e,t,this._currentRenderContext),o=this.backend.get(a);if(this._bundleNeedsUpdate(e,o)){i.begin(),void 0===o.renderObjects?o.renderObjects=[]:o.renderObjects.length=0;const s=e.children;for(let e=0,a=s.length;e<a;e++)this._projectObject(s[e],t,n,i,r);i.finish()}return void s.pushBundle({bundleGroup:e,camera:t,renderList:i})}const s=e.children;for(let e=0,a=s.length;e<a;e++)this._projectObject(s[e],t,n,i,r)}_renderBundles(e,t,n){for(const i of e)this._renderBundle(i,t,n)}_renderTransparents(e,t,n,i,r){if(t.length>0){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<a;s++){const{object:a,geometry:o,material:l,group:u,clippingContext:c}=e[s];this._currentRenderObjectFunction(a,n,t,o,l,u,i,c,r)}}_getShadowNodes(e){const t=e.version;let n=this._cacheShadowNodes.get(e);if(void 0===n||n.version!==t){const i=e.map&&e.map.isTexture,r=e.colorNode&&e.colorNode.isNode,s=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,l=null,u=null;if(i||r||s||a){let t,n;if(s?(t=e.castShadowNode.rgb,n=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&Kt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=Hm(0),n=Um(1)),i&&(n=n.mul(ax("map","texture",e).a)),r&&(n=n.mul(e.colorNode.a)),l=Xm(t,n),a){const t=e.maskShadowNode||e.maskNode;l=Nm(([e])=>(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<i;n++){const i=this.uniforms[n],r=i.boundary,s=i.itemSize*e,a=t%PE,o=a%r,l=a+o;t+=o,0!==l&&PE-l<s&&(t+=PE-l),i.offset=t/e,i.index=n,t+=s}return Math.ceil(t/PE)*PE}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}release(){super.release(),this._values=null}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void Yt("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r]!==i){this._getBufferForType(s)[r]=n[r]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r+0]!==i.x||n[r+1]!==i.y){const a=this._getBufferForType(s);a[r+0]=n[r+0]=i.x,a[r+1]=n[r+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r+0]!==i.x||n[r+1]!==i.y||n[r+2]!==i.z){const a=this._getBufferForType(s);a[r+0]=n[r+0]=i.x,a[r+1]=n[r+1]=i.y,a[r+2]=n[r+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r+0]!==i.x||n[r+1]!==i.y||n[r+2]!==i.z||n[r+3]!==i.w){const a=this._getBufferForType(s);a[r+0]=n[r+0]=i.x,a[r+1]=n[r+1]=i.y,a[r+2]=n[r+2]=i.z,a[r+3]=n[r+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset;if(n[r+0]!==i.r||n[r+1]!==i.g||n[r+2]!==i.b){const s=this.buffer;s[r+0]=n[r+0]=i.r,s[r+1]=n[r+1]=i.g,s[r+2]=n[r+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const n=this.values,i=e.getValue().elements,r=e.offset;if(n[r+0]!==i[0]||n[r+1]!==i[1]||n[r+2]!==i[2]||n[r+4]!==i[3]||n[r+5]!==i[4]||n[r+6]!==i[5]||n[r+8]!==i[6]||n[r+9]!==i[7]||n[r+10]!==i[8]){const s=this.buffer;s[r+0]=n[r+0]=i[0],s[r+1]=n[r+1]=i[1],s[r+2]=n[r+2]=i[2],s[r+4]=n[r+4]=i[3],s[r+5]=n[r+5]=i[4],s[r+6]=n[r+6]=i[5],s[r+8]=n[r+8]=i[6],s[r+9]=n[r+9]=i[7],s[r+10]=n[r+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const n=this.values,i=e.getValue().elements,r=e.offset;if(!1===function(e,t,n){for(let i=0,r=t.length;i<r;i++)if(e[n+i]!==t[i])return!1;return!0}(n,i,r)){this.buffer.set(i,r),function(e,t,n){for(let i=0,r=t.length;i<r;i++)e[n+i]=t[i]}(n,i,r),t=!0,this.addUniformUpdateRange(e)}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let bN=0;class xN extends yN{constructor(e,t){super(e),this.id=bN++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class SN extends pN{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}reset(){this.generation=null,this.version=-1}release(){this._texture=null}}let TN=0;class MN extends SN{constructor(e,t){super(e,t),this.id=TN++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class wN extends MN{constructor(e,t,n,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class EN extends wN{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledCubeTexture=!0}}class AN extends wN{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledTexture3D=!0}}const RN={textureGather:new DA("\nvec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, ij.xw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zy, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.xy, 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherArray:new DA("\nvec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompare:new DA("\nvec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zy, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.xy, ref ), 0.0 )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompareArray:new DA("\nvec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttexture( map, vec4( ij.xw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zy, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.xy, coord.z, ref ) )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),floatpack_snorm_4x8:new DA("uint tsl_packSnorm4x8( vec4 v ) { uvec4 u = uvec4( ivec4( round( clamp( v, -1.0, 1.0 ) * 127.0 ) ) & 0xff ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatpack_unorm_4x8:new DA("uint tsl_packUnorm4x8( vec4 v ) { uvec4 u = uvec4( round( clamp( v, 0.0, 1.0 ) * 255.0 ) ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatunpack_snorm_4x8:new DA("vec4 tsl_unpackSnorm4x8( uint x ) { return max( vec4( ivec4( x << 24, x << 16, x << 8, x ) >> 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*i<n&&l++;const u=o*l*i,c=new e.constructor(u);c.set(e,0),t.array=c;const h=new Kr(t.array,o,l,s,a[t.array.constructor.name]||_e);h.needsUpdate=!0,h.isPBOTexture=!0;const d=new Cy(h,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?e.name:super.getPropertyName(e,t)}isReservedKeyword(e){return UN.has(e)}generatePBO(e){const{node:t,indexNode:n}=e,i=t.value;if(this.renderer.backend.has(i)){this.renderer.backend.get(i).pbo=i.pbo}const r=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),s=this.getPropertyName(r);this.increaseUsage(n);const a=n.build(this,"uint"),o=this.getDataFromNode(e);let l=o.propertyName;if(void 0===l){const n=this.getVarFromNode(e);l=this.getPropertyName(n);const r=this.getDataFromNode(t);let u=r.propertySizeName;void 0===u&&(u=l+"Size",this.getVarFromNode(t,u,"uint"),this.addLineFlowCode(`${u} = uint( textureSize( ${s}, 0 ).x )`,e),r.propertySizeName=u);const{itemSize:c}=i,h="."+Nf.join("").slice(0,c),d=`ivec2(${a} % ${u}, ${a} / ${u})`,p=this.generateTextureLoad(null,s,d,"0",null,null);let f="vec4";i.pbo.type===ge?f="uvec4":i.pbo.type===me&&(f="ivec4"),this.addLineFlowCode(`${l} = ${f}(${p})${h}`,e),o.propertyName=l}return l}generateTextureLoad(e,t,n,i,r,s){let a;return null===i&&(i="0"),a=r?s?`texelFetchOffset( ${t}, ivec3( ${n}, ${r} ), int( ${i} ), ${s} )`:`texelFetch( ${t}, ivec3( ${n}, ${r} ), int( ${i} ) )`:s?`texelFetchOffset( ${t}, ${n}, int( ${i} ), ${s} )`:`texelFetch( ${t}, ${n}, int( ${i} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,n,i,r){return i&&(n=`vec3( ${n}, ${i} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${n}, ${r} ).x`:`texture( ${t}, ${n} ).x`:r?`textureOffset( ${t}, ${n}, ${r} )`:`texture( ${t}, ${n} )`}generateTextureSize(e,t,n){return`textureSize( ${t}, ${n} )`}generateTextureLevel(e,t,n,i,r,s){return r&&(n=`vec3( ${n}, ${r} )`),s?`textureLodOffset( ${t}, ${n}, ${i}, ${s} )`:`textureLod( ${t}, ${n}, ${i} )`}generateTextureBias(e,t,n,i,r,s){return r&&(n=`vec3( ${n}, ${r} )`),s?`textureOffset( ${t}, ${n}, ${s}, ${i} )`:`texture( ${t}, ${n}, ${i} )`}generateTextureGrad(e,t,n,i,r,s){return r&&(n=`vec3( ${n}, ${r} )`),s?`textureGradOffset( ${t}, ${n}, ${i[0]}, ${i[1]}, ${s} )`:`textureGrad( ${t}, ${n}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${i} ) )`:r?s?`textureOffset( ${t}, vec4( ${n}, ${r}, ${i} ), ${s} )`:`texture( ${t}, vec4( ${n}, ${r}, ${i} ) )`:s?`textureOffset( ${t}, vec3( ${n}, ${i} ), ${s} )`:`texture( ${t}, vec3( ${n}, ${i} ) )`;Yt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,n,i,r,s,a){return e.isDepthTexture&&(i="0"),null===s&&(s="ivec2( 0 )"),null===a&&(a="false"),r?(this._include("textureGatherArray"),`tsl_textureGather_array( ${i}, ${t}, vec3( ${n}, ${r} ), ${s}, ${a} )`):(this._include("textureGather"),`tsl_textureGather( ${i}, ${t}, ${n}, ${s}, ${a} )`)}generateTextureGatherCompare(e,t,n,i,r,s,a){return null===s&&(s="ivec2( 0 )"),null===a&&(a="false"),r?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${n}, ${r} ), ${s}, ${i}, ${a} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${n}, ${s}, ${i}, ${a} )`)}getUniforms(e){const t=this.uniforms[e],n=[],i={};for(const e of t){let t=null,r=!1;if("texture"===e.type||"texture3D"===e.type){const n=e.node,i=n.value,r=this.getComponentTypeFromTexture(i),s="float"===r?"":r.charAt(0);t="texture3D"===e.type&&!1===i.isArrayTexture?`${s}sampler3D ${e.name};`:i.compareFunction&&n.isSampleCompare()?!0===i.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===i.isArrayTexture||!0===i.isDataArrayTexture||!0===i.isCompressedArrayTexture?`${s}sampler2DArray ${e.name};`:`${s}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const n=e.node,i=this.getType(n.bufferType),r=n.bufferCount,s=r>0?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;n<e.length;n++){const i=e[n],r=this.getPropertyName(i.attributeNode);r&&(t+=`${i.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${IN}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${IN}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n="// code\n\n";n+=this.flowCode[t];const i=this.flowNodes[t],r=i[i.length-1];for(const e of i){const i=this.getFlowData(e),s=e.name;s&&(n.length>0&&(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;e++){const t=o[e];n.bufferSubData(a,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}n.bindBuffer(a,null),s.version=r.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);n.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){const r=this.backend,{gl:s}=r,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a),{bufferGPU:l}=o,u=-1===i?o.byteLength-n:i;let c;if(null===t)c=new Uint8Array(new ArrayBuffer(u));else if(t.isReadbackBuffer){if(!0===t._mapped)throw new Error("THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.");const e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),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;s<e.length;s++){const a=e[s];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=n:0!==e.blending&&(o=e)}else o=n;null!==o?this._setMRTBlendingIndex(s,o):r.blendFuncSeparateiOES(s,i.ONE,i.ZERO,i.ONE,i.ZERO)}else Kt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:n}=this,i=this.backend.drawBuffersIndexedExt,r=t.blending,s=t.blendSrc,a=t.blendDst,o=t.blendEquation,l=t.premultipliedAlpha;if(5===r){const n=null!==t.blendSrcAlpha?t.blendSrcAlpha:s,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,l=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;i.blendEquationSeparateiOES(e,zN[o],zN[l]),i.blendFuncSeparateiOES(e,VN[s],VN[a],VN[n],VN[r])}else if(i.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),l)switch(r){case 1:default:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case 3:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case 4:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE)}else switch(r){case 1:default:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case 3:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case 4:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE)}}setBlending(e,t,n,i,r,s,a,o,l,u){const{gl:c}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,s=s||n,a=a||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(c.blendEquationSeparate(zN[t],zN[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),n===this.currentBlendSrc&&i===this.currentBlendDst&&s===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(c.blendFuncSeparate(VN[n],VN[i],VN[s],VN[a]),this.currentBlendSrc=n,this.currentBlendDst=i,this.currentBlendSrcAlpha=s,this.currentBlendDstAlpha=a),!1!==o.equals(this.currentBlendColor)&&l===this.currentBlendAlpha||(c.blendColor(o.r,o.g,o.b,l),this.currentBlendColor.copy(o),this.currentBlendAlpha=l),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||u!==this.currentPremultipledAlpha){if(this.currentBlendEquation===p&&this.currentBlendEquationAlpha===p||(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=p,this.currentBlendEquationAlpha=p),u)switch(e){case 1:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case 2:c.blendFunc(c.ONE,c.ONE);break;case 3:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case 4:c.blendFuncSeparate(c.DST_COLOR,c.ONE_MINUS_SRC_ALPHA,c.ZERO,c.ONE);break;default:Yt("WebGLState: Invalid blending: ",e)}else switch(e){case 1:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case 2:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE,c.ONE,c.ONE);break;case 3:Yt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Yt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Yt("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=u}}else!0===this.currentBlendingEnabled&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=Qt[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,i){const r=this._tempVec4.set(e,t,n,i);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,n,i){const r=this._tempVec4.set(e,t,n,i);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,n){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===n||(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===n||(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:i}=this;2===e.side?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.blendColor,e.blendAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const s=e.stencilWrite;if(this.setStencilTest(s),s&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t<n?this.enable(e+t):this.disable(e+t);this.currentClippingPlanes=n}}setPolygonOffset(e,t,n){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===n||(i.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const n=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(n.bindVertexArray(e),null!==t&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:n,currentBoundFramebuffers:i}=this;return i[e]!==t&&(n.bindFramebuffer(e,t),i[e]=t,e===n.DRAW_FRAMEBUFFER&&(i[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(i[n.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:n}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const s=e.textures;if(i.length!==s.length||i[0]!==n.COLOR_ATTACHMENT0){for(let e=0,t=s.length;e<t;e++)i[e]=n.COLOR_ATTACHMENT0+e;i.length=s.length,r=!0}}else i[0]!==n.BACK&&(i[0]=n.BACK,r=!0);r&&n.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:i}=this;void 0===e&&(e=t.TEXTURE0+i-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:i,currentTextureSlot:r,currentBoundTextures:s,maxTextures:a}=this;void 0===n&&(n=null===r?i.TEXTURE0+a-1:r);let o=s[n];void 0===o&&(o={type:void 0,texture:void 0},s[n]=o),o.type===e&&o.texture===t||(r!==n&&(i.activeTexture(n),this.currentTextureSlot=n),i.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,n){const{gl:i}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==n&&(i.bindBufferBase(e,t,n),this.currentBoundBufferBases[r]=n,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,i=n[t];void 0!==i&&void 0!==i.type&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}getParameter(e){const{gl:t,parameters:n}=this;return void 0!==n[e]?n[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:n,parameters:i}=this;i[e]!==t&&(n.pixelStorei(e,t),i[e]=t)}reset(){const{gl:e}=this;e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),this.resetVertexState(),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.set(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this.currentScissor.set(0,0,e.canvas.width,e.canvas.height),this.currentViewport.set(0,0,e.canvas.width,e.canvas.height),this.currentDepthReversed=!1,!0===this.backend.renderer.reversedDepthBuffer&&this.setReversedDepth(!0)}}class $N{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:n,extensions:i}=this;let r;const s=Sn.getTransfer(t);if(e===he)return n.UNSIGNED_BYTE;if(e===ye)return n.UNSIGNED_SHORT_4_4_4_4;if(e===be)return n.UNSIGNED_SHORT_5_5_5_1;if(e===Se)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===Te)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===de)return n.BYTE;if(e===pe)return n.SHORT;if(e===fe)return n.UNSIGNED_SHORT;if(e===me)return n.INT;if(e===ge)return n.UNSIGNED_INT;if(e===_e)return n.FLOAT;if(e===ve)return n.HALF_FLOAT;if(e===Me)return n.ALPHA;if(e===we)return n.RGB;if(e===Ee)return n.RGBA;if(e===Ae)return n.DEPTH_COMPONENT;if(e===Re)return n.DEPTH_STENCIL;if(e===Ce)return n.RED;if(e===Ne)return n.RED_INTEGER;if(e===Pe)return n.RG;if(e===Le)return n.RG_INTEGER;if(e===Ie)return n.RGBA_INTEGER;if(e===Ue||e===Fe||e===Oe||e===Be)if(s===xt){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===Ue)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Fe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Oe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Be)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===Ue)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Fe)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Oe)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Be)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===ke||e===ze||e===Ve||e===Ge){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===ke)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===ze)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Ve)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Ge)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===He||e===We||e===je||e===$e||e===Xe||e===qe||e===Ye){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===He||e===We)return s===xt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===je)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===$e)return r.COMPRESSED_R11_EAC;if(e===Xe)return r.COMPRESSED_SIGNED_R11_EAC;if(e===qe)return r.COMPRESSED_RG11_EAC;if(e===Ye)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Ke||e===Ze||e===Qe||e===Je||e===et||e===tt||e===nt||e===it||e===rt||e===st||e===at||e===ot||e===lt||e===ut){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Ke)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Ze)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Qe)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Je)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===et)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===tt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===nt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===it)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===rt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===st)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===at)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===ot)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===lt)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ut)return s===xt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===ct||e===ht||e===dt){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===ct)return s===xt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===ht)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===dt)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(e===pt||e===ft||e===mt||e===gt){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===pt)return r.COMPRESSED_RED_RGTC1_EXT;if(e===ft)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===mt)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===gt)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===xe?n.UNSIGNED_INT_24_8:void 0!==n[e]?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,i)=>{!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;t<i.length;t++){const s=i[t];if(e.isCompressedArrayTexture)if(e.format!==n.RGBA)if(null!==o)if(e.layerUpdates.size>0){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;t<a.length;t++){const i=QN(a[t].images[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,o,l,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){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;e<t;e++){const t=s[e],i=QN(t);n.texSubImage2D(a,e,0,0,t.width,t.height,o,l,i)}else{const e=QN(t.image);n.texSubImage2D(a,0,0,0,i,r,o,l,e)}}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:i,glTextureType:r}=n.get(e);n.state.bindTexture(r,i),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const i=n.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const e in i.framebuffers)t.deleteFramebuffer(i.framebuffers[e]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let e=0;e<i.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(i.msaaRenderbuffers[e]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:n,backend:i}=this,{textureGPU:r,renderTarget:s}=i.get(e);this.deallocateRenderBuffers(s),!1===t&&!0!==e.isExternalTexture&&n.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){const{gl:a,backend:o}=this,{state:l}=this.backend,{textureGPU:u,glTextureType:c,glType:h,glFormat:d}=o.get(t);let p,f,m,g,_,v,y,b,x;l.bindTexture(c,u);const S=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)p=n.max.x-n.min.x,f=n.max.y-n.min.y,m=n.isBox3?n.max.z-n.min.z:1,g=n.min.x,_=n.min.y,v=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(S.width*t),f=Math.floor(S.height*t),m=e.isDataArrayTexture||e.isArrayTexture?S.depth:e.isData3DTexture?Math.floor(S.depth*t):1,g=0,_=0,v=0}null!==i?(y=i.x,b=i.y,x=i.z):(y=0,b=0,x=0),l.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const T=l.getParameter(a.UNPACK_ROW_LENGTH),M=l.getParameter(a.UNPACK_IMAGE_HEIGHT),w=l.getParameter(a.UNPACK_SKIP_PIXELS),E=l.getParameter(a.UNPACK_SKIP_ROWS),A=l.getParameter(a.UNPACK_SKIP_IMAGES);l.pixelStorei(a.UNPACK_ROW_LENGTH,S.width),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,S.height),l.pixelStorei(a.UNPACK_SKIP_PIXELS,g),l.pixelStorei(a.UNPACK_SKIP_ROWS,_),l.pixelStorei(a.UNPACK_SKIP_IMAGES,v);const R=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const n=o.get(e),i=o.get(t),c=o.get(n.renderTarget),h=o.get(i.renderTarget),d=c.framebuffers[n.cacheKey],S=h.framebuffers[i.cacheKey],T=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,M=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,d),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,S);for(let e=0;e<m;e++)R&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,n.textureGPU,r,v+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,s,x+e)),a.blitFramebuffer(g,_,p,f,y,b,p,f,a.DEPTH_BUFFER_BIT,a.NEAREST);l.bindFramebuffer(a.READ_FRAMEBUFFER,T),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,M)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer());const n=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,i=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<m;e++)R?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,r,v+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,s,x+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,u,s),0!==r?a.blitFramebuffer(g,_,p,f,y,b,p,f,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(c,s,y,b,x+e,g,_,p,f):a.copyTexSubImage2D(c,s,y,b,g,_,p,f);l.bindFramebuffer(a.READ_FRAMEBUFFER,n),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,i)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(c,s,y,b,x,p,f,m,d,h,S.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(c,s,y,b,x,p,f,m,d,S.data):a.texSubImage3D(c,s,y,b,x,p,f,m,d,h,S):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,s,y,b,p,f,d,h,S.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,s,y,b,S.width,S.height,d,S.data):a.texSubImage2D(a.TEXTURE_2D,s,y,b,p,f,d,h,S);l.pixelStorei(a.UNPACK_ROW_LENGTH,T),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,M),l.pixelStorei(a.UNPACK_SKIP_PIXELS,w),l.pixelStorei(a.UNPACK_SKIP_ROWS,E),l.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===s&&t.generateMipmaps&&a.generateMipmap(c),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:i}=this,{state:r}=this.backend,{textureGPU:s}=this.backend.get(e),{x:a,y:o,z:l,w:u}=n,c=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,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;i<n;i++)this.render(e[i],t[i]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,n):o.multiDrawArraysWEBGL(r,e,0,t,0,n);let i=0;for(let e=0;e<n;e++)i+=t[e];a.update(s,i,1)}}}class iP{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(qt(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class rP extends iP{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return qt("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;this.currentQueryIndex+2>this.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<s.length;e++){const t=s[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,this._resolveRenderTarget(e),null!==r){if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:e,height:t}=this.getDrawingBufferSize();n.viewport(0,0,e,t)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=this.getDrawingBufferSize();n.scissor(0,0,e,t)}}this.prepareTimestampBuffer(Ot,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=!0;for(let t=0;t<n.length;t++){const s=n[t];s&&(r.getQueryParameter(s,r.QUERY_RESULT_AVAILABLE)?(0===r.getQueryParameter(s,r.QUERY_RESULT)&&e.add(i[t]),n[t]=null,r.deleteQuery(s)):a=!1)}!1===a?requestAnimationFrame(s):t.occluded=e};s()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:i,width:r,height:s}=e.viewportValue;t.viewport(n,e.height-s-i,r,s)}updateScissor(e){const{state:t}=this,{x:n,y:i,width:r,height:s}=e.scissorValue;t.scissor(n,e.height-s-i,r,s)}setScissorTest(e){this.state.setScissorTest(e)}resetState(){this.state.reset()}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,i=null,r=!0,s=!0){const{gl:a,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let l=0;if(e&&(l|=a.COLOR_BUFFER_BIT),t&&(l|=a.DEPTH_BUFFER_BIT),n&&(l|=a.STENCIL_BUFFER_BIT),0!==l){let u;u=i.clearColorValue?i.clearColorValue:this.getClearColor();const c=o.getClearDepth(),h=o.getClearStencil();if(t&&this.state.setDepthMask(!0),n&&this.state.setStencilMask(4294967295),null===i.textures)e&&a.clearColor(u.r,u.g,u.b,u.a),t&&a.clearDepth(c),n&&a.clearStencil(h),a.clear(l);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++){const t=i.mrt?i.mrt.getClearColor(i.textures[e].name):null;null!==t?a.clearBufferfv(a.COLOR,e,[t.r,t.g,t.b,t.a]):0===e?a.clearBufferfv(a.COLOR,e,[u.r,u.g,u.b,u.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1])}t&&n?a.clearBufferfi(a.DEPTH_STENCIL,0,c,h):t?a.clearBufferfv(a.DEPTH,0,[c]):n&&a.clearBufferiv(a.STENCIL,0,[h]),r&&s&&this._resolveRenderTarget(i),r&&null!==this._currentContext&&this._currentContext!==i&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Ft,this.getTimestampUID(e))}compute(e,t,n,i,r=null){const{state:s,gl:a}=this;!1===this.discard&&(s.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:l,attributes:u}=this.get(i),c=this._getVaoKey(u),h=this.vaoCache[c];void 0===h?this.vaoCache[c]=this._createVao(u):s.setVertexState(h),s.useProgram(o),this._bindUniforms(n);const d=this._getTransformFeedback(l);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,d),a.beginTransformFeedback(a.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(Kt("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(Kt("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),u[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<l.length;e++){const t=l[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Ft,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,n,i,r,s){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:n}=this,i=n.getUniformLocation(s,"nodeUniformDrawId"),r=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)n.uniform1ui(i,e),t.render(r[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else r>1?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<r;n++){const i=o.createBuffer();e[0]=n,o.bindBuffer(o.UNIFORM_BUFFER,i),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(i)}n.indexesGPU=t}let s=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===r)break e;(e.isUniformsGroup||e.isUniformBuffer)&&s++}const u=this._currentContext.renderTarget,c=null===u||!0===u.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,h=this._isRenderCameraDepthArray(this._currentContext),d=this._currentContext.activeCubeFace;if(h){const e=this.get(u.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=u;for(let e=0,n=i.length;e<n;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=d,this._currentContext.activeCubeFace=d}}for(let r=0,u=i.length;r<u;r++){const u=i[r];if(t.layers.test(u.layers)){h&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const i=u.viewport;if(void 0!==i){const t=i.x*c,n=i.y*c,r=i.width*c,s=i.height*c;l.viewport(Math.floor(t),Math.floor(e.context.height-s-n),Math.floor(r),Math.floor(s))}l.bindBufferBase(o.UNIFORM_BUFFER,s,n.indexesGPU[r]),this._draw(t,v,x,y,b,a)}this._currentContext.activeCubeFace=d,this.renderer._activeCubeFace=d}}else this._draw(t,v,x,y,b,a)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,r,s){return this.textureUtils.copyTextureToBuffer(e,t,n,i,r,s)}updateSampler(){return""}createNodeBuilder(e,t){return new FN(e,t)}createProgram(e){const t=this.gl,{stage:n,code:i}=e,r="fragment"===n?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:s}=i,a=n.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU;if(n.attachShader(a,o),n.attachShader(a,l),n.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const r=new Promise(t=>{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<s;e++){const r=e+1;i.push(`${r===t?">":" "} ${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<u.length;e++){const t=u[e];c.push(t.varyingName),h.push(t.attributeNode)}i.attachShader(a,o),i.attachShader(a,l),i.transformFeedbackVaryings(a,c,i.SEPARATE_ATTRIBS),i.linkProgram(a);const d=s.attributes,p=[],f=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}for(let e=0;e<h.length;e++){const t=h[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER);const n=this.get(t);f.push(n)}if(this.set(e,{programGPU:a,fragmentShader:o,vertexShader:l,transformBuffers:f,attributes:p}),null!==n&&this.parallel){const r=this.parallel,s=new Promise(n=>{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;r<a;r++){const a=s[r],o=a.start*n,l=a.count*n,u=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,u,i,o,l)}}this.set(n,e)}else if(n.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(n.texture);e.textureGPU=t,e.glTextureType=i,this.set(n,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const n=this.get(e).bufferGPU,i=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),0===r.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=Gt(i),n=e?1:i.BYTES_PER_ELEMENT;let s=r[0].start;for(let a=0,o=r.length;a<o;a++){const o=r[a],l=r[a+1],u=o.start+o.count;if(void 0!==l&&l.start===u)continue;const c=s*n,h=(u-s)*n,d=c*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,d,i,c,h),void 0!==l&&(s=l.start)}}}}createUniformBuffer(e){const t=this.get(e);if(void 0===t.bufferGPU){const n=this.gl,i=e.buffer;t.bufferGPU=n.createBuffer(),n.bindBuffer(n.UNIFORM_BUFFER,t.bufferGPU),n.bufferData(n.UNIFORM_BUFFER,i.byteLength,n.DYNAMIC_DRAW)}}destroyUniformBuffer(e){const t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(tP).filter(t=>tP[t]===e),n=this.extensions;for(let e=0;e<t.length;e++)if(n.has(t[e]))return!0;return!1}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){this.textureUtils.copyTextureToTexture(e,t,n,i,r,s)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===Bt||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:n}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,s=this.get(r),{depthBuffer:a,stencilBuffer:o}=r,l=!0===r.isCubeRenderTarget,u=!0===r.isRenderTarget3D,c=r.depth>1,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;n<i.length;n++){const s=i[n],a=this.get(s);a.renderTarget=e.renderTarget,a.cacheKey=y;const o=t.COLOR_ATTACHMENT0+n;if(r.multiview)g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,a.textureGPU,0,v,0,2);else if(u||c){const e=this.renderer._activeCubeFace,n=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,o,a.textureGPU,n,e)}else if(_)m.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,a.textureGPU,0,v);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,a.textureGPU,e)}}}const h=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const n=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(n,e,0,_),s.xrDepthRenderbuffer=n,a.push(o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,h,t.RENDERBUFFER,n)}else if(null!==e.depthTexture){a.push(o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const n=this.get(e.depthTexture);if(n.renderTarget=e.renderTarget,n.cacheKey=y,r.multiview)g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,n.textureGPU,0,v,0,2);else if(d&&_)m.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,n.textureGPU,0,v);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,h,n.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,n.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,n.textureGPU,0)}s.depthInvalidationArray=a}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,b);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),s=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,s,r.textureGPU,0,i)}if((h||_||r.multiview)&&!0!==r._isOpaqueFramebuffer){n.bindFramebuffer(t.FRAMEBUFFER,b);const i=this.get(e.textures[0]);r.multiview?g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,v,0,2):_?m.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,v):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const a=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=s.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,e)}else{const n=this.get(e.depthTexture);r.multiview?g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,a,n.textureGPU,0,v,0,2):_?m.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,a,t.TEXTURE_2D,n.textureGPU,0,v):t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,n.textureGPU,0)}}}if(v>0&&!1===_&&!r.multiview){if(void 0===p){p=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,p);const i=[],r=e.textures;for(let n=0;n<r.length;n++){i[n]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,i[n]);const r=e.textures[n],s=this.get(r);t.renderbufferStorageMultisample(t.RENDERBUFFER,v,s.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+n,t.RENDERBUFFER,i[n])}t.bindRenderbuffer(t.RENDERBUFFER,null),s.msaaFrameBuffer=p,s.msaaRenderbuffers=i,a&&void 0===f&&(f=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(f,e,v),s.depthRenderbuffer=f)}i=s.msaaFrameBuffer}else i=b;n.drawBuffers(e,b)}n.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){t+=":"+this.get(e[n]).id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let n=0;n<e.length;n++){const i=e[n],r=this.get(i);let s,a;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(n),!0===i.isInterleavedBufferAttribute?(s=i.data.stride*r.bytesPerElement,a=i.offset*r.bytesPerElement):(s=0,a=0),r.isInteger?t.vertexAttribIPointer(n,i.itemSize,r.type,s,a):t.vertexAttribPointer(n,i.itemSize,r.type,i.normalized,s,a),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?t.vertexAttribDivisor(n,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(n,i.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let n=this.transformFeedbackCache[t];if(void 0!==n)return n;const{gl:i}=this;n=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,n);for(let t=0;t<e.length;t++){const n=e[t];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,t,n.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;let i=0,r=0;for(const s of e)for(const e of s.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const r=i++,s=n.getUniformBlockIndex(t,e.name);n.uniformBlockBinding(t,s,r)}else if(e.isSampledTexture){const i=r++,s=n.getUniformLocation(t,e.name);n.uniform1i(s,i)}}_bindUniforms(e){const{gl:t,state:n}=this;let i=0,r=0;for(const s of e)for(const e of s.bindings){const s=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=i++;n.bindBufferBase(t.UNIFORM_BUFFER,e,s.bufferGPU)}else if(e.isSampledTexture){const e=r++;n.bindTexture(s.glTextureType,s.textureGPU,t.TEXTURE0+e)}}}_resolveRenderTarget(e){const{gl:t,state:n}=this,i=e.renderTarget;if(null!==e.textures&&i){const r=this.get(i);if(i.samples>0&&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;e<u.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let n=0;n<u.length;n++){if(c){const{textureGPU:e}=this.get(u[n]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[n]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:n,y:i,width:r,height:s}=e.scissorValue,o=e.height-s-i;t.blitFramebuffer(n,o,n+r,o+s,n,o,n+r,o+s,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(c)for(let e=0;e<u.length;e++){const{textureGPU:n}=this.get(u[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,l[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,n,0)}if(!0===this._supportsInvalidateFramebuffer){if(!1===i.storeMultisampledColorBuffer)for(let e=0;e<u.length;e++)sP.push(t.COLOR_ATTACHMENT0+e);i.depthBuffer&&!1===i.storeMultisampledDepthBuffer&&sP.push(i.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),sP.length>0&&(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<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n",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;s<e.mipLevelCount;s++)for(let a=0;a<e.depthOrArrayLayers;a++){KI.dimension=t,KI.baseMipLevel=s-1,KI.mipLevelCount=1;const o=e.createView(KI);KI.reset(),VI.layout=i,VI.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:o},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(VI);VI.reset(),KI.dimension="2d",KI.baseMipLevel=s,KI.mipLevelCount=1,KI.baseArrayLayer=a,KI.arrayLayerCount=1;const u=e.createView(KI);KI.reset();const c=new II;c.view=u,c.loadOp=TP,c.storeOp=bP;const h=new UI;h.colorAttachments.push(c),WI.colorFormats=[e.format];const d=this.device.createRenderBundleEncoder(WI);WI.reset(),d.setPipeline(n),d.setBindGroup(0,l),d.draw(3,1,0,a),r.push({renderBundles:[d.finish()],passDescriptor:h})}return r}_mipmapRunBundles(e,t){const n=t.length;for(let i=0;i<n;i++){const n=t[i],r=e.beginRenderPass(n.passDescriptor);r.executeBundles(n.renderBundles),r.end()}}}class QI{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect="all"}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect="all"}}class JI{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}}const eU=new PI,tU=new LI,nU=new class{constructor(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}},iU=new QI,rU=new class{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},sU=new class{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},aU=new class{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}},oU=new class extends QI{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}},lU=new kI,uU=new JI,cU={[Tt]:"never",[Mt]:"less",[wt]:"equal",[Et]:"less-equal",[At]:"greater",[Ct]:"greater-equal",[Nt]:"always",[Rt]:"not-equal"},hU=[0,1,3,2,4,5];function dU(e,t,n,i,r,s,a,o,l,u){iU.texture=t,iU.mipLevel=n,iU.origin.z=i,sU.offset=i*s,sU.bytesPerRow=a,sU.rowsPerImage=o,uU.width=l,uU.height=u,e.queue.writeTexture(iU,r.data,sU,uU),iU.reset(),sU.reset(),uU.reset()}class pU{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,n=e.texture,i=e.textureNode,r=!0===n.isDepthTexture&&null!==n.compareFunction&&i.isSampleCompare()&&t.hasCompatibility(Bt),s=n.minFilter+"-"+n.magFilter+"-"+n.wrapS+"-"+n.wrapT+"-"+(n.wrapR||"0")+"-"+n.anisotropy+"-"+(!0===n.isDepthTexture?1:0)+"-"+(r?n.compareFunction:0);let a=this._samplerCache.get(s);if(void 0===a){nU.addressModeU=this._convertAddressMode(n.wrapS),nU.addressModeV=this._convertAddressMode(n.wrapT),nU.addressModeW=this._convertAddressMode(n.wrapR),nU.magFilter=this._convertFilterMode(n.magFilter),nU.minFilter=this._convertFilterMode(n.minFilter),nU.mipmapFilter=this._convertMipmapFilterMode(n.minFilter),n.isDepthTexture&&!1===r&&(nU.magFilter=wD,nU.minFilter=wD,nU.mipmapFilter=wD),nU.magFilter===MD&&nU.minFilter===MD&&nU.mipmapFilter===MD&&(nU.maxAnisotropy=n.anisotropy),r&&(nU.compare=cU[n.compareFunction]);const e=t.device.createSampler(nU);nU.reset(),a={sampler:e,usedTimes:0},this._samplerCache.set(s,a)}const o=t.get(e);return o.sampler!==a.sampler&&(this._releaseSampler(o),o.samplerKey=s,o.sampler=a.sampler,a.usedTimes++),s}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(void 0!==e.sampler){const t=this._samplerCache.get(e.samplerKey);t.usedTimes--,0===t.usedTimes&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t;const n=fU(e,this.backend.device);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(n):this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,i=n.get(e);if(i.initialized){if(!0===i.externalTexture)return;throw new Error("THREE.WebGPUTextureUtils: Texture already initialized.")}if(e.isExternalTexture)return i.texture=e.sourceTexture,void(i.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:s,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),u=e.internalFormat||t.format||fU(e,n.device);i.format=u;const{samples:c,primarySamples:h,isMSAA:d}=n.utils.getTextureSampleData(e),p=e.renderTarget,f=c>1&&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;t<a;t++)e.label=y.label+"-msaa-"+t,i.msaaTextures.push(n.device.createTexture(e))}else i.msaaTexture=n.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=y}destroyTexture(e,t=!1){const n=this.backend,i=n.get(e);if(void 0!==i.texture&&!1===t&&!0!==e.isExternalTexture&&!0!==i.externalTexture&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),void 0!==i.msaaTextures)for(const e of i.msaaTextures)e.destroy();n.delete(e)}generateMipmaps(e,t=null){const n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,s=t.colorTexture,a=e.get(s);if(s.width===n&&s.height===i&&s.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),lU.label="colorBuffer",lU.size.width=n,lU.size.height=i,lU.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),lU.format=e.utils.getPreferredCanvasFormat(),lU.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,o=e.device.createTexture(lU),lU.reset(),s.source.width=n,s.source.height=i,s.samples=r,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const n=this.backend,i=n.renderer.getCanvasTarget(),{width:r,height:s}=n.getDrawingBufferSize(),a=n.renderer.currentSamples,o=i.depthTexture;if(o.width===r&&o.height===s&&o.samples===a&&o.depth===e&&o.stencil===t)return n.get(o).texture;const l=n.get(o).texture;let u,c;if(t?(u=Re,c=!0===n.renderer.reversedDepthBuffer?_e:xe):e&&(u=Ae,c=!0===n.renderer.reversedDepthBuffer?_e:ge),void 0!==l){if(o.image.width===r&&o.image.height===s&&o.format===u&&o.type===c&&o.samples===a)return l;this.destroyTexture(o)}return o.name="depthBuffer",o.format=u,o.type=c,o.image.width=r,o.image.height=s,o.samples=a,this.createTexture(o,{width:r,height:s}),n.get(o).texture}updateTexture(e,t){const n=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:r}=n;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(i.length>0)for(let t=0,s=i.length;t<s;t++){const s=i[t];this._copyBufferToTexture(s,n.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,n.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const i of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,r,i,e.flipY,i);e.clearLayerUpdates()}else for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,n.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)e.isCompressedArrayTexture&&e.layerUpdates.size>0?(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;t<s;t++){const s=i[t];this._copyImageToTexture(s,n.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,n.texture,r,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,i,r,s){const a=this.backend.device,o=this.backend.get(e),l=o.texture,u=o.textureDescriptorGPU.format,c=this._getBytesPerTexel(u);let h=i*c;h=256*Math.ceil(h/256),eU.size=(r-1)*h+i*c,eU.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const d=a.createBuffer(eU);eU.reset();const p=a.createCommandEncoder(tU);iU.texture=l,iU.origin.x=t,iU.origin.y=n,iU.origin.z=s,rU.buffer=d,rU.bytesPerRow=h,uU.width=i,uU.height=r,p.copyTextureToBuffer(iU,rU,uU),iU.reset(),rU.reset(),uU.reset();const f=this._getTypedArrayType(u);CI(a,p.finish()),await d.mapAsync(GPUMapMode.READ);const m=d.getMappedRange().slice();return d.destroy(),new f(m)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const n=new Ln;n.minFilter=se,n.magFilter=se,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const n=new ms;n.minFilter=se,n.magFilter=se,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){const i=e.images,r=e.mipmaps;for(let s=0;s<6;s++){const a=i[s],o=!0===e.flipY?hU[s]:s;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,o,e.flipY):this._copyImageToTexture(a,t,n,o,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const a=r[i].images[s];a.isDataTexture?this._copyBufferToTexture(a.image,t,n,o,e.flipY,0,i+1):this._copyImageToTexture(a,t,n,o,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,n,i,r,s,a=0){const o=this.backend.device,l=a>0?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<e.length;i++){const l=e[i],u=l.width,c=l.height,h=a?n.size.depthOrArrayLayers:1,d=Math.ceil(u/s.width)*s.byteLength,p=Math.ceil(c/s.height),f=d*p,m=Math.ceil(u/s.width)*s.width,g=p*s.height;if(null!==o)for(const e of o)dU(r,t,i,e,l,f,d,p,m,g);else for(let e=0;e<h;e++)dU(r,t,i,e,l,f,d,p,m,g)}}_getBlockData(e){return e===TL||e===ML?{byteLength:8,width:4,height:4}:e===wL||e===EL||e===AL||e===RL?{byteLength:16,width:4,height:4}:e===CL||e===NL?{byteLength:8,width:4,height:4}:e===PL||e===LL||e===DL||e===IL||e===UL||e===FL?{byteLength:16,width:4,height:4}:e===OL||e===BL||e===kL||e===zL?{byteLength:8,width:4,height:4}:e===VL||e===GL?{byteLength:16,width:4,height:4}:e===HL||e===WL?{byteLength:8,width:4,height:4}:e===jL||e===$L||e===XL||e===qL?{byteLength:16,width:4,height:4}:e===YL||e===KL?{byteLength:16,width:5,height:4}:e===ZL||e===QL?{byteLength:16,width:5,height:5}:e===JL||e===eD?{byteLength:16,width:6,height:5}:e===tD||e===nD?{byteLength:16,width:6,height:6}:e===iD||e===rD?{byteLength:16,width:8,height:5}:e===sD||e===aD?{byteLength:16,width:8,height:6}:e===oD||e===lD?{byteLength:16,width:8,height:8}:e===uD||e===cD?{byteLength:16,width:10,height:5}:e===hD||e===dD?{byteLength:16,width:10,height:6}:e===pD||e===fD?{byteLength:16,width:10,height:8}:e===mD||e===gD?{byteLength:16,width:10,height:10}:e===_D||e===vD?{byteLength:16,width:12,height:10}:e===yD||e===bD?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=xD;return e===ne?t=SD:e===re&&(t=TD),t}_convertFilterMode(e){let t=MD;return e!==se&&e!==ae&&e!==oe||(t=wD),t}_convertMipmapFilterMode(e){return e===oe||e===ce?MD:wD}_getBytesPerTexel(e){return e===NP||e===PP||e===LP||e===DP?1:e===IP||e===UP||e===FP||e===OP||e===BP||e===kP||e===zP||e===VP||e===GP?2:e===HP||e===WP||e===jP||e===$P||e===XP||e===qP||e===YP||e===KP||e===ZP||e===QP||e===JP||e===eL||e===tL||e===nL||e===iL||e===rL||e===sL||e===aL||e===xL||e===yL||e===bL||e===SL?4:e===oL||e===lL||e===uL||e===cL||e===hL||e===dL||e===pL||e===fL?8:e===mL||e===gL||e===_L?16:void 0}_getTypedArrayType(e){return e===LP?Uint8Array:e===DP?Int8Array:e===NP?Uint8Array:e===PP?Int8Array:e===kP?Uint8Array:e===zP?Int8Array:e===OP?Uint8Array:e===BP?Int8Array:e===QP?Uint8Array:e===JP?Int8Array:e===YP||e===KP?Uint8Array:e===ZP?Int8Array:e===IP?Uint16Array:e===UP?Int16Array:e===$P?Uint16Array:e===XP?Int16Array:e===cL?Uint16Array:e===hL?Int16Array:e===FP||e===qP||e===dL||e===VP?Uint16Array:e===GP?Int16Array:e===nL?Uint16Array:e===iL?Int16Array:e===pL?Uint16Array:e===fL?Int16Array:e===HP?Uint32Array:e===WP?Int32Array:e===jP?Float32Array:e===oL?Uint32Array:e===lL?Int32Array:e===uL?Float32Array:e===mL?Uint32Array:e===gL?Int32Array:e===_L?Float32Array:e===eL||e===tL?Uint8Array:e===sL||e===rL||e===aL?Uint32Array:e===xL?Float32Array:e===yL||e===bL?Uint32Array:e===SL?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?pI:dI,t}}function fU(e,t){const n=e.format,i=e.type,r=e.normalized,s=e.colorSpace,a=Sn.getTransfer(s);let o,l=!1;if(r&&(l=t.features.has(xI.TextureFormatsTier1),!1===l&&qt("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(n){case Ue:case Fe:o=a===xt?ML:TL;break;case Oe:o=a===xt?EL:wL;break;case Be:o=a===xt?RL:AL;break;case pt:o=CL;break;case ft:o=NL;break;case mt:o=PL;break;case gt:o=LL;break;case ct:o=a===xt?FL:UL;break;case ht:o=IL;break;case dt:o=DL;break;case We:case He:o=a===xt?BL:OL;break;case je:o=a===xt?GL:VL;break;case $e:o=HL;break;case Xe:o=WL;break;case qe:o=jL;break;case Ye:o=$L;break;case Ke:o=a===xt?qL:XL;break;case Ze:o=a===xt?KL:YL;break;case Qe:o=a===xt?QL:ZL;break;case Je:o=a===xt?eD:JL;break;case et:o=a===xt?nD:tD;break;case tt:o=a===xt?rD:iD;break;case nt:o=a===xt?aD:sD;break;case it:o=a===xt?lD:oD;break;case rt:o=a===xt?cD:uD;break;case st:o=a===xt?dD:hD;break;case at:o=a===xt?fD:pD;break;case ot:o=a===xt?gD:mD;break;case lt:o=a===xt?vD:_D;break;case ut:o=a===xt?bD:yD;break;case Ee:o=a===xt?KP:YP;break;default:Yt("WebGPURenderer: Unsupported texture format.",n)}else switch(n){case Ee:switch(i){case de:o=ZP;break;case pe:o=l?fL:hL;break;case fe:o=l?pL:cL;break;case ge:o=mL;break;case me:o=gL;break;case he:o=a===xt?KP:YP;break;case ve:o=dL;break;case _e:o=_L;break;default:Yt("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case we:switch(i){case Se:o=rL;break;case Te:o=aL;break;default:Yt("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case Ce:switch(i){case de:o=PP;break;case pe:o=l?GP:UP;break;case fe:o=l?VP:IP;break;case ge:o=HP;break;case me:o=WP;break;case he:o=NP;break;case ve:o=FP;break;case _e:o=jP;break;default:Yt("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case Pe:switch(i){case de:o=BP;break;case pe:o=l?iL:XP;break;case fe:o=l?nL:$P;break;case ge:o=oL;break;case me:o=lL;break;case he:o=OP;break;case ve:o=qP;break;case _e:o=uL;break;default:Yt("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case Ae:switch(i){case fe:o=vL;break;case ge:o=yL;break;case _e:o=xL;break;default:Yt("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case Re:switch(i){case xe:o=bL;break;case _e:t&&!1===t.features.has(xI.Depth32FloatStencil8)&&Yt('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=SL;break;default:Yt("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case Ne:switch(i){case me:o=WP;break;case ge:o=HP;break;default:Yt("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case Le:switch(i){case me:o=lL;break;case ge:o=oL;break;default:Yt("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Ie:switch(i){case me:o=gL;break;case ge:o=mL;break;default:Yt("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:Yt("WebGPURenderer: Unsupported texture format.",n)}return o}const mU=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\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<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",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<i.length;e++){const{name:t,type:n}=i[e];let r=n;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=n.split("<")[0]),r=_U[r]),s.push(new pC(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:_U[o]||o,inputs:s,name:l,inputsCode:n,blockCode:a,outputType:o}}throw new Error("THREE.WGSLNodeFunction: Function is not a WGSL code.")})(e);super(t,n,i),this.inputsCode=r,this.blockCode=s,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+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<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},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<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new DA("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new DA("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new 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<f32> ) -> mat2x2<f32> {\n\n\tlet det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];\n\n\treturn mat2x2<f32>(\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<f32> ) -> mat3x3<f32> {\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<f32>(\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<f32> ) -> mat4x4<f32> {\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<f32>(\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<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new DA("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},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<f32>",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<u32>":"vec2<u32>",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<f32>(${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<f32>(${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}<f32>(${r}) / ${l}<f32>( ${o} )`);return n=`${l}<u32>( clamp( floor( ${a}( ${n} ) * ${l}<f32>( ${o} ) ), ${`${l}<f32>( 0 )`}, ${`${l}<f32>( ${o} - ${"vec3"===l?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 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<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],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<f32, ${e} >`,"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<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e<i;e++){const i=n[e],r=i.name,s=this.getType(i.type);t.push(`@location( ${e} ) ${r} : ${s}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const n of e.members){const i=e.output?"@location( "+n.index+" ) ":"";let r=this.getType(n.type);n.atomic&&(r="atomic< "+r+" >"),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="<private>");const i=[],r=this.vars[e];if(void 0!==r)for(const e of r)i.push(`${this.getVar(e.type,e.name,e.count,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<f32>","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];let r=0;for(let s=0;s<n.length;s++){const a=n[s];if(a.needsInterpolation){let e=`@location( ${r++} )`;if(a.interpolationType){const t=null!==a.interpolationSampling?`, ${a.interpolationSampling} )`:" )";e+=` @interpolate( ${a.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(a.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${a.name} : ${this.getType(a.type)}`)}else"vertex"===e&&!1===i.includes(a)&&i.push(a)}}const n=this.getBuiltins(e);n&&t.push(n);const i=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+i):i}isCustomStruct(e){const t=e.value,n=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==n.structTypeNode,r=n.value&&n.value.array&&"number"==typeof n.value.itemSize&&n.value.array.length>n.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<f32>";else if(!0===r.isDepthTexture)a=t.compatibilityMode&&null===r.compareFunction?`texture${l}_2d<f32>`:`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<private> 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<private> 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<private> varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${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<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${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;e<l.length;e++)65535===l[e]&&(l[e]=4294967295);if(n.array=l,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&3===n.itemSize)o=4;else if(n.itemSize>1&&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;i<n.count;i++)t.set(l.subarray(i*e,i*e+e),i*o);(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(n.itemSize=o,n.array=t),l=t,r._itemSize=e,r._paddedItemSize=o}const u=l.byteLength,c=u+(4-u%4)%4;LU.label=n.name,LU.size=c,LU.usage=t,LU.mappedAtCreation=!0,s=a.createBuffer(LU),LU.reset(),new l.constructor(s.getMappedRange()).set(l),s.unmap(),r.buffer=s}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,i=n.device,r=n.get(t),s=n.get(t).buffer;let a=t.array;const o=r._itemSize,l=r._paddedItemSize;if(void 0!==l){a=new a.constructor(t.count*l);for(let e=0;e<t.count;e++)a.set(t.array.subarray(e*o,e*o+o),e*l);(t.isStorageBufferAttribute||t.isStorageInstancedBufferAttribute)&&(t.array=a)}const u=t.updateRanges;if(0===u.length)i.queue.writeBuffer(s,0,a,0);else{const e=Gt(a),n=e?1:a.BYTES_PER_ELEMENT;for(let t=0,r=u.length;t<r;t++){const r=u[t];let c,h;if(void 0!==l){const e=Math.floor(r.start/o);c=e*l*n,h=(Math.ceil((r.start+r.count)/o)-e)*l*n}else c=r.start*n,h=r.count*n;const d=c*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(s,d,a,c,h)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let e=0;e<t.length;e++){const i=t[e],r=i.array.BYTES_PER_ELEMENT,s=this._getBufferAttribute(i);let a=n.get(s);if(void 0===a){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?bI:yI):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?bI:yI,i.itemSize>1&&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;o<l;o++){const l=s[o],u=s[o+1],c=l.start+l.count;if(void 0!==u&&u.start===c)continue;const h=a*t,d=(c-a)*t,p=h*(e?i.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(r,p,i,h,d),void 0!==u&&(a=u.start)}}}createBindGroupIndex(e,t){const n=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0];kU.label="bindingCameraIndex_"+r,kU.size=16,kU.usage=i;const s=n.createBuffer(kU);kU.reset(),n.queue.writeBuffer(s,0,e,0),BU.label="bindGroupCameraIndex_"+r,BU.layout=t,BU.entries.push({binding:0,resource:{buffer:s}});const a=n.createBindGroup(BU);return BU.reset(),a}createBindGroup(e,t){const n=this.backend,i=n.device;let r=0;BU.label="bindGroup_"+e.name,BU.layout=t;for(const t of e.bindings){if(t.isUniformBuffer){const e=n.get(t);BU.entries.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=n.get(t.attribute).buffer;BU.entries.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=n.get(t.texture);let s;if(void 0!==e.externalTexture)s=i.importExternalTexture({source:e.externalTexture});else{const n=t.store?1:e.texture.mipLevelCount,i=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${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;e<t.length;e++){const i=t[e],r=c.getTextureFormatGPU(i);let s;if(null!==n)if(!0!==this.backend.compatibilityMode){const e=n.getBlendMode(i.name);6===e.blending?s=f:0!==e.blending&&(s=this._getBlending(e))}else Kt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),s=f;else s=f;_.push({format:r,blend:s,writeMask:g})}}else{const t=c.getCurrentColorFormat(e.context);_.push({format:t,blend:f,writeMask:g})}const v=l.get(a).module,y=l.get(o).module,b=this._getPrimitiveState(n,r,i),x=this._getDepthCompare(i),S=c.getCurrentDepthStencilFormat(e.context),T=this._getSampleCount(e.context);jU.bindGroupLayouts=d;const M=u.createPipelineLayout(jU);jU.reset(),XU.label=`renderPipeline_${i.name||i.type}_${i.id}`,XU.vertex=Object.assign({},v,{buffers:p}),XU.fragment=Object.assign({},y,{targets:_}),XU.primitive=b,XU.multisample.count=T,XU.multisample.alphaToCoverageEnabled=i.alphaToCoverage&&T>1,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;e<t.length;e++)if(!0===this.get(t[e]).externalTexture)return!0;return!1}_getExternalMSAATextures(e,t,n){const i=this.utils.getSampleCount(e.sampleCount);if(1===i){if(void 0!==t.msaaTextures){for(const e of t.msaaTextures)e.destroy();t.msaaTextures=void 0}return null}const r=e.renderTarget,s=r.width,a=r.height,o=t.format;if(void 0===t.msaaTextures||t.msaaTextures.length!==n||t.msaaWidth!==s||t.msaaHeight!==a||t.msaaSamples!==i||t.msaaFormat!==o){if(void 0!==t.msaaTextures)for(const e of t.msaaTextures)e.destroy();hF.size.width=s,hF.size.height=a,hF.sampleCount=i,hF.format=o,hF.usage=GPUTextureUsage.RENDER_ATTACHMENT,t.msaaTextures=[];for(let e=0;e<n;e++)hF.label=r.texture.name+"-msaa-"+e,t.msaaTextures.push(this.device.createTexture(hF));hF.reset(),t.msaaWidth=s,t.msaaHeight=a,t.msaaSamples=i,t.msaaFormat=o}return t.msaaTextures}_createExternalTextureViews(e,t){const n=[],i=e.camera,r=t.xrViewDescriptors,s=Math.max(r?.length||0,e.activeCubeFace+1,1),a=this._getExternalMSAATextures(e,t,s);if(r&&null!==i&&!0===i.isArrayCamera)for(let i=0;i<r.length;i++){const s=t.texture.createView(r[i]);n.push({view:null!==a?a[i].createView():s,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?s:void 0,depthSlice:void 0})}else{const i=e.activeCubeFace,r=t.texture.createView({dimension:fI,baseArrayLayer:i,arrayLayerCount:1});n.push({view:null!==a?a[i].createView():r,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?r:void 0,depthSlice:void 0})}return n}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,i=this.get(n),r=this._hasExternalTexture(e);let s=i.descriptors;(void 0===s||i.width!==n.width||i.height!==n.height||i.samples!==n.samples||r)&&(s={},i.descriptors=s);const a=e.getCacheKey();let o=s[a];if(void 0===o||r){const t=e.textures,r=[];let l;const u=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const s=this.get(t[i]);if(!0!==s.externalTexture){if(dF.label=`colorAttachment_${i}`,dF.baseMipLevel=e.activeMipmapLevel,dF.mipLevelCount=1,dF.baseArrayLayer=e.activeCubeFace,dF.arrayLayerCount=1,dF.dimension=fI,n.isRenderTarget3D)l=e.activeCubeFace,dF.baseArrayLayer=0,dF.dimension=_I;else if(n.isRenderTarget&&t[i].image.depth>1)if(!0===u){const t=e.camera.cameras;for(let e=0;e<t.length;e++){dF.baseArrayLayer=e,dF.arrayLayerCount=1,dF.dimension=fI;const t=s.texture.createView(dF),i=s.msaaTextures?.[e];r.push({view:void 0!==i?i.createView():t,resolveTarget:void 0!==i&&!0===n.resolveColorBuffer?t:void 0,depthSlice:void 0})}}else dF.dimension=mI;if(!0!==u){const t=s.texture.createView(dF);let i,a;void 0!==s.msaaTexture?(i=s.msaaTexture.createView(),a=!0===n.resolveColorBuffer?t:void 0):void 0!==s.msaaTextures?(i=s.msaaTextures[e.activeCubeFace].createView(),a=!0===n.resolveColorBuffer?t:void 0):(i=t,a=void 0),r.push({view:i,resolveTarget:a,depthSlice:l})}dF.reset()}else r.push(...this._createExternalTextureViews(e,s))}const c=[];for(let e=0;e<r.length;e++){const t=r[e],n=new II;n.view=t.view,n.depthSlice=t.depthSlice,n.resolveTarget=t.resolveTarget,c.push(n)}if(o={textureViews:r,colorAttachments:c,descriptor:new UI},e.depth){const t=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(dF.dimension=fI,dF.arrayLayerCount=1,dF.baseArrayLayer=e.activeCubeFace);const n=new eF,i=t.msaaTextures?.[e.activeCubeFace];n.view=void 0!==i?i.createView():t.texture.createView(dF),o.depthStencilAttachment=n,dF.reset()}s[a]=o,i.width=n.width,i.height=n.height,i.samples=n.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const l=o.descriptor;l.reset();for(let e=0;e<o.colorAttachments.length;e++){const n=o.colorAttachments[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),n.loadOp=t.loadOp||SP,n.storeOp=t.storeOp||bP,n.clearValue=i,l.colorAttachments.push(n)}return o.depthStencilAttachment&&(l.depthStencilAttachment=o.depthStencilAttachment),l}beginRender(e){const t=this.get(e),n=this.device,i=e.occlusionQueryCount;let r,s;i>0?(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;n<t.length;n++){const i=t[n];if(e.clearColor||l||h){const t=e.mrt?e.mrt.getClearColor(e.textures[n].name):null;null!==t?i.clearValue=t:0===n?i.clearValue=e.clearColorValue:(tF.r=0,tF.g=0,tF.b=0,tF.a=1,i.clearValue=tF),i.loadOp=TP}else i.loadOp=SP;i.storeOp=l?xP:bP}}else{const t=s.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=TP):t.loadOp=SP,t.storeOp=bP}e.depth&&(e.clearDepth||u?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=TP):a.depthLoadOp=SP,a.depthStoreOp=u?xP:bP),e.stencil&&(e.clearStencil||c?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=TP):a.stencilLoadOp=SP,a.stencilStoreOp=c?xP:bP),rF.label="renderContext_"+e.id;const d=n.createCommandEncoder(rF);if(rF.reset(),!0===this._isRenderCameraDepthArray(e)){const n=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===n.length?this._updateArrayCameraLayerDescriptors(e,t,s,n):this._createArrayCameraLayerDescriptors(e,t,s,n),this._createArrayCameraBundleEncoders(e,t),t.arrayCameraRenderStages=[],t.currentPass=null}else{t.bundleEncoders=void 0,t.bundleSets=void 0,t.arrayCameraRenderStages=void 0;const n=d.beginRenderPass(s);t.currentPass=n,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=s,t.encoder=d,t.renderBundles=[],this._resetRenderContextData(t)}_resetRenderContextData(e){e.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},void 0===e.currentBlendColor&&(e.currentBlendColor=new yi),e.currentBlendColor.setRGB(0,0,0),e.currentBlendAlpha=0,e.currentStencilRef=0}_createArrayCameraBundleEncoders(e,t){const n=e.camera.cameras;t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<n.length;i++){const n=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(n),t.bundleSets.push(r)}}_finishArrayCameraBundleEncoders(e){const t=[];for(const n of e.bundleEncoders)t.push(n.finish());return t}_createArrayCameraLayerDescriptors(e,t,n,i){const r=n.depthStencilAttachment;t.layerDescriptors=[];const s=this.get(e.depthTexture);s.viewCache||(s.viewCache=[]);for(let a=0;a<i.length;a++){const i=n.colorAttachments[0],o=n.colorAttachments[a],l=new II;l.view=o.view,l.depthSlice=o.depthSlice,l.resolveTarget=o.resolveTarget,l.loadOp=i.loadOp,l.storeOp=i.storeOp,l.clearValue=i.clearValue;const u=new UI;if(u.label=n.label,u.occlusionQuerySet=n.occlusionQuerySet,u.timestampWrites=n.timestampWrites,u.colorAttachments.push(l),n.depthStencilAttachment){const t=a;if(!s.viewCache[t]){const e=s.msaaTextures?.[t];void 0!==e?s.viewCache[t]=e.createView():(dF.dimension=fI,dF.baseArrayLayer=a,dF.arrayLayerCount=1,s.viewCache[t]=s.texture.createView(dF)),dF.reset()}const n=new eF;n.view=s.viewCache[t],n.depthLoadOp=r.depthLoadOp||TP,n.depthStoreOp=r.depthStoreOp||bP,n.depthClearValue=r.depthClearValue||1,e.stencil&&(n.stencilLoadOp=r.stencilLoadOp,n.stencilStoreOp=r.stencilStoreOp,n.stencilClearValue=r.stencilClearValue),u.depthStencilAttachment=n}else{const e=new eF;e.view=r.view,e.depthLoadOp=r.depthLoadOp,e.depthStoreOp=r.depthStoreOp,e.depthClearValue=r.depthClearValue,e.depthReadOnly=r.depthReadOnly,e.stencilLoadOp=r.stencilLoadOp,e.stencilStoreOp=r.stencilStoreOp,e.stencilClearValue=r.stencilClearValue,e.stencilReadOnly=r.stencilReadOnly,u.depthStencilAttachment=e}t.layerDescriptors.push(u)}}_updateArrayCameraLayerDescriptors(e,t,n,i){const r=e.renderTarget,s=e.sampleCount>1&&!1===r?.storeMultisampledDepthBuffer,a=e.sampleCount>1&&!1===r?.storeMultisampledStencilBuffer;for(let r=0;r<i.length;r++){const i=t.layerDescriptors[r],o=n.colorAttachments[0],l=n.colorAttachments[r],u=i.colorAttachments[0];if(u.view=l.view,u.resolveTarget=l.resolveTarget,u.depthSlice=l.depthSlice,u.loadOp=o.loadOp,u.storeOp=o.storeOp,u.clearValue=o.clearValue,i.depthStencilAttachment){const t=i.depthStencilAttachment;e.depth&&(e.clearDepth||s?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=TP):t.depthLoadOp=SP),e.stencil&&(e.clearStencil||a?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=TP):t.stencilLoadOp=SP)}}}finishRender(e){const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&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;n<t.layerDescriptors.length;n++){const s=t.layerDescriptors[n],a=s.colorAttachments.map(e=>e.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;t<i.length;t++){const d=i[t],p=d.bundles[n],f=t===i.length-1;for(let e=0;e<s.colorAttachments.length;e++){const n=s.colorAttachments[e];n.loadOp=0===t?a[e]:SP,n.storeOp=f?o[e]:bP}e.depth&&(s.depthStencilAttachment.depthLoadOp=0===t?l:SP,s.depthStencilAttachment.depthStoreOp=f?u:bP),e.stencil&&(s.depthStencilAttachment.stencilLoadOp=0===t?c:SP,s.depthStencilAttachment.stencilStoreOp=f?h:bP);const m=r.beginRenderPass(s);if(e.viewport){const{x:t,y:n,width:i,height:r,minDepth:s,maxDepth:a}=e.viewportValue;m.setViewport(t,n,i,r,s,a)}if(e.scissor){const{x:t,y:n,width:i,height:r}=e.scissorValue;m.setScissorRect(t,n,i,r)}if(m.executeBundles([p]),m.end(),void 0!==d.framebufferCopy){const{texture:e,sourceGPU:t,destinationGPU:i,rectangle:s,generateMipmaps:a}=d.framebufferCopy;this._copyFramebufferToTexture(r,e,t,i,s,n,a)}}for(let e=0;e<s.colorAttachments.length;e++)s.colorAttachments[e].loadOp=a[e],s.colorAttachments[e].storeOp=o[e];e.depth&&(s.depthStencilAttachment.depthLoadOp=l,s.depthStencilAttachment.depthStoreOp=u),e.stencil&&(s.depthStencilAttachment.stencilLoadOp=c,s.depthStencilAttachment.stencilStoreOp=h)}}else t.currentPass&&t.currentPass.end();if(n>0){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;e<t.length;e++){const n=t[e];!0===n.generateMipmaps&&this.textureUtils.generateMipmaps(n)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const r=n.getMappedRange(),s=new BigUint64Array(r);for(let t=0;t<i.length;t++){const n=i[t];void 0!==n&&s[t]===BigInt(0)&&e.add(n)}n.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:r,height:s,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(n,i,r,s,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:r,height:s}=e.scissorValue;t.setScissorRect(n,i,r,s)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,n,i=null){const r=this.device,s=this.renderer;let a,o,l,u=[];if(e){const e=this.getClearColor();tF.r=e.r,tF.g=e.g,tF.b=e.b,tF.a=e.a}if(null===i){o=s.depth,l=s.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){u=t.colorAttachments;const e=u[0];e.clearValue=tF,e.loadOp=TP,e.storeOp=bP}(o||l)&&(a=t.depthStencilAttachment)}else{o=i.depth,l=i.stencil;const r={loadOp:e?TP:SP,clearValue:e?tF:void 0};o&&(r.depthLoadOp=t?TP:SP,r.depthClearValue=t?s.getClearDepth():void 0,r.depthStoreOp=bP),l&&(r.stencilLoadOp=n?TP:SP,r.stencilClearValue=n?s.getClearStencil():void 0,r.stencilStoreOp=bP);const c=this._getRenderPassDescriptor(i,r);u=c.colorAttachments,a=c.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=TP,a.depthClearValue=s.getClearDepth(),a.depthStoreOp=bP):(a.depthLoadOp=SP,a.depthStoreOp=bP)),l&&a&&(n?(a.stencilLoadOp=TP,a.stencilClearValue=s.getClearStencil(),a.stencilStoreOp=bP):(a.stencilLoadOp=SP,a.stencilStoreOp=bP)),rF.label="clear";const c=r.createCommandEncoder(rF);rF.reset();c.beginRenderPass({colorAttachments:u,depthStencilAttachment:a}).end(),CI(r,c.finish())}beginCompute(e){const t=this.get(e),n="computeGroup_"+e.id;sF.label=n,rF.label=n,this.initTimestampQuery(Ft,this.getTimestampUID(e),sF),t.cmdEncoderGPU=this.device.createCommandEncoder(rF),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(sF),t.currentPipeline=null,rF.reset(),sF.reset()}compute(e,t,n,i,r=null){const s=this.get(t),a=this.get(e),{passEncoderGPU:o}=a,l=this.get(i).pipeline;a.currentPipeline!==l&&(o.setPipeline(l),a.currentPipeline=l);for(let e=0,t=n.length;e<t;e++){const t=n[e],i=this.get(t);o.setBindGroup(e,i.group)}if(null===r&&(r=t.dispatchSize||t.count),r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void o.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===s.dispatchSize||s.count!==e){s.dispatchSize=[0,1,1],s.count=e;const n=t.workgroupSize;let i=n[0];for(let e=1;e<n.length;e++)i*=n[e];const a=Math.ceil(e/i),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),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;e<t;e++){if(e===u)continue;const t=r[e],n=this.get(t).group;m[e]!==n&&(o.setBindGroup(e,n),m[e]=n)}if(!0===f&&l.index!==p){const e=this.get(p).buffer,t=p.array instanceof Uint16Array?RP:CP;o.setIndexBuffer(e,t),l.index=p}for(let e=0,t=s.length;e<t;e++){const t=s[e];if(l.attributes[e]!==t){const n=this.get(t).buffer;o.setVertexBuffer(e,n),l.attributes[e]=t}}if(!0===d.stencil&&!0===h.stencilWrite&&n.currentStencilRef!==h.stencilRef&&(o.setStencilReference(h.stencilRef),n.currentStencilRef=h.stencilRef),5===h.blending&&void 0!==o.setBlendConstant){const e=h.blendColor,t=h.blendAlpha;!1!==e.equals(n.currentBlendColor)&&t===n.currentBlendAlpha||(nF.r=e.r,nF.g=e.g,nF.b=e.b,nF.a=t,o.setBlendConstant(nF),n.currentBlendColor.copy(e),n.currentBlendAlpha=t)}if(!0===c.isBatchedMesh){const e=c._multiDrawStarts,n=c._multiDrawCounts,i=c._multiDrawCount,r=c._multiDrawBytesPerElement;for(let s=0;s<i;s++)!0===f?o.drawIndexed(n[s],1,e[s]/r,0,s):o.draw(n[s],1,e[s],s),t.update(c,n[s],1)}else if(!0===f){const{vertexCount:n,instanceCount:i,firstVertex:r}=a,s=e.getIndirect();if(null!==s){const t=this.get(s).buffer,n=e.getIndirectOffset(),i=Array.isArray(n)?n:[n];for(let e=0;e<i.length;e++)o.drawIndexedIndirect(t,i[e])}else o.drawIndexed(n,i,r,0,0);t.update(c,n,i)}else{const{vertexCount:n,instanceCount:i,firstVertex:r}=a,s=e.getIndirect();if(null!==s){const t=this.get(s).buffer,n=e.getIndirectOffset(),i=Array.isArray(n)?n:[n];for(let e=0;e<i.length;e++)o.drawIndirect(t,i[e])}else o.draw(n,i,r,0);t.update(c,n,i)}}draw(e,t){const{object:n,context:i,pipeline:r}=e,s=this.get(i),a=this.get(r),o=a.pipeline;if(!0===a.error)return;const l=e.getDrawParameters();if(null===l)return;const u=e.getBindings(),c=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){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<r;i++){n[0]=i;const{layoutGPU:r}=e.layout,s=this.bindingUtils.createBindGroupIndex(n,r);t.push(s)}r.indexesGPU=t}const d=i.renderTarget,p=null===d||!0===d.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,f=h?u.indexOf(h):-1;for(let h=0,d=a.length;h<d;h++){const d=a[h];if(n.layers.test(d.layers)){const n=d.viewport;let a=s.currentPass,m=s.currentSets;const g=void 0!==s.bundleEncoders;if(g){a=s.bundleEncoders[h],m=s.bundleSets[h]}if(n&&!g&&a.setViewport(Math.floor(n.x*p),Math.floor(n.y*p),Math.floor(n.width*p),Math.floor(n.height*p),i.viewportValue.minDepth,i.viewportValue.maxDepth),-1!==f&&r.indexesGPU){const e=r.indexesGPU[h];m.bindingGroups[f]!==e&&(a.setBindGroup(f,e),m.bindingGroups[f]=e)}this._draw(e,t,s,o,u,c,l,a,m,f)}}}else if(s.currentPass){if(s.currentPass instanceof GPURenderBundleEncoder)!0===n.occlusionTest&&Kt("WebGPUBackend: Occlusion queries can not be recorded into render bundles.");else if(void 0!==s.occlusionQuerySet){const e=s.lastOcclusionObject;e!==n&&(null!==e&&!0===e.occlusionTest&&(s.currentPass.endOcclusionQuery(),s.occlusionQueryIndex++),!0===n.occlusionTest&&(s.currentPass.beginOcclusionQuery(s.occlusionQueryIndex),s.occlusionQueryObjects[s.occlusionQueryIndex]=n),s.lastOcclusionObject=n)}this._draw(e,t,s,o,u,c,l,s.currentPass,s.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:i}=e,r=this.utils,s=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),o=r.getCurrentColorFormat(e.context),l=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(n,i),c=n.isMesh&&n.matrixWorld.determinantAffine()<0;let h=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.polygonOffset===i.polygonOffset&&t.polygonOffsetFactor===i.polygonOffsetFactor&&t.polygonOffsetUnits===i.polygonOffsetUnits&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===s&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===l&&t.primitiveTopology===u&&t.frontFaceCW===c&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.polygonOffset=i.polygonOffset,t.polygonOffsetFactor=i.polygonOffsetFactor,t.polygonOffsetUnits=i.polygonOffsetUnits,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=s,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=l,t.primitiveTopology=u,t.frontFaceCW=c,t.clippingContextCacheKey=e.clippingContextCacheKey,h=!0),h}getRenderCacheKey(e){const{object:t,material:n}=e,i=this.utils,r=e.context,s=t.isMesh&&t.matrixWorld.determinantAffine()<0;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.polygonOffset,n.polygonOffsetFactor,n.polygonOffsetUnits,n.side,n.alphaToCoverage,s,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,r,s){return this.textureUtils.copyTextureToBuffer(e,t,n,i,r,s)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new JU(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);lF.querySet=i.querySet,lF.beginningOfPassWriteIndex=r,lF.endOfPassWriteIndex=r+1,n.timestampWrites=lF}createNodeBuilder(e,t){return new PU(e,t)}createProgram(e){const t=this.get(e);oF.label=e.stage+(""!==e.name?`_${e.name}`:""),oF.code=e.code,t.module={module:this.device.createShaderModule(oF),entryPoint:"main"},oF.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t,n=null){this.pipelineUtils.createComputePipeline(e,t,n)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const n=this.get(e),i=n.currentPass.finish();this.get(t).bundleGPU=i,n.currentSets=n._currentSets,n.currentPass=n._currentPass,n._currentPass=null,n._currentSets=null}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){const t=this.get(e);if(void 0===t.buffer){const n=e.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=[];e.visibility&hP.VERTEX&&r.push("vertex"),e.visibility&hP.FRAGMENT&&r.push("fragment"),e.visibility&hP.COMPUTE&&r.push("compute");const s=`(${r.join(",")})`;iF.label=`bindingBuffer${e.id}_${e.name}_${s}`,iF.size=n,iF.usage=i;const a=this.device.createBuffer(iF);iF.reset(),t.buffer=a}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return void 0!==SI[e]&&(e=SI[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){let a=0,o=0,l=0,u=0,c=0,h=0,d=e.image.width,p=e.image.height,f=1;null!==n&&(!0===n.isBox3?(u=n.min.x,c=n.min.y,h=n.min.z,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=n.max.z-n.min.z):(u=n.min.x,c=n.min.y,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=1)),null!==i&&(a=i.x,o=i.y,l=i.z||0),rF.label="copyTextureToTexture_"+e.id+"_"+t.id;const m=this.device.createCommandEncoder(rF);rF.reset();const g=this.get(e).texture,_=this.get(t).texture;uF.texture=g,uF.mipLevel=r,uF.origin.x=u,uF.origin.y=c,uF.origin.z=h,cF.texture=_,cF.mipLevel=s,cF.origin.x=a,cF.origin.y=o,cF.origin.z=l,pF.width=d,pF.height=p,pF.depthOrArrayLayers=f,m.copyTextureToTexture(uF,cF,pF),uF.reset(),cF.reset(),pF.reset(),CI(this.device,m.finish()),0===s&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const i=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const s=this.get(e).texture;if(r.format!==s.format)return void Yt("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,s.format);if(!0===this._isRenderCameraDepthArray(t)){const a=this._finishArrayCameraBundleEncoders(i);return i.arrayCameraRenderStages.push({bundles:a,framebufferCopy:{texture:e,sourceGPU:r,destinationGPU:s,rectangle:{x:n.x,y:n.y,z:n.z,w:n.w},generateMipmaps:e.generateMipmaps}}),void this._createArrayCameraBundleEncoders(t,i)}let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):(rF.label="copyFramebufferToTexture_"+e.id,a=this.device.createCommandEncoder(rF),rF.reset()),this._copyFramebufferToTexture(a,e,r,s,n),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=SP;t.depth&&(e.depthStencilAttachment.depthLoadOp=SP),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=SP),i.currentPass=a.beginRenderPass(e),this._resetRenderContextData(i),t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else CI(this.device,a.finish())}_copyFramebufferToTexture(e,t,n,i,r,s=0,a=t.generateMipmaps){uF.texture=n,uF.origin.x=r.x,uF.origin.y=r.y,uF.origin.z=s,cF.texture=i,pF.width=r.z,pF.height=r.w,e.copyTextureToTexture(uF,cF,pF),uF.reset(),cF.reset(),pF.reset(),a&&this.textureUtils.generateMipmaps(t,e)}hasCompatibility(e){return void 0!==this._compatibility[e]?this._compatibility[e]:super.hasCompatibility(e)}async dispose(){if(await super.dispose(),this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class mF extends wa{constructor(e,t,n,i,r,s){super(e,t,n,i,r,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class gF extends wa{constructor(e,t,n,i,r,s){super(e,t,n,i,r,s),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class _F extends HC{constructor(){super(),this.addMaterial(dM,"MeshPhongMaterial"),this.addMaterial(Qw,"MeshStandardMaterial"),this.addMaterial(eE,"MeshPhysicalMaterial"),this.addMaterial(rE,"MeshToonMaterial"),this.addMaterial(iM,"MeshBasicMaterial"),this.addMaterial(cM,"MeshLambertMaterial"),this.addMaterial(HT,"MeshNormalMaterial"),this.addMaterial(oE,"MeshMatcapMaterial"),this.addMaterial(DT,"LineBasicMaterial"),this.addMaterial(UT,"LineDashedMaterial"),this.addMaterial(fE,"PointsMaterial"),this.addMaterial(hE,"SpriteMaterial"),this.addMaterial(vE,"ShadowMaterial"),this.addLight(ER,Aa),this.addLight(mC,Na),this.addLight(wC,La),this.addLight(_C,wa),this.addLight(fC,Pa),this.addLight(gC,ha),this.addLight(yC,Ia),this.addLight(vC,mF),this.addLight(xC,gF),this.addToneMapping(TA,1),this.addToneMapping(MA,2),this.addToneMapping(wA,3),this.addToneMapping(AA,4),this.addToneMapping(PA,6),this.addToneMapping(LA,7)}}class vF extends dN{constructor(e={}){let t;e.forceWebGL?t=aP:(t=fF,e.getFallback=()=>(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;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId)return void this._pointers.splice(t,1)}_trackPointer(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new dn,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){this.noZoom&&this.noPan||(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function zF(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function VF(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function GF(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),0===this._pointers.length&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function HF(e){this._removePointer(e)}function WF(){!1!==this.enabled&&(this.keyState=TF,window.addEventListener("keydown",this._onKeyDown))}function jF(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===TF&&(e.code!==this.keys[MF]||this.noRotate?e.code!==this.keys[wF]||this.noZoom?e.code!==this.keys[EF]||this.noPan||(this.keyState=EF):this.keyState=wF:this.keyState=MF))}function $F(e){let r;switch(e.button){case 0:r=this.mouseButtons.LEFT;break;case 1:r=this.mouseButtons.MIDDLE;break;case 2:r=this.mouseButtons.RIGHT;break;default:r=-1}switch(r){case n:this.state=wF;break;case t:this.state=MF;break;case i:this.state=EF;break;default:this.state=TF}const s=this.keyState!==TF?this.keyState:this.state;s!==MF||this.noRotate?s!==wF||this.noZoom?s!==EF||this.noPan||(this._panStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(bF)}function XF(e){const t=this.keyState!==TF?this.keyState:this.state;t!==MF||this.noRotate?t!==wF||this.noZoom?t!==EF||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY))}function qF(){this.state=TF,this.dispatchEvent(xF)}function YF(e){if(!1!==this.enabled&&!0!==this.noZoom){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=.025*e.deltaY;break;case 1:this._zoomStart.y-=.01*e.deltaY;break;default:this._zoomStart.y-=25e-5*e.deltaY}this.dispatchEvent(bF),this.dispatchEvent(xF)}}function KF(e){!1!==this.enabled&&e.preventDefault()}function ZF(e){if(this._trackPointer(e),1===this._pointers.length)this.state=AF,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=RF;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,i)),this._panEnd.copy(this._panStart)}this.dispatchEvent(bF)}function QF(e){if(this._trackPointer(e),1===this._pointers.length)this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(n*n+i*i);const r=(e.pageX+t.x)/2,s=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,s))}}function JF(e){switch(this._pointers.length){case 0:this.state=TF;break;case 1:this.state=AF,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=RF;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){const e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent(xF)}const eO={type:"change"},tO={type:"start"},nO={type:"end"},iO=new Ur,rO=new Ar,sO=Math.cos(70*hn.DEG2RAD),aO=new fn,oO=2*Math.PI,lO=-1,uO=0,cO=1,hO=2,dO=3,pO=4,fO=5,mO=6,gO=1e-6;class _O extends Xa{constructor(e,s=null){super(e,s),this.state=lO,this.target=new fn,this.cursor=new fn,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:t,MIDDLE:n,RIGHT:i},this.touches={ONE:r,TWO:a},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new fn,this._lastQuaternion=new pn,this._lastTargetPosition=new fn,this._quat=(new pn).setFromUnitVectors(e.up,new fn(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new ja,this._sphericalDelta=new ja,this._scale=1,this._panOffset=new fn,this._rotateStart=new dn,this._rotateEnd=new dn,this._rotateDelta=new dn,this._panStart=new dn,this._panEnd=new dn,this._panDelta=new dn,this._dollyStart=new dn,this._dollyEnd=new dn,this._dollyDelta=new dn,this._dollyDirection=new fn,this._mouse=new dn,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=yO.bind(this),this._onPointerDown=vO.bind(this),this._onPointerUp=bO.bind(this),this._onContextMenu=AO.bind(this),this._onMouseWheel=TO.bind(this),this._onKeyDown=MO.bind(this),this._onTouchStart=wO.bind(this),this._onTouchMove=EO.bind(this),this._onMouseDown=xO.bind(this),this._onMouseMove=SO.bind(this),this._interceptControlDown=RO.bind(this),this._interceptControlUp=CO.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,this.domElement.style.cursor="grab"===e?"grab":"auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1});this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=lO,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){null!==this._domElementKeyEvents&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(eO),this.update(),this.state=lO}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;aO.copy(t).sub(this.target),aO.applyQuaternion(this._quat),this._spherical.setFromVector3(aO),this.autoRotate&&this.state===lO&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=oO:n>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))<sO?this.object.lookAt(this.target):(rO.setFromNormalAndCoplanarPoint(this.object.up,this.target),iO.intersectPlane(rO,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,!!(r||this._lastPosition.distanceToSquared(this.object.position)>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;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new dn,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function vO(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e),"grab"===this._cursorStyle&&(this.domElement.style.cursor="grabbing")))}function yO(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function bO(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(nO),this.state=lO,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function xO(e){let r;switch(e.button){case 0:r=this.mouseButtons.LEFT;break;case 1:r=this.mouseButtons.MIDDLE;break;case 2:r=this.mouseButtons.RIGHT;break;default:r=-1}switch(r){case n:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=cO;break;case t:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=hO}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=uO}break;case i:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=uO}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=hO}break;default:this.state=lO}this.state!==lO&&this.dispatchEvent(tO)}function SO(e){switch(this.state){case uO:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case cO:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case hO:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function TO(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===lO&&(e.preventDefault(),this.dispatchEvent(tO),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(nO))}function MO(e){!1!==this.enabled&&this._handleKeyDown(e)}function wO(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case r:if(!1===this.enableRotate)return;this._handleTouchStartRotate(e),this.state=dO;break;case s:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=pO;break;default:this.state=lO}break;case 2:switch(this.touches.TWO){case a:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=fO;break;case o:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=mO;break;default:this.state=lO}break;default:this.state=lO}this.state!==lO&&this.dispatchEvent(tO)}function EO(e){switch(this._trackPointer(e),this.state){case dO:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case pO:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case fO:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case mO:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=lO}}function AO(e){!1!==this.enabled&&e.preventDefault()}function RO(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function CO(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const NO={type:"change"},PO=1e-6,LO=new pn;class DO extends Xa{constructor(e,t=null){super(e,t),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new fn(0,0,0),this._rotationVector=new fn(0,0,0),this._lastQuaternion=new pn,this._lastPosition=new fn,this._status=0,this._onKeyDown=IO.bind(this),this._onKeyUp=UO.bind(this),this._onPointerMove=OO.bind(this),this._onPointerDown=FO.bind(this),this._onPointerUp=BO.bind(this),this._onPointerCancel=kO.bind(this),this._onContextMenu=zO.bind(this),null!==t&&this.connect(t)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,n=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),LO.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(LO),(this._lastPosition.distanceToSquared(t.position)>PO||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;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),void 0===e&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let t=0,i=this.passes.length;t<i;t++){const i=this.passes[t];if(!1!==i.enabled){if(i.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),i.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),i.needsSwap){if(n){const t=this.renderer.getContext(),n=this.renderer.state.buffers.stencil;n.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),n.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==XO&&(i instanceof XO?n=!0:i instanceof qO&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new dn);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,(e=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(n,i),this.renderTarget2.setSize(n,i);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class KO extends GO{constructor(e,t,n=null,i=null,r=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=i,this.clearAlpha=r,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new yi}render(e,t,n){const i=e.autoClear;let r,s;e.autoClear=!1,null!==this.overrideMaterial&&(s=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=s),e.autoClear=i}}function ZO(){return ZO=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ZO.apply(null,arguments)}function QO(e,t){return QO=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},QO(e,t)}function JO(e){return JO=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},JO(e)}function eB(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(eB=function(){return!!e})()}function tB(e){var t="function"==typeof Map?new Map:void 0;return tB=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(eB())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return n&&QO(r,n.prototype),r}(e,arguments,JO(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),QO(n,e)},tB(e)}var nB={1:"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",2:"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",3:"Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",4:"Couldn't generate valid rgb string from %s, it returned %s.\n\n",5:"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",6:"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",7:"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",8:"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",9:"Please provide a number of steps to the modularScale helper.\n\n",10:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",11:'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n',12:'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n',13:'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n',14:'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',15:'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',16:"You must provide a template to this method.\n\n",17:"You passed an unsupported selector state to this method.\n\n",18:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",19:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",20:"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:"fontFace expects a name of a font-family.\n\n",24:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",25:"fontFace expects localFonts to be an array.\n\n",26:"fontFace expects fileFormats to be an array.\n\n",27:"radialGradient requries at least 2 color-stops to properly render.\n\n",28:"Please supply a filename to retinaImage() as the first argument.\n\n",29:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",32:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",33:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",34:"borderRadius expects a radius value as a string or number as the second argument.\n\n",35:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',36:"Property must be a string value.\n\n",37:"Syntax Error at %s.\n\n",38:"Formula contains a function that needs parentheses at %s.\n\n",39:"Formula is missing closing parenthesis at %s.\n\n",40:"Formula has too many closing parentheses at %s.\n\n",41:"All values in a formula must have the same unit or be unitless.\n\n",42:"Please provide a number of steps to the modularScale helper.\n\n",43:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",44:"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",45:"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",46:"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",47:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",48:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",49:"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",50:"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",51:"Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",52:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",53:"fontFace expects localFonts to be an array.\n\n",54:"fontFace expects fileFormats to be an array.\n\n",55:"fontFace expects a name of a font-family.\n\n",56:"linearGradient requries at least 2 color-stops to properly render.\n\n",57:"radialGradient requries at least 2 color-stops to properly render.\n\n",58:"Please supply a filename to retinaImage() as the first argument.\n\n",59:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:"Property must be a string value.\n\n",62:"borderRadius expects a radius value as a string or number as the second argument.\n\n",63:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',64:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",65:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",66:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",67:"You must provide a template to this method.\n\n",68:"You passed an unsupported selector state to this method.\n\n",69:'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n',70:'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n',71:'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n',72:'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n',73:"Please provide a valid CSS variable.\n\n",74:"CSS variable not found and no default was provided.\n\n",75:"important requires a valid style object, got a %s instead.\n\n",76:"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",77:'remToPx expects a value in "rem" but you provided it in "%s".\n\n',78:'base must be set in "px" or "%" but you set it in "%s".\n'};function iB(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var i,r=t[0],s=[];for(i=1;i<t.length;i+=1)s.push(t[i]);return s.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var rB=function(e){function t(t){var n;if("production"===process.env.NODE_ENV)n=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this;else{for(var i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];n=e.call(this,iB.apply(void 0,[nB[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,QO(e,t)}(t,e),t}(tB(Error));function sB(e){return Math.round(255*e)}function aB(e,t,n){return sB(e)+","+sB(t)+","+sB(n)}function oB(e,t,n,i){if(void 0===i&&(i=aB),0===t)return i(n,n,n);var r=(e%360+360)%360/60,s=(1-Math.abs(2*n-1))*t,a=s*(1-Math.abs(r%2-1)),o=0,l=0,u=0;r>=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<r?6:0);break;case i:t=(r-n)/l+2;break;default:t=(n-i)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:u,lightness:o,alpha:e.alpha}:{hue:t,saturation:u,lightness:o}}(_B(e))}var yB=function(e){return 7===e.length&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function bB(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function xB(e){return bB(Math.round(255*e))}function SB(e,t,n){return yB("#"+xB(e)+xB(t)+xB(n))}function TB(e,t,n){return oB(e,t,n,SB)}function MB(e,t,n){if("number"==typeof e&&"number"==typeof t&&"number"==typeof n)return yB("#"+bB(e)+bB(t)+bB(n));if("object"==typeof e&&void 0===t&&void 0===n)return yB("#"+bB(e.red)+bB(e.green)+bB(e.blue));throw new rB(6)}function wB(e,t,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=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=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),UB=function(){return performance.now()},FB=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];null===(e=s._group)||void 0===e||e.remove(s),s._group=this,this._tweens[s.getId()]=s,this._tweensAddedDuringUpdate[s.getId()]=s}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,i=e;n<i.length;n++){var r=i[n];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=UB()),void 0===t&&(t=!0);var n=Object.keys(this._tweens);if(0!==n.length)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<n.length;i++){var r=this._tweens[n[i]],s=!t;r&&!1===r.update(e,s)&&!t&&this.remove(r)}n=Object.keys(this._tweensAddedDuringUpdate)}},e}(),OB={Linear:function(e,t){var n=e.length-1,i=n*t,r=Math.floor(i),s=OB.Utils.Linear;return t<0?s(e[0],e[1],i):t>1?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;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){u=!1,console.warn("Found invalid interpolation list. Skipping.");break}c.push(p)}u&&(n[s]=c)}if("object"!==l&&!o||!a||u)(void 0===t[s]||r)&&(t[s]=a),o||(t[s]*=1),i[s]=u?n[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var f=a;for(var m in f)t[s][m]=f[m];i[s]=o?[]:{};var g=n[s];if(!this._isDynamic){var _={};for(var m in g)_[m]=g[m];n[s]=g=_}this._setupProperties(f,t[s],g,i[s],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=UB()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=UB()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=IB.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=OB.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,n){var i,r,s=this;if(void 0===t&&(t=UB()),void 0===n&&(n=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!n)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),l=this._duration+this._repeat*o,u=function(){if(0===s._duration)return 1;if(a>l)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<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,n,i){for(var r in n)if(void 0!==t[r]){var s=t[r]||0,a=n[r],o=Array.isArray(e[r]),l=Array.isArray(a);!o&&l?e[r]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[r],s,a,i):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[r]=s+(a-s)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof n?this._valuesStartRepeat[e]+parseFloat(n):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();BB.nextId;var VB=kB;VB.getAll.bind(VB),VB.removeAll.bind(VB),VB.add.bind(VB),VB.remove.bind(VB),VB.update.bind(VB);var GB="http://www.w3.org/1999/xhtml",HB={svg:"http://www.w3.org/2000/svg",xhtml:GB,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function WB(e){var t=e+="",n=t.indexOf(":");return n>=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;o<u;++o)(a=t[o])?(a.__data__=s[o],i[o]=a):n[o]=new rk(e,s[o]);for(;o<l;++o)(a=t[o])&&(r[o]=a)}function ak(e,t,n,i,r,s,a){var o,l,u,c=new Map,h=t.length,d=s.length,p=new Array(h);for(o=0;o<h;++o)(l=t[o])&&(p[o]=u=a.call(l,l.__data__,o,t)+"",c.has(u)?r[o]=l:c.set(u,l));for(o=0;o<d;++o)u=a.call(e,s[o],o,s)+"",(l=c.get(u))?(i[o]=l,l.__data__=s[o],c.delete(u)):n[o]=new rk(e,s[o]);for(o=0;o<h;++o)(l=t[o])&&c.get(p[o])===l&&(r[o]=l)}function ok(e){return e.__data__}function lk(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function uk(e,t){return e<t?-1:e>t?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<r;)n.add(t[i])}function Ak(e,t){for(var n=Mk(e),i=-1,r=t.length;++i<r;)n.remove(t[i])}function Rk(e){return function(){Ek(this,e)}}function Ck(e){return function(){Ak(this,e)}}function Nk(e,t){return function(){(t.apply(this,arguments)?Ek:Ak)(this,e)}}function Pk(){this.textContent=""}function Lk(e){return function(){this.textContent=e}}function Dk(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function Ik(){this.innerHTML=""}function Uk(e){return function(){this.innerHTML=e}}function Fk(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function Ok(){this.nextSibling&&this.parentNode.appendChild(this)}function Bk(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function kk(){return null}function zk(){var e=this.parentNode;e&&e.removeChild(this)}function Vk(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Gk(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Hk(e){return function(){var t=this.__on;if(t){for(var n,i=0,r=-1,s=t.length;i<s;++i)n=t[i],e.type&&n.type!==e.type||n.name!==e.name?t[++r]=n:this.removeEventListener(n.type,n.listener,n.options);++r?t.length=r:delete this.__on}}}function Wk(e,t,n){return function(){var i,r=this.__on,s=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((i=r[a]).type===e.type&&i.name===e.name)return this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=s,i.options=n),void(i.value=t);this.addEventListener(e.type,s,n),i={type:e.type,name:e.name,value:t,listener:s,options:n},r?r.push(i):this.__on=[i]}}function jk(e,t,n){var i=gk(e),r=i.CustomEvent;"function"==typeof r?r=new r(t,n):(r=i.document.createEvent("Event"),n?(r.initEvent(t,n.bubbles,n.cancelable),r.detail=n.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function $k(e,t){return function(){return jk(this,e,t)}}function Xk(e,t){return function(){return jk(this,e,t.apply(this,arguments))}}rk.prototype={constructor:rk,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},wk.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var 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<n;++r)for(var s,a,o=t[r],l=o.length,u=i[r]=new Array(l),c=0;c<l;++c)(s=o[c])&&(a=e.call(s,s.__data__,c,o))&&("__data__"in s&&(a.__data__=s.__data__),u[c]=a);return new Yk(i,this._parents)},selectAll:function(e){e="function"==typeof e?ZB(e):function(e){return null==e?KB:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,n=t.length,i=[],r=[],s=0;s<n;++s)for(var a,o=t[s],l=o.length,u=0;u<l;++u)(a=o[u])&&(i.push(e.call(a,a.__data__,u,o)),r.push(a));return new Yk(i,r)},selectChild:function(e){return this.select(null==e?ek:function(e){return function(){return JB.call(this.children,e)}}("function"==typeof e?e:QB(e)))},selectChildren:function(e){return this.selectAll(null==e?nk:function(e){return function(){return tk.call(this.children,e)}}("function"==typeof e?e:QB(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r<n;++r)for(var s,a=t[r],o=a.length,l=i[r]=[],u=0;u<o;++u)(s=a[u])&&e.call(s,s.__data__,u,a)&&l.push(s);return new Yk(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,ok);var n=t?ak:sk,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var s=r.length,a=new Array(s),o=new Array(s),l=new Array(s),u=0;u<s;++u){var c=i[u],h=r[u],d=h.length,p=lk(e.call(c,c&&c.__data__,u,i)),f=p.length,m=o[u]=new Array(f),g=a[u]=new Array(f);n(c,h,m,g,l[u]=new Array(d),p,t);for(var _,v,y=0,b=0;y<f;++y)if(_=m[y]){for(y>=b&&(b=y+1);!(v=g[b])&&++b<f;);_._next=v||null}}return(a=new Yk(a,i))._enter=o,a._exit=l,a},enter:function(){return new Yk(this._enter||this._groups.map(ik),this._parents)},exit:function(){return new Yk(this._exit||this._groups.map(ik),this._parents)},join:function(e,t,n){var i=this.enter(),r=this,s=this.exit();return"function"==typeof e?(i=e(i))&&(i=i.selection()):i=i.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==n?s.remove():n(s),i&&r?i.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,i=t._groups,r=n.length,s=i.length,a=Math.min(r,s),o=new Array(r),l=0;l<a;++l)for(var u,c=n[l],h=i[l],d=c.length,p=o[l]=new Array(d),f=0;f<d;++f)(u=c[f]||h[f])&&(p[f]=u);for(;l<r;++l)o[l]=n[l];return new Yk(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var i,r=e[t],s=r.length-1,a=r[s];--s>=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;s<i;++s){for(var a,o=n[s],l=o.length,u=r[s]=new Array(l),c=0;c<l;++c)(a=o[c])&&(u[c]=a);u.sort(t)}return new Yk(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i=e[t],r=0,s=i.length;r<s;++r){var a=i[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,n=0,i=t.length;n<i;++n)for(var r,s=t[n],a=0,o=s.length;a<o;++a)(r=s[a])&&e.call(r,r.__data__,a,s);return this},attr:function(e,t){var n=WB(e);if(arguments.length<2){var i=this.node();return n.local?i.getAttributeNS(n.space,n.local):i.getAttribute(n)}return this.each((null==t?n.local?hk:ck:"function"==typeof t?n.local?mk:fk:n.local?pk:dk)(n,t))},style:function(e,t,n){return arguments.length>1?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<s;)if(!i.contains(n[r]))return!1;return!0}return this.each(("function"==typeof t?Nk:t?Rk:Ck)(n,t))},text:function(e){return arguments.length?this.each(null==e?Pk:("function"==typeof e?Dk:Lk)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?Ik:("function"==typeof e?Fk:Uk)(e)):this.node().innerHTML},raise:function(){return this.each(Ok)},lower:function(){return this.each(Bk)},append:function(e){var t="function"==typeof e?e:XB(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var n="function"==typeof e?e:XB(e),i=null==t?kk:"function"==typeof t?t:YB(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),i.apply(this,arguments)||null)})},remove:function(){return this.each(zk)},clone:function(e){return this.select(e?Gk:Vk)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var i,r,s=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");return n>=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;i<a;++i)this.each(o(s[i],t,n));return this}var o=this.node().__on;if(o)for(var l,u=0,c=o.length;u<c;++u)for(i=0,l=o[u];i<a;++i)if((r=s[i]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?Xk:$k)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i,r=e[t],s=0,a=r.length;s<a;++s)(i=r[s])&&(yield i)}};var Kk,Zk,Qk,Jk,ez,tz,nz,iz,rz,sz,az,oz,lz,uz,cz,hz={},dz=[],pz=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,fz=Array.isArray;function mz(e,t){for(var n in t)e[n]=t[n];return e}function gz(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function _z(e,t,n,i,r){var s={type:e,props:t,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++Qk:r,__i:-1,__u:0};return null==r&&null!=Zk.vnode&&Zk.vnode(s),s}function vz(e){return e.children}function yz(e,t){this.props=e,this.context=t}function bz(e,t){if(null==t)return e.__?bz(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?bz(e):null}function xz(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,i=[],r=[],s=mz({},t);s.__v=t.__v+1,Zk.vnode&&Zk.vnode(s),Lz(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,i,null==n?bz(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,Iz(i,s,r),t.__e=t.__=null,s.__e!=n&&Sz(s)}}function Sz(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),Sz(e)}function Tz(e){(!e.__d&&(e.__d=!0)&&ez.push(e)&&!Mz.__r++||tz!=Zk.debounceRendering)&&((tz=Zk.debounceRendering)||nz)(Mz)}function Mz(){try{for(var e,t=1;ez.length;)ez.length>t&&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;h<v;h++)null!=(p=n.__k[h])&&(d=-1!=p.__i&&_[p.__i]||hz,p.__i=h,g=Lz(e,p,d,r,s,a,o,l,u,c),f=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&Oz(d.ref,null,p),c.push(p.ref,p.__c||f,p)),null==m&&null!=f&&(m=f),4&p.__u?(l=Az(p,l,e),d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==g?l=g:f&&(l=f.nextSibling),p.__u&=-7);return n.__e=m,l}function Ez(e,t,n,i,r){var s,a,o,l,u,c=n.length,h=c,d=0;for(e.__k=new Array(r),s=0;s<r;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[s]=_z(null,a,null,null,null):fz(a)?a=e.__k[s]=_z(vz,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?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--:r<c&&d++),"function"!=typeof a.type&&(a.__u|=4)):u!=l&&(u==l-1?d--:u==l+1?d++:(u>l?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s<c;s++)null!=(o=n[s])&&!(2&o.__u)&&(o.__e==i&&(i=bz(o)),Bz(o,o));return i}function Az(e,t,n){var i,r;if("function"==typeof e.type){for(i=e.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=e,t=Az(i[r],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=bz(e)),t=n.insertBefore(e.__e,t||null));do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function Rz(e,t,n,i){var r,s,a,o=e.key,l=e.type,u=t[n],c=null!=u&&!(2&u.__u);if(null===u&&null==o||c&&o==u.key&&l==u.type)return n;if(i>(c?1:0))for(r=n-1,s=n+1;r>=0||s<t.length;)if(null!=(u=t[a=r>=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]<n[az])return;return n(Zk.event?Zk.event(t):t)}}}function Lz(e,t,n,i,r,s,a,o,l,u){var c,h,d,p,f,m,g,_,v,y,b,x,S,T,M,w,E=t.type;if(void 0!==t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[o=t.__e=n.__e]),(c=Zk.__b)&&c(t);e:if("function"==typeof E){h=a.length;try{if(v=t.props,y=E.prototype&&E.prototype.render,b=(c=E.contextType)&&i[c.__c],x=c?b?b.props.value:c.__:i,n.__c?_=(d=t.__c=n.__c).__=d.__E:(y?t.__c=d=new E(v,x):(t.__c=d=new yz(v,x),d.constructor=E,d.render=kz),b&&b.sub(d),d.state||(d.state={}),d.__n=i,p=d.__d=!0,d.__h=[],d._sb=[]),y&&null==d.__s&&(d.__s=d.state),y&&null!=E.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=mz({},d.__s)),mz(d.__s,E.getDerivedStateFromProps(v,d.__s))),f=d.props,m=d.state,d.__v=t,p)y&&null==E.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),y&&null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(y&&null==E.getDerivedStateFromProps&&v!==f&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(v,x),t.__v==n.__v||!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(v,d.__s,x)){t.__v!=n.__v&&(d.props=v,d.state=d.__s,d.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),dz.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&a.push(d),o=bz(n);break e}null!=d.componentWillUpdate&&d.componentWillUpdate(v,d.__s,x),y&&null!=d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(f,m,g)})}if(d.context=x,d.props=v,d.__P=e,d.__e=!1,S=Zk.__r,T=0,y)d.state=d.__s,d.__d=!1,S&&S(t),c=d.render(d.props,d.state,d.context),dz.push.apply(d.__h,d._sb),d._sb=[];else do{d.__d=!1,S&&S(t),c=d.render(d.props,d.state,d.context),d.state=d.__s}while(d.__d&&++T<25);d.state=d.__s,null!=d.getChildContext&&(i=mz(mz({},i),d.getChildContext())),y&&!p&&null!=d.getSnapshotBeforeUpdate&&(g=d.getSnapshotBeforeUpdate(f,m)),M=null!=c&&c.type===vz&&null==c.key?Uz(c.props.children):c,o=wz(e,fz(M)?M:[M],t,n,i,r,s,a,o,l,u),d.base=t.__e,t.__u&=-161,d.__h.length&&a.push(d),_&&(d.__E=d.__=null)}catch(e){if(a.length=h,t.__v=null,l||null!=s){if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;null!=s&&(s[s.indexOf(o)]=null),t.__e=o}else if(null!=s)for(w=s.length;w--;)gz(s[w])}else t.__e=n.__e;null==t.__k&&(t.__k=n.__k||[]),e.then||Dz(t),Zk.__e(e,t,n)}}else null==s&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):o=t.__e=Fz(n.__e,t,n,i,r,s,a,l,u);return(c=Zk.diffed)&&c(t),128&t.__u?void 0:o}function Dz(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Dz))}function Iz(e,t,n){for(var i=0;i<n.length;i++)Oz(n[i],n[++i],n[++i]);Zk.__c&&Zk.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){Zk.__e(e,t.__v)}})}function Uz(e){return"object"!=typeof e||null==e||e.__b>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;u<s.length;u++)if((p=s[u])&&"setAttribute"in p==!!v&&(v?p.localName==v:3==p.nodeType)){e=p,s[u]=null;break}if(null==e){if(null==v)return document.createTextNode(_);e=document.createElementNS(r,v,_.is&&_),o&&(Zk.__m&&Zk.__m(t,s),o=!1),s=null}if(null==v)g===_||o&&e.data==_||(e.data=_);else{if(s="textarea"==v&&null!=_.defaultValue?null:s&&Kk.call(e.childNodes),!o&&null!=s)for(g={},u=0;u<e.attributes.length;u++)g[(p=e.attributes[u]).name]=p.value;for(u in g)p=g[u],"dangerouslySetInnerHTML"==u?h=p:"children"==u||u in _||"value"==u&&"defaultValue"in _||"checked"==u&&"defaultChecked"in _||Nz(e,u,null,p,r);for(u in _)p=_[u],"children"==u?d=p:"dangerouslySetInnerHTML"==u?c=p:"value"==u?f=p:"checked"==u?m=p:o&&"function"!=typeof p||g[u]===p||Nz(e,u,p,g[u],r);if(c)o||h&&(c.__html==h.__html||c.__html==e.innerHTML)||(e.innerHTML=c.__html),t.__k=[];else if(h&&(e.innerHTML=""),wz("template"==t.type?e.content:e,fz(d)?d:[d],t,n,i,"foreignObject"==v?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&bz(n,0),o,l),null!=s)for(u=s.length;u--;)gz(s[u]);o&&"textarea"!=v||(u="value","progress"==v&&null==f?e.removeAttribute("value"):null!=f&&(f!==e[u]||"progress"==v&&!f||"option"==v&&f!=g[u])&&Nz(e,u,f,g[u],r),u="checked",null!=m&&m!=e[u]&&Nz(e,u,m,g[u],r))}return e}function Oz(e,t,n){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){Zk.__e(e,n)}}function Bz(e,t,n){var i,r;if(Zk.unmount&&Zk.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||Oz(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){Zk.__e(e,t)}i.base=i.__P=i.__n=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&Bz(i[r],t,n||"function"!=typeof e.type);n||gz(e.__e),e.__c=e.__=e.__e=void 0}function kz(e,t,n){return this.constructor(e,n)}function zz(e,t,n){var i,r,s;t==document&&(t=document.documentElement),Zk.__&&Zk.__(e,t),i=!1?null:t.__k,r=[],s=[],Lz(t,e=t.__k=function(e,t,n){var i,r,s,a={};for(s in t)"key"==s?i=t[s]:"ref"==s?r=t[s]:a[s]=t[s];if(arguments.length>2&&(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);n<t;n++)i[n]=e[n];return i}function Hz(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wz(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,i)}return n}function jz(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Gz(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Gz(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function $z(e){return $z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$z(e)}Kk=dz.slice,Zk={__e:function(e,t,n,i){for(var r,s,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((s=r.constructor)&&null!=s.getDerivedStateFromError&&(r.setState(s.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},Qk=0,Jk=function(e){return null!=e&&void 0===e.constructor},yz.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=mz({},this.state),"function"==typeof e&&(e=e(mz({},n),this.props)),e&&mz(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),Tz(this))},yz.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Tz(this))},yz.prototype.render=vz,ez=[],nz="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,iz=function(e,t){return e.__v.__b-t.__v.__b},Mz.__r=0,rz=Math.random().toString(8),sz="__d"+rz,az="__a"+rz,oz=/(PointerCapture)$|Capture$/i,lz=0,uz=Pz(!1),cz=Pz(!0);var Xz=function(e){if("object"!==$z(e))return e;var t,n=Vz(e);n.props&&(n.props=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Wz(Object(n),!0).forEach(function(t){Hz(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Wz(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({},n.props),null!=n&&null!==(t=n.props)&&void 0!==t&&t.children&&(n.props.children=Array.isArray(n.props.children)?n.props.children.map(Xz):Xz(n.props.children)));return n};!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))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var qz=Pd({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var n=(arguments.length>2&&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;t<e.length;t++)if(!0===e[t].isOutputPass){qt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}w.setEffects(e||[])}else Yt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.")},this.getCurrentViewport=function(e){return e.copy(O)},this.getViewport=function(e){return e.copy(X)},this.setViewport=function(e,t,n,i){e.isVector4?X.set(e.x,e.y,e.z,e.w):X.set(e,t,n,i),ue.viewport(O.copy(X).multiplyScalar(W).round())},this.getScissor=function(e){return e.copy(q)},this.setScissor=function(e,t,n,i){e.isVector4?q.set(e.x,e.y,e.z,e.w):q.set(e,t,n,i),ue.scissor(B.copy(q).multiplyScalar(W).round())},this.getScissorTest=function(){return Y},this.setScissorTest=function(e){ue.setScissorTest(Y=e)},this.setOpaqueSort=function(e){j=e},this.setTransparentSort=function(e){$=e},this.getClearColor=function(e){return e.copy(Ue.getClearColor())},this.setClearColor=function(){Ue.setClearColor(...arguments)},this.getClearAlpha=function(){return Ue.getClearAlpha()},this.setClearAlpha=function(){Ue.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let i=0;if(e){let e=!1;if(null!==I){const t=I.texture.format;e=g.has(t)}if(e){const e=I.texture.type,t=_.has(e),n=Ue.getClearColor(),i=Ue.getClearAlpha(),r=n.r,s=n.g,a=n.b;t?(v[0]=r,v[1]=s,v[2]=a,v[3]=i,Ge.clearBufferuiv(Ge.COLOR,0,v)):(y[0]=r,y[1]=s,y[2]=a,y[3]=i,Ge.clearBufferiv(Ge.COLOR,0,y))}else i|=Ge.COLOR_BUFFER_BIT}t&&(i|=Ge.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(i|=Ge.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),0!==i&&Ge.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),R=e},this.dispose=function(){n.removeEventListener("webglcontextlost",$e,!1),n.removeEventListener("webglcontextrestored",Xe,!1),n.removeEventListener("webglcontextcreationerror",qe,!1),Ue.dispose(),Ae.dispose(),Re.dispose(),pe.dispose(),_e.dispose(),Me.dispose(),ze.dispose(),Ve.dispose(),we.dispose(),je.dispose(),je.removeEventListener("sessionstart",Qe),je.removeEventListener("sessionend",Je),et.stop()},this.renderBufferDirect=function(e,t,n,i,r,s){null===t&&(t=ne);const a=r.isMesh&&r.matrixWorld.determinantAffine()<0,o=function(e,t,n,i,r){!0!==t.isScene&&(t=ne);me.resetTextureUnits();const s=t.fog,a=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?t.environment:null,o=null===I?E.outputColorSpace:!0===I.isXRRenderTarget?I.texture.colorSpace:Sn.workingColorSpace,l=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,u=_e.get(i.envMap||a,l),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!n.attributes.tangent&&(!!i.normalMap||i.anisotropy>0),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;t<n;t++){const n=e[t];if(null!==n.texture&&n.boundingBox.containsPoint(b))return n}return null}(S.state.lightProbeGridArray,r);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(M||F!==e){ue.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),C.setValue(Ge,"projectionMatrix",e.projectionMatrix),C.setValue(Ge,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(Ge,ee.setFromMatrixPosition(e.matrixWorld)),oe.logarithmicDepthBuffer&&C.setValue(Ge,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(Ge,"isOrthographic",!0===e.isOrthographicCamera),F!==e&&(F=e,w=!0,A=!0)}v.needsLights&&(y.state.sunShadowMap.length>0&&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<n;t++){const n=e[t];Ve.update(n,T),Ve.bind(n,T)}}return T}(e,t,n,i,r);ue.setMaterial(i,a);let l=n.index,u=1;if(!0===i.wireframe){if(l=Te.getWireframeAttribute(n),void 0===l)return;u=2}const c=n.drawRange,h=n.attributes.position;let d=c.start*u,p=(c.start+c.count)*u;null!==s&&(d=Math.max(d,s.start*u),p=Math.min(p,(s.start+s.count)*u)),null!==l?(d=Math.max(d,0),p=Math.min(p,l.count)):null!=h&&(d=Math.max(d,0),p=Math.min(p,h.count));const f=p-d;if(f<0||f===1/0)return;let m;ze.setup(r,i,o,n,l);let g=Oe;if(null!==l&&(m=Se.get(l),g=Be,g.setIndex(m)),r.isMesh)!0===i.wireframe?(ue.setLineWidth(i.wireframeLinewidth*se()),g.setMode(Ge.LINES)):g.setMode(Ge.TRIANGLES);else if(r.isLine){let e=i.linewidth;void 0===e&&(e=1),ue.setLineWidth(e*se()),r.isLineSegments?g.setMode(Ge.LINES):r.isLineLoop?g.setMode(Ge.LINE_LOOP):g.setMode(Ge.LINE_STRIP)}else r.isPoints?g.setMode(Ge.POINTS):r.isSprite&&g.setMode(Ge.TRIANGLES);if(r.isBatchedMesh)if(ae.get("WEBGL_multi_draw"))g.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);else{const e=r._multiDrawStarts,t=r._multiDrawCounts,n=r._multiDrawCount,s=l?Se.get(l).bytesPerElement:1,a=pe.get(i).currentProgram.getUniforms();for(let i=0;i<n;i++)a.setValue(Ge,"_gl_DrawID",i),g.render(e[i]/s,t[i])}else if(r.isInstancedMesh)g.renderInstances(d,f,r.count);else if(n.isInstancedBufferGeometry){const e=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,t=Math.min(n.instanceCount,e);g.renderInstances(d,f,t)}else g.render(d,f)},this.compile=function(e,t,n=null){null===n&&(n=e),null!==R&&R.renderStart(e,t,n),S=Re.get(n),S.init(t),M.push(S),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(S.pushLight(e),e.castShadow&&S.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(S.pushLight(e),e.castShadow&&S.pushShadow(e))}),S.setupLights(),null!==R&&R.updateLights(S.state.lightsArray),Q=this.localClippingEnabled,Z=Ce.init(this.clippingPlanes,Q),!0===Z&&Ce.setGlobalState(this.clippingPlanes,t),null!==R&&De.render(S.state.shadowsArray,n,t);const i=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const r=e.material;if(r)if(Array.isArray(r))for(let s=0;s<r.length;s++){const a=r[s];Ke(a,n,t,e),i.add(a)}else Ke(r,n,t,e),i.add(r)}),S=M.pop(),null!==R&&R.renderEnd(),i},this.compileAsync=function(e,t,n=null){const i=this.compile(e,t,n);return new Promise(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;a<o;a++){const o=i[a],l=s[o.materialIndex];l&&l.visible&&x.push(e,r,l,n,te.z,o,t)}}else s.visible&&x.push(e,r,s,n,te.z,null,t)}const r=e.children;for(let e=0,s=r.length;e<s;e++)tt(r[e],t,n,i)}function nt(e,t,n,i){const{opaque:r,transmissive:s,transparent:a}=e;S.setupLightsView(n),!0===Z&&Ce.setGlobalState(E.clippingPlanes,n),i&&ue.viewport(O.copy(i)),r.length>0&&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;r<s;r++){const s=t[r],{object:a,geometry:o,material:l,group:u}=s;if(2===l.side&&a.layers.test(i.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,st(a,n,i,o,l,u),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(me.updateMultisampleRenderTarget(r),me.updateRenderTargetMipmap(r))}E.setRenderTarget(o,l,u),E.setClearColor(z,V),void 0!==h&&(i.viewport=h),E.toneMapping=c}function rt(e,t,n){const i=!0===t.isScene?t.overrideMaterial:null;for(let r=0,s=e.length;r<s;r++){const s=e[r],{object:a,geometry:o,group:l}=s;let u=s.material;!0===u.allowOverride&&null!==i&&(u=i),a.layers.test(n.layers)&&st(a,t,n,o,u,l)}}function st(e,t,n,i,r,s){null!==R&&r.isNodeMaterial&&R.setObject(e,r),e.onBeforeRender(E,t,n,i,r,s),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),r.onBeforeRender(E,t,n,i,e,s),!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,r.needsUpdate=!0,E.renderBufferDirect(n,t,i,r,e,s),r.side=0,r.needsUpdate=!0,E.renderBufferDirect(n,t,i,r,e,s),r.side=2):E.renderBufferDirect(n,t,i,r,e,s),e.onAfterRender(E,t,n,i,r,s)}function at(e,t,n){!0!==t.isScene&&(t=ne);const i=pe.get(e),r=S.state.lights,s=S.state.shadowsArray,a=r.state.version,o=we.getParameters(e,r.state,s,t,n,S.state.lightProbeGridArray),l=we.getProgramCacheKey(o);let u=i.programs;i.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,i.fog=t.fog;const c=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;i.envMap=_e.get(e.envMap||i.environment,c),i.envMapRotation=null!==i.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===u&&(e.addEventListener("dispose",Ye),u=new Map,i.programs=u);let h=u.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return lt(e,o),h}else o.uniforms=we.getUniforms(e),null!==R&&e.isNodeMaterial&&R.build(e,n,o),e.onBeforeCompile(o,E),h=we.acquireProgram(o,l),u.set(l,h),i.uniforms=o.uniforms;const d=i.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(d.clippingPlanes=Ce.uniform),lt(e,o),i.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),i.lightsStateVersion=a,i.needsLights&&(d.ambientLightColor.value=r.state.ambient,d.lightProbe.value=r.state.probe,d.sunLights.value=r.state.sun,d.sunLightShadows.value=r.state.sunShadow,d.directionalLights.value=r.state.directional,d.directionalLightShadows.value=r.state.directionalShadow,d.spotLights.value=r.state.spot,d.spotLightShadows.value=r.state.spotShadow,d.rectAreaLights.value=r.state.rectArea,d.ltc_1.value=r.state.rectAreaLTC1,d.ltc_2.value=r.state.rectAreaLTC2,d.pointLights.value=r.state.point,d.pointLightShadows.value=r.state.pointShadow,d.hemisphereLights.value=r.state.hemi,d.sunShadowMatrix.value=r.state.sunShadowMatrix,d.sunShadowCascade.value=r.state.sunShadowCascade,d.directionalShadowMatrix.value=r.state.directionalShadowMatrix,d.spotLightMatrix.value=r.state.spotLightMatrix,d.spotLightMap.value=r.state.spotLightMap,d.pointShadowMatrix.value=r.state.pointShadowMatrix),i.lightProbeGrid=S.state.lightProbeGridArray.length>0,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;t<s;t++){it(n,i,e,r[t])}re&&Ue.render(e);for(let t=0,n=r.length;t<n;t++){const n=r[t];nt(x,e,n,n.viewport)}}else i.length>0&&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;t<e.textures.length;t++){const r=pe.get(e.textures[t]);Ge.framebufferTextureLayer(Ge.FRAMEBUFFER,Ge.COLOR_ATTACHMENT0+t,r.__webglTexture,n,i)}}else if(null!==e&&0!==n){const t=pe.get(e.texture);Ge.framebufferTexture2D(Ge.FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,Ge.TEXTURE_2D,t.__webglTexture,n)}U=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void Yt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=pe.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){ue.bindFramebuffer(Ge.FRAMEBUFFER,l);try{const a=e.textures[o],l=a.format,u=a.type;e.textures.length>1&&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<l;n++)M&&(Ge.framebufferTextureLayer(Ge.READ_FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,pe.get(e).__webglTexture,r,h+n),Ge.framebufferTextureLayer(Ge.DRAW_FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,pe.get(t).__webglTexture,s,f+n)),Ge.blitFramebuffer(u,c,a,o,d,p,a,o,Ge.DEPTH_BUFFER_BIT,Ge.NEAREST);ue.bindFramebuffer(Ge.READ_FRAMEBUFFER,null),ue.bindFramebuffer(Ge.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||pe.has(e)){const n=pe.get(e),i=pe.get(t);ue.bindFramebuffer(Ge.READ_FRAMEBUFFER,N),ue.bindFramebuffer(Ge.DRAW_FRAMEBUFFER,P);for(let e=0;e<l;e++)M?Ge.framebufferTextureLayer(Ge.READ_FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,n.__webglTexture,r,h+e):Ge.framebufferTexture2D(Ge.READ_FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,Ge.TEXTURE_2D,n.__webglTexture,r),w?Ge.framebufferTextureLayer(Ge.DRAW_FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,i.__webglTexture,s,f+e):Ge.framebufferTexture2D(Ge.DRAW_FRAMEBUFFER,Ge.COLOR_ATTACHMENT0,Ge.TEXTURE_2D,i.__webglTexture,s),0!==r?Ge.blitFramebuffer(u,c,a,o,d,p,a,o,Ge.COLOR_BUFFER_BIT,Ge.NEAREST):w?Ge.copyTexSubImage3D(v,s,d,p,f+e,u,c,a,o):Ge.copyTexSubImage2D(v,s,d,p,u,c,a,o);ue.bindFramebuffer(Ge.READ_FRAMEBUFFER,null),ue.bindFramebuffer(Ge.DRAW_FRAMEBUFFER,null)}else w?e.isDataTexture||e.isData3DTexture?Ge.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m.data):t.isCompressedArrayTexture?Ge.compressedTexSubImage3D(v,s,d,p,f,a,o,l,g,m.data):Ge.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m):e.isDataTexture?Ge.texSubImage2D(Ge.TEXTURE_2D,s,d,p,a,o,g,_,m.data):e.isCompressedTexture?Ge.compressedTexSubImage2D(Ge.TEXTURE_2D,s,d,p,m.width,m.height,g,m.data):Ge.texSubImage2D(Ge.TEXTURE_2D,s,d,p,a,o,g,_,m);ue.pixelStorei(Ge.UNPACK_ROW_LENGTH,y),ue.pixelStorei(Ge.UNPACK_IMAGE_HEIGHT,b),ue.pixelStorei(Ge.UNPACK_SKIP_PIXELS,x),ue.pixelStorei(Ge.UNPACK_SKIP_ROWS,S),ue.pixelStorei(Ge.UNPACK_SKIP_IMAGES,T),0===s&&t.generateMipmaps&&Ge.generateMipmap(v),ue.unbindTexture()},this.initRenderTarget=function(e){void 0===pe.get(e).__webglFramebuffer&&me.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?me.setTextureCube(e,0):e.isData3DTexture?me.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?me.setTexture2DArray(e,0):me.setTexture2D(e,0),ue.unbindTexture()},this.resetState=function(){L=0,D=0,I=null,ue.reset(),ze.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return It}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Sn._getDrawingBufferColorSpace(e),t.unpackColorSpace=Sn._getUnpackColorSpace()}},Scene:xi,PerspectiveCamera:Ta,Raycaster:Ga,SRGBColorSpace:vt,TextureLoader:class extends oa{constructor(e){super(e)}load(e,t,n,i){const r=new Ln,s=new ua(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){r.image=e,r.needsUpdate=!0,void 0!==t&&t(r)},n,i),r}},Vector2:dn,Vector3:fn,Box3:Fi,Color:yi,Mesh:qr,SphereGeometry:Os,MeshBasicMaterial:Fr,BackSide:1,Timer:Ba};var Qz=Pd({props:{width:{default:window.innerWidth,onChange(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange(e,t,n){isNaN(e)&&(t.height=n)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:()=>!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});