diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 840dc445342dae..1af05e8ff8965b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,13 +56,17 @@ jobs: with: node-version: 24 cache: 'npm' + - name: Install Vulkan drivers and xvfb + run: | + sudo apt-get update + sudo apt-get install -y mesa-vulkan-drivers xvfb - name: Install dependencies run: npm ci - name: Build run: npm run build-module - name: === E2E testing === - run: npm run test-e2e + run: xvfb-run -a npm run test-e2e - name: Upload output screenshots uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 if: always() diff --git a/build/three.cjs b/build/three.cjs index fbda092404baf5..48f6dee5e1ef79 100644 --- a/build/three.cjs +++ b/build/three.cjs @@ -37295,10 +37295,7 @@ function cloneUniforms( src ) { const property = src[ u ][ p ]; - if ( property && ( property.isColor || - property.isMatrix3 || property.isMatrix4 || - property.isVector2 || property.isVector3 || property.isVector4 || - property.isTexture || property.isQuaternion ) ) { + if ( isThreeObject( property ) ) { if ( property.isRenderTargetTexture ) { @@ -37313,7 +37310,23 @@ function cloneUniforms( src ) { } else if ( Array.isArray( property ) ) { - dst[ u ][ p ] = property.slice(); + if ( isThreeObject( property[ 0 ] ) ) { + + const clonedProperty = []; + + for ( let i = 0, l = property.length; i < l; i ++ ) { + + clonedProperty[ i ] = property[ i ].clone(); + + } + + dst[ u ][ p ] = clonedProperty; + + } else { + + dst[ u ][ p ] = property.slice(); + + } } else { @@ -37357,6 +37370,15 @@ function mergeUniforms( uniforms ) { } +function isThreeObject( property ) { + + return ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ); + +} + function cloneUniformsGroups( src ) { const dst = []; @@ -44051,7 +44073,6 @@ class FileLoader extends Loader { * @param {function(any)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. * @param {onErrorCallback} [onError] - Executed when errors occur. - * @return {any|undefined} The cached resource if available. */ load( url, onLoad, onProgress, onError ) { @@ -44075,7 +44096,7 @@ class FileLoader extends Loader { }, 0 ); - return cached; + return; } @@ -49525,6 +49546,9 @@ class ImageBitmapLoader extends Loader { * Sets the given loader options. The structure of the object must match the `options` parameter of * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap). * + * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with + * different options will return the cached result of the first request. + * * @param {Object} options - The loader options to set. * @return {ImageBitmapLoader} A reference to this image bitmap loader. */ @@ -49543,7 +49567,6 @@ class ImageBitmapLoader extends Loader { * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Unsupported in this loader. * @param {onErrorCallback} onError - Executed when errors occur. - * @return {ImageBitmap|undefined} The image bitmap. */ load( url, onLoad, onProgress, onError ) { @@ -49581,8 +49604,6 @@ class ImageBitmapLoader extends Loader { scope.manager.itemEnd( url ); - return imageBitmap; - } } ); @@ -49600,7 +49621,7 @@ class ImageBitmapLoader extends Loader { }, 0 ); - return cached; + return; } @@ -49625,8 +49646,6 @@ class ImageBitmapLoader extends Loader { scope.manager.itemEnd( url ); - return imageBitmap; - } ).catch( function ( e ) { if ( onError ) onError( e ); @@ -49757,11 +49776,21 @@ class AudioLoader extends Loader { const bufferCopy = buffer.slice( 0 ); const context = AudioContext.getContext(); + + const decodeUrl = url + '#decode'; + scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378 + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { onLoad( audioBuffer ); + scope.manager.itemEnd( decodeUrl ); - } ).catch( handleError ); + } ).catch( function ( e ) { + + handleError( e ); + scope.manager.itemEnd( decodeUrl ); + + } ); } catch ( e ) { diff --git a/build/three.core.js b/build/three.core.js index 4fffe356a1e2d4..dc72370bc441ac 100644 --- a/build/three.core.js +++ b/build/three.core.js @@ -37315,10 +37315,7 @@ function cloneUniforms( src ) { const property = src[ u ][ p ]; - if ( property && ( property.isColor || - property.isMatrix3 || property.isMatrix4 || - property.isVector2 || property.isVector3 || property.isVector4 || - property.isTexture || property.isQuaternion ) ) { + if ( isThreeObject( property ) ) { if ( property.isRenderTargetTexture ) { @@ -37333,7 +37330,23 @@ function cloneUniforms( src ) { } else if ( Array.isArray( property ) ) { - dst[ u ][ p ] = property.slice(); + if ( isThreeObject( property[ 0 ] ) ) { + + const clonedProperty = []; + + for ( let i = 0, l = property.length; i < l; i ++ ) { + + clonedProperty[ i ] = property[ i ].clone(); + + } + + dst[ u ][ p ] = clonedProperty; + + } else { + + dst[ u ][ p ] = property.slice(); + + } } else { @@ -37377,6 +37390,15 @@ function mergeUniforms( uniforms ) { } +function isThreeObject( property ) { + + return ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ); + +} + function cloneUniformsGroups( src ) { const dst = []; @@ -44071,7 +44093,6 @@ class FileLoader extends Loader { * @param {function(any)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. * @param {onErrorCallback} [onError] - Executed when errors occur. - * @return {any|undefined} The cached resource if available. */ load( url, onLoad, onProgress, onError ) { @@ -44095,7 +44116,7 @@ class FileLoader extends Loader { }, 0 ); - return cached; + return; } @@ -49545,6 +49566,9 @@ class ImageBitmapLoader extends Loader { * Sets the given loader options. The structure of the object must match the `options` parameter of * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap). * + * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with + * different options will return the cached result of the first request. + * * @param {Object} options - The loader options to set. * @return {ImageBitmapLoader} A reference to this image bitmap loader. */ @@ -49563,7 +49587,6 @@ class ImageBitmapLoader extends Loader { * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Unsupported in this loader. * @param {onErrorCallback} onError - Executed when errors occur. - * @return {ImageBitmap|undefined} The image bitmap. */ load( url, onLoad, onProgress, onError ) { @@ -49601,8 +49624,6 @@ class ImageBitmapLoader extends Loader { scope.manager.itemEnd( url ); - return imageBitmap; - } } ); @@ -49620,7 +49641,7 @@ class ImageBitmapLoader extends Loader { }, 0 ); - return cached; + return; } @@ -49645,8 +49666,6 @@ class ImageBitmapLoader extends Loader { scope.manager.itemEnd( url ); - return imageBitmap; - } ).catch( function ( e ) { if ( onError ) onError( e ); @@ -49777,11 +49796,21 @@ class AudioLoader extends Loader { const bufferCopy = buffer.slice( 0 ); const context = AudioContext.getContext(); + + const decodeUrl = url + '#decode'; + scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378 + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { onLoad( audioBuffer ); + scope.manager.itemEnd( decodeUrl ); - } ).catch( handleError ); + } ).catch( function ( e ) { + + handleError( e ); + scope.manager.itemEnd( decodeUrl ); + + } ); } catch ( e ) { diff --git a/build/three.core.min.js b/build/three.core.min.js index 6b7f1d07a4a991..1399c89cf994a0 100644 --- a/build/three.core.min.js +++ b/build/three.core.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2026 Three.js Authors * SPDX-License-Identifier: MIT */ -const t="184dev",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},i={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},s=0,r=1,n=2,a=3,o=0,h=1,l=2,c=3,u=0,d=1,p=2,m=0,y=1,g=2,f=3,x=4,b=5,v=6,w=100,M=101,S=102,_=103,A=104,T=200,z=201,C=202,I=203,B=204,k=205,O=206,P=207,R=208,N=209,V=210,E=211,L=212,F=213,j=214,D=0,U=1,W=2,q=3,J=4,X=5,Y=6,H=7,Z=0,G=1,$=2,Q=0,K=1,tt=2,et=3,it=4,st=5,rt=6,nt=7,at="attached",ot="detached",ht=300,lt=301,ct=302,ut=303,dt=304,pt=306,mt=1e3,yt=1001,gt=1002,ft=1003,xt=1004,bt=1004,vt=1005,wt=1005,Mt=1006,St=1007,_t=1007,At=1008,Tt=1008,zt=1009,Ct=1010,It=1011,Bt=1012,kt=1013,Ot=1014,Pt=1015,Rt=1016,Nt=1017,Vt=1018,Et=1020,Lt=35902,Ft=35899,jt=1021,Dt=1022,Ut=1023,Wt=1026,qt=1027,Jt=1028,Xt=1029,Yt=1030,Ht=1031,Zt=1032,Gt=1033,$t=33776,Qt=33777,Kt=33778,te=33779,ee=35840,ie=35841,se=35842,re=35843,ne=36196,ae=37492,oe=37496,he=37488,le=37489,ce=37490,ue=37491,de=37808,pe=37809,me=37810,ye=37811,ge=37812,fe=37813,xe=37814,be=37815,ve=37816,we=37817,Me=37818,Se=37819,_e=37820,Ae=37821,Te=36492,ze=36494,Ce=36495,Ie=36283,Be=36284,ke=36285,Oe=36286,Pe=2200,Re=2201,Ne=2202,Ve=2300,Ee=2301,Le=2302,Fe=2303,je=2400,De=2401,Ue=2402,We=2500,qe=2501,Je=0,Xe=1,Ye=2,He=3200,Ze=3201,Ge=3202,$e=3203,Qe=0,Ke=1,ti="",ei="srgb",ii="srgb-linear",si="linear",ri="srgb",ni="",ai="rg",oi="ga",hi=0,li=7680,ci=7681,ui=7682,di=7683,pi=34055,mi=34056,yi=5386,gi=512,fi=513,xi=514,bi=515,vi=516,wi=517,Mi=518,Si=519,_i=512,Ai=513,Ti=514,zi=515,Ci=516,Ii=517,Bi=518,ki=519,Oi=35044,Pi=35048,Ri=35040,Ni=35045,Vi=35049,Ei=35041,Li=35046,Fi=35050,ji=35042,Di="100",Ui="300 es",Wi=2e3,qi=2001,Ji={COMPUTE:"compute",RENDER:"render"},Xi={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Yi={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"},Hi={TEXTURE_COMPARE:"depthTextureCompare"};const Zi={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Gi(t,e){return new Zi[t](e)}function $i(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Qi(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Ki(){const t=Qi("canvas");return t.style.display="block",t}const ts={};let es=null;function is(t){es=t}function ss(){return es}function rs(...t){const e="THREE."+t.shift();es?es("log",e,...t):console.log(e,...t)}function ns(t){const e=t[0];if("string"==typeof e&&e.startsWith("TSL:")){const e=t[1];e&&e.isStackTrace?t[0]+=" "+e.getLocation():t[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return t}function as(...t){const e="THREE."+(t=ns(t)).shift();if(es)es("warn",e,...t);else{const i=t[0];i&&i.isStackTrace?console.warn(i.getError(e)):console.warn(e,...t)}}function os(...t){const e="THREE."+(t=ns(t)).shift();if(es)es("error",e,...t);else{const i=t[0];i&&i.isStackTrace?console.error(i.getError(e)):console.error(e,...t)}}function hs(...t){const e=t.join(" ");e in ts||(ts[e]=!0,as(...t))}function ls(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(t=>{requestAnimationFrame(t)})}function cs(t,e,i){return new Promise(function(s,r){setTimeout(function n(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:r();break;case t.TIMEOUT_EXPIRED:setTimeout(n,i);break;default:s()}},i)})}const us={[D]:1,[W]:6,[J]:7,[q]:5,[U]:0,[Y]:2,[H]:4,[X]:3};class ds{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return void 0!==i&&(void 0!==i[t]&&-1!==i[t].indexOf(e))}removeEventListener(t,e){const i=this._listeners;if(void 0===i)return;const s=i[t];if(void 0!==s){const t=s.indexOf(e);-1!==t&&s.splice(t,1)}}dispatchEvent(t){const e=this._listeners;if(void 0===e)return;const i=e[t.type];if(void 0!==i){t.target=this;const e=i.slice(0);for(let i=0,s=e.length;i>8&255]+ps[t>>16&255]+ps[t>>24&255]+"-"+ps[255&e]+ps[e>>8&255]+"-"+ps[e>>16&15|64]+ps[e>>24&255]+"-"+ps[63&i|128]+ps[i>>8&255]+"-"+ps[i>>16&255]+ps[i>>24&255]+ps[255&s]+ps[s>>8&255]+ps[s>>16&255]+ps[s>>24&255]).toLowerCase()}function xs(t,e,i){return Math.max(e,Math.min(i,t))}function bs(t,e){return(t%e+e)%e}function vs(t,e,i){return(1-i)*t+i*e}function ws(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Ms(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Ss={DEG2RAD:ys,RAD2DEG:gs,generateUUID:fs,clamp:xs,euclideanModulo:bs,mapLinear:function(t,e,i,s,r){return s+(t-e)*(r-s)/(i-e)},inverseLerp:function(t,e,i){return t!==e?(i-t)/(e-t):0},lerp:vs,damp:function(t,e,i,s){return vs(t,e,1-Math.exp(-i*s))},pingpong:function(t,e=1){return e-Math.abs(bs(t,2*e)-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(ms=t);let e=ms+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*ys},radToDeg:function(t){return t*gs},isPowerOfTwo:function(t){return!(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,i,s,r){const n=Math.cos,a=Math.sin,o=n(i/2),h=a(i/2),l=n((e+s)/2),c=a((e+s)/2),u=n((e-s)/2),d=a((e-s)/2),p=n((s-e)/2),m=a((s-e)/2);switch(r){case"XYX":t.set(o*c,h*u,h*d,o*l);break;case"YZY":t.set(h*d,o*c,h*u,o*l);break;case"ZXZ":t.set(h*u,h*d,o*c,o*l);break;case"XZX":t.set(o*c,h*m,h*p,o*l);break;case"YXY":t.set(h*p,o*c,h*m,o*l);break;case"ZYZ":t.set(h*m,h*p,o*c,o*l);break;default:as("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Ms,denormalize:ws};class _s{static{_s.prototype.isVector2=!0}constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=xs(this.x,t.x,e.x),this.y=xs(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=xs(this.x,t,e),this.y=xs(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(xs(i,t,e))}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(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.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(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(xs(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),r=this.x-t.x,n=this.y-t.y;return this.x=r*i-n*s+t.x,this.y=r*s+n*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class As{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,r,n,a){let o=i[s+0],h=i[s+1],l=i[s+2],c=i[s+3],u=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(c!==m||o!==u||h!==d||l!==p){let t=o*u+h*d+l*p+c*m;t<0&&(u=-u,d=-d,p=-p,m=-m,t=-t);let e=1-a;if(t<.9995){const i=Math.acos(t),s=Math.sin(i);e=Math.sin(e*i)/s,o=o*e+u*(a=Math.sin(a*i)/s),h=h*e+d*a,l=l*e+p*a,c=c*e+m*a}else{o=o*e+u*a,h=h*e+d*a,l=l*e+p*a,c=c*e+m*a;const t=1/Math.sqrt(o*o+h*h+l*l+c*c);o*=t,h*=t,l*=t,c*=t}}t[e]=o,t[e+1]=h,t[e+2]=l,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,r,n){const a=i[s],o=i[s+1],h=i[s+2],l=i[s+3],c=r[n],u=r[n+1],d=r[n+2],p=r[n+3];return t[e]=a*p+l*c+o*d-h*u,t[e+1]=o*p+l*u+h*c-a*d,t[e+2]=h*p+l*d+a*u-o*c,t[e+3]=l*p-a*c-o*u-h*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,r=t._z,n=t._order,a=Math.cos,o=Math.sin,h=a(i/2),l=a(s/2),c=a(r/2),u=o(i/2),d=o(s/2),p=o(r/2);switch(n){case"XYZ":this._x=u*l*c+h*d*p,this._y=h*d*c-u*l*p,this._z=h*l*p+u*d*c,this._w=h*l*c-u*d*p;break;case"YXZ":this._x=u*l*c+h*d*p,this._y=h*d*c-u*l*p,this._z=h*l*p-u*d*c,this._w=h*l*c+u*d*p;break;case"ZXY":this._x=u*l*c-h*d*p,this._y=h*d*c+u*l*p,this._z=h*l*p+u*d*c,this._w=h*l*c-u*d*p;break;case"ZYX":this._x=u*l*c-h*d*p,this._y=h*d*c+u*l*p,this._z=h*l*p-u*d*c,this._w=h*l*c+u*d*p;break;case"YZX":this._x=u*l*c+h*d*p,this._y=h*d*c+u*l*p,this._z=h*l*p-u*d*c,this._w=h*l*c-u*d*p;break;case"XZY":this._x=u*l*c-h*d*p,this._y=h*d*c-u*l*p,this._z=h*l*p+u*d*c,this._w=h*l*c+u*d*p;break;default:as("Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],r=e[8],n=e[1],a=e[5],o=e[9],h=e[2],l=e[6],c=e[10],u=i+a+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(l-o)*t,this._y=(r-h)*t,this._z=(n-s)*t}else if(i>a&&i>c){const t=2*Math.sqrt(1+i-a-c);this._w=(l-o)/t,this._x=.25*t,this._y=(s+n)/t,this._z=(r+h)/t}else if(a>c){const t=2*Math.sqrt(1+a-i-c);this._w=(r-h)/t,this._x=(s+n)/t,this._y=.25*t,this._z=(o+l)/t}else{const t=2*Math.sqrt(1+c-i-a);this._w=(n-s)/t,this._x=(r+h)/t,this._y=(o+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(xs(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._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 t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,r=t._z,n=t._w,a=e._x,o=e._y,h=e._z,l=e._w;return this._x=i*l+n*a+s*h-r*o,this._y=s*l+n*o+r*a-i*h,this._z=r*l+n*h+i*o-s*a,this._w=n*l-i*a-s*o-r*h,this._onChangeCallback(),this}slerp(t,e){let i=t._x,s=t._y,r=t._z,n=t._w,a=this.dot(t);a<0&&(i=-i,s=-s,r=-r,n=-n,a=-a);let o=1-e;if(a<.9995){const t=Math.acos(a),h=Math.sin(t);o=Math.sin(o*t)/h,e=Math.sin(e*t)/h,this._x=this._x*o+i*e,this._y=this._y*o+s*e,this._z=this._z*o+r*e,this._w=this._w*o+n*e,this._onChangeCallback()}else this._x=this._x*o+i*e,this._y=this._y*o+s*e,this._z=this._z*o+r*e,this._w=this._w*o+n*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ts{static{Ts.prototype.isVector3=!0}constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Cs.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Cs.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*s,this.y=r[1]*e+r[4]*i+r[7]*s,this.z=r[2]*e+r[5]*i+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=t.elements,n=1/(r[3]*e+r[7]*i+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*s+r[12])*n,this.y=(r[1]*e+r[5]*i+r[9]*s+r[13])*n,this.z=(r[2]*e+r[6]*i+r[10]*s+r[14])*n,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,r=t.x,n=t.y,a=t.z,o=t.w,h=2*(n*s-a*i),l=2*(a*e-r*s),c=2*(r*i-n*e);return this.x=e+o*h+n*c-a*l,this.y=i+o*l+a*h-r*c,this.z=s+o*c+r*l-n*h,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s,this.y=r[1]*e+r[5]*i+r[9]*s,this.z=r[2]*e+r[6]*i+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=xs(this.x,t.x,e.x),this.y=xs(this.y,t.y,e.y),this.z=xs(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=xs(this.x,t,e),this.y=xs(this.y,t,e),this.z=xs(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(xs(i,t,e))}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(t){return this.x*t.x+this.y*t.y+this.z*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,r=t.z,n=e.x,a=e.y,o=e.z;return this.x=s*o-r*a,this.y=r*n-i*o,this.z=i*a-s*n,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return zs.copy(this).projectOnVector(t),this.sub(zs)}reflect(t){return this.sub(zs.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(xs(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const zs=new Ts,Cs=new As;class Is{static{Is.prototype.isMatrix3=!0}constructor(t,e,i,s,r,n,a,o,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,r,n,a,o,h)}set(t,e,i,s,r,n,a,o,h){const l=this.elements;return l[0]=t,l[1]=s,l[2]=a,l[3]=e,l[4]=r,l[5]=o,l[6]=i,l[7]=n,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,r=this.elements,n=i[0],a=i[3],o=i[6],h=i[1],l=i[4],c=i[7],u=i[2],d=i[5],p=i[8],m=s[0],y=s[3],g=s[6],f=s[1],x=s[4],b=s[7],v=s[2],w=s[5],M=s[8];return r[0]=n*m+a*f+o*v,r[3]=n*y+a*x+o*w,r[6]=n*g+a*b+o*M,r[1]=h*m+l*f+c*v,r[4]=h*y+l*x+c*w,r[7]=h*g+l*b+c*M,r[2]=u*m+d*f+p*v,r[5]=u*y+d*x+p*w,r[8]=u*g+d*b+p*M,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],o=t[6],h=t[7],l=t[8];return e*n*l-e*a*h-i*r*l+i*a*o+s*r*h-s*n*o}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],o=t[6],h=t[7],l=t[8],c=l*n-a*h,u=a*o-l*r,d=h*r-n*o,p=e*c+i*u+s*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=c*m,t[1]=(s*h-l*i)*m,t[2]=(a*i-s*n)*m,t[3]=u*m,t[4]=(l*e-s*o)*m,t[5]=(s*r-a*e)*m,t[6]=d*m,t[7]=(i*o-h*e)*m,t[8]=(n*e-i*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,r,n,a){const o=Math.cos(r),h=Math.sin(r);return this.set(i*o,i*h,-i*(o*n+h*a)+n+t,-s*h,s*o,-s*(-h*n+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(Bs.makeScale(t,e)),this}rotate(t){return this.premultiply(Bs.makeRotation(-t)),this}translate(t,e){return this.premultiply(Bs.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const Bs=new Is,ks=(new Is).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Os=(new Is).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ps(){const t={enabled:!0,workingColorSpace:ii,spaces:{},convert:function(t,e,i){return!1!==this.enabled&&e!==i&&e&&i?(this.spaces[e].transfer===ri&&(t.r=Ns(t.r),t.g=Ns(t.g),t.b=Ns(t.b)),this.spaces[e].primaries!==this.spaces[i].primaries&&(t.applyMatrix3(this.spaces[e].toXYZ),t.applyMatrix3(this.spaces[i].fromXYZ)),this.spaces[i].transfer===ri&&(t.r=Vs(t.r),t.g=Vs(t.g),t.b=Vs(t.b)),t):t},workingToColorSpace:function(t,e){return this.convert(t,this.workingColorSpace,e)},colorSpaceToWorking:function(t,e){return this.convert(t,e,this.workingColorSpace)},getPrimaries:function(t){return this.spaces[t].primaries},getTransfer:function(t){return""===t?si:this.spaces[t].transfer},getToneMappingMode:function(t){return this.spaces[t].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(t,e=this.workingColorSpace){return t.fromArray(this.spaces[e].luminanceCoefficients)},define:function(t){Object.assign(this.spaces,t)},_getMatrix:function(t,e,i){return t.copy(this.spaces[e].toXYZ).multiply(this.spaces[i].fromXYZ)},_getDrawingBufferColorSpace:function(t){return this.spaces[t].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(t=this.workingColorSpace){return this.spaces[t].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(e,i){return hs("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(e,i)},toWorkingColorSpace:function(e,i){return hs("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(e,i)}},e=[.64,.33,.3,.6,.15,.06],i=[.2126,.7152,.0722],s=[.3127,.329];return t.define({[ii]:{primaries:e,whitePoint:s,transfer:si,toXYZ:ks,fromXYZ:Os,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:ei},outputColorSpaceConfig:{drawingBufferColorSpace:ei}},[ei]:{primaries:e,whitePoint:s,transfer:ri,toXYZ:ks,fromXYZ:Os,luminanceCoefficients:i,outputColorSpaceConfig:{drawingBufferColorSpace:ei}}}),t}const Rs=Ps();function Ns(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function Vs(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let Es;class Ls{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{void 0===Es&&(Es=Qi("canvas")),Es.width=t.width,Es.height=t.height;const e=Es.getContext("2d");t instanceof ImageData?e.putImageData(t,0,0):e.drawImage(t,0,0,t.width,t.height),i=Es}return i.toDataURL(e)}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=Qi("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height),r=s.data;for(let t=0;t1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Ws).x}get height(){return this.source.getSize(Ws).y}get depth(){return this.source.getSize(Ws).z}get image(){return this.source.data}set image(t){this.source.data=t}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(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(void 0===i){as(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const s=this[e];void 0!==s?s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[e]=i:as(`Texture.setValues(): property '${e}' does not exist.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).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&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==ht)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case mt:t.x=t.x-Math.floor(t.x);break;case yt:t.x=t.x<0?0:1;break;case gt:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case mt:t.y=t.y-Math.floor(t.y);break;case yt:t.y=t.y<0?0:1;break;case gt:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}qs.DEFAULT_IMAGE=null,qs.DEFAULT_MAPPING=ht,qs.DEFAULT_ANISOTROPY=1;class Js{static{Js.prototype.isVector4=!0}constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=this.w,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s+n[12]*r,this.y=n[1]*e+n[5]*i+n[9]*s+n[13]*r,this.z=n[2]*e+n[6]*i+n[10]*s+n[14]*r,this.w=n[3]*e+n[7]*i+n[11]*s+n[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,r;const n=.01,a=.1,o=t.elements,h=o[0],l=o[4],c=o[8],u=o[1],d=o[5],p=o[9],m=o[2],y=o[6],g=o[10];if(Math.abs(l-u)o&&t>f?tf?o1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return(new this.constructor).copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,i=t.textures.length;e>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),null!==this.pivot&&(s.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(s.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(s.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(s.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox?t.boundingBox.toJSON():void 0,boundingSphere:t.boundingSphere?t.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(t=>({...t})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),null!==this._colorsTexture&&(s.colorsTexture=this._colorsTexture.toJSON(t)),null!==this.boundingSphere&&(s.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(s.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const i=e.shapes;if(Array.isArray(i))for(let e=0,s=i.length;e0){s.children=[];for(let e=0;e0){s.animations=[];for(let e=0;e0&&(i.geometries=e),s.length>0&&(i.materials=s),r.length>0&&(i.textures=r),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),h.length>0&&(i.skeletons=h),l.length>0&&(i.animations=l),c.length>0&&(i.nodes=c)}return i.object=s,i;function n(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=null!==t.pivot?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;eo+l?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!h.inputState.pinching&&a<=o-l&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,i),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:t,target:this})));null!==a&&(s=e.getPose(t.targetRaySpace,i),null===s&&null!==r&&(s=r),null!==s&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(zr)))}return null!==a&&(a.visible=null!==s),null!==o&&(o.visible=null!==r),null!==h&&(h.visible=null!==n),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const i=new Tr;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}const Ir={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},Br={h:0,s:0,l:0},kr={h:0,s:0,l:0};function Or(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}class Pr{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(void 0===e&&void 0===i){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=ei){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,Rs.colorSpaceToWorking(this,e),this}setRGB(t,e,i,s=Rs.workingColorSpace){return this.r=t,this.g=e,this.b=i,Rs.colorSpaceToWorking(this,s),this}setHSL(t,e,i,s=Rs.workingColorSpace){if(t=bs(t,1),e=xs(e,0,1),i=xs(i,0,1),0===e)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,r=2*i-s;this.r=Or(r,s,t+1/3),this.g=Or(r,s,t),this.b=Or(r,s,t-1/3)}return Rs.colorSpaceToWorking(this,s),this}setStyle(t,e=ei){function i(e){void 0!==e&&parseFloat(e)<1&&as("Color: Alpha component of "+t+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let r;const n=s[1],a=s[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(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,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(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,e);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 i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:as("Color: Unknown color model "+t)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){const i=s[1],r=i.length;if(3===r)return this.setRGB(parseInt(i.charAt(0),16)/15,parseInt(i.charAt(1),16)/15,parseInt(i.charAt(2),16)/15,e);if(6===r)return this.setHex(parseInt(i,16),e);as("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=ei){const i=Ir[t.toLowerCase()];return void 0!==i?this.setHex(i,e):as("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Ns(t.r),this.g=Ns(t.g),this.b=Ns(t.b),this}copyLinearToSRGB(t){return this.r=Vs(t.r),this.g=Vs(t.g),this.b=Vs(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=ei){return Rs.workingToColorSpace(Rr.copy(this),t),65536*Math.round(xs(255*Rr.r,0,255))+256*Math.round(xs(255*Rr.g,0,255))+Math.round(xs(255*Rr.b,0,255))}getHexString(t=ei){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Rs.workingColorSpace){Rs.workingToColorSpace(Rr.copy(this),e);const i=Rr.r,s=Rr.g,r=Rr.b,n=Math.max(i,s,r),a=Math.min(i,s,r);let o,h;const l=(a+n)/2;if(a===n)o=0,h=0;else{const t=n-a;switch(h=l<=.5?t/(n+a):t/(2-n-a),n){case i:o=(s-r)/t+(s0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const Lr=new Ts,Fr=new Ts,jr=new Ts,Dr=new Ts,Ur=new Ts,Wr=new Ts,qr=new Ts,Jr=new Ts,Xr=new Ts,Yr=new Ts,Hr=new Js,Zr=new Js,Gr=new Js;class $r{constructor(t=new Ts,e=new Ts,i=new Ts){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,s){s.subVectors(i,e),Lr.subVectors(t,e),s.cross(Lr);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,i,s,r){Lr.subVectors(s,e),Fr.subVectors(i,e),jr.subVectors(t,e);const n=Lr.dot(Lr),a=Lr.dot(Fr),o=Lr.dot(jr),h=Fr.dot(Fr),l=Fr.dot(jr),c=n*h-a*a;if(0===c)return r.set(0,0,0),null;const u=1/c,d=(h*o-a*l)*u,p=(n*l-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,i,s){return null!==this.getBarycoord(t,e,i,s,Dr)&&(Dr.x>=0&&Dr.y>=0&&Dr.x+Dr.y<=1)}static getInterpolation(t,e,i,s,r,n,a,o){return null===this.getBarycoord(t,e,i,s,Dr)?(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,Dr.x),o.addScaledVector(n,Dr.y),o.addScaledVector(a,Dr.z),o)}static getInterpolatedAttribute(t,e,i,s,r,n){return Hr.setScalar(0),Zr.setScalar(0),Gr.setScalar(0),Hr.fromBufferAttribute(t,e),Zr.fromBufferAttribute(t,i),Gr.fromBufferAttribute(t,s),n.setScalar(0),n.addScaledVector(Hr,r.x),n.addScaledVector(Zr,r.y),n.addScaledVector(Gr,r.z),n}static isFrontFacing(t,e,i,s){return Lr.subVectors(i,e),Fr.subVectors(t,e),Lr.cross(Fr).dot(s)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,s){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,i,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,s),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Lr.subVectors(this.c,this.b),Fr.subVectors(this.a,this.b),.5*Lr.cross(Fr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return $r.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return $r.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,s,r){return $r.getInterpolation(t,this.a,this.b,this.c,e,i,s,r)}containsPoint(t){return $r.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return $r.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,s=this.b,r=this.c;let n,a;Ur.subVectors(s,i),Wr.subVectors(r,i),Jr.subVectors(t,i);const o=Ur.dot(Jr),h=Wr.dot(Jr);if(o<=0&&h<=0)return e.copy(i);Xr.subVectors(t,s);const l=Ur.dot(Xr),c=Wr.dot(Xr);if(l>=0&&c<=l)return e.copy(s);const u=o*c-l*h;if(u<=0&&o>=0&&l<=0)return n=o/(o-l),e.copy(i).addScaledVector(Ur,n);Yr.subVectors(t,r);const d=Ur.dot(Yr),p=Wr.dot(Yr);if(p>=0&&d<=p)return e.copy(r);const m=d*h-o*p;if(m<=0&&h>=0&&p<=0)return a=h/(h-p),e.copy(i).addScaledVector(Wr,a);const y=l*p-d*c;if(y<=0&&c-l>=0&&d-p>=0)return qr.subVectors(r,s),a=(c-l)/(c-l+(d-p)),e.copy(s).addScaledVector(qr,a);const g=1/(y+m+u);return n=m*g,a=u*g,e.copy(i).addScaledVector(Ur,n).addScaledVector(Wr,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class Qr{constructor(t=new Ts(1/0,1/0,1/0),e=new Ts(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,tn),tn.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(ln),cn.subVectors(this.max,ln),sn.subVectors(t.a,ln),rn.subVectors(t.b,ln),nn.subVectors(t.c,ln),an.subVectors(rn,sn),on.subVectors(nn,rn),hn.subVectors(sn,nn);let e=[0,-an.z,an.y,0,-on.z,on.y,0,-hn.z,hn.y,an.z,0,-an.x,on.z,0,-on.x,hn.z,0,-hn.x,-an.y,an.x,0,-on.y,on.x,0,-hn.y,hn.x,0];return!!pn(e,sn,rn,nn,cn)&&(e=[1,0,0,0,1,0,0,0,1],!!pn(e,sn,rn,nn,cn)&&(un.crossVectors(an,on),e=[un.x,un.y,un.z],pn(e,sn,rn,nn,cn)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,tn).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(tn).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Kr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Kr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Kr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Kr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Kr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Kr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Kr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Kr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Kr)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Kr=[new Ts,new Ts,new Ts,new Ts,new Ts,new Ts,new Ts,new Ts],tn=new Ts,en=new Qr,sn=new Ts,rn=new Ts,nn=new Ts,an=new Ts,on=new Ts,hn=new Ts,ln=new Ts,cn=new Ts,un=new Ts,dn=new Ts;function pn(t,e,i,s,r){for(let n=0,a=t.length-3;n<=a;n+=3){dn.fromArray(t,n);const a=r.x*Math.abs(dn.x)+r.y*Math.abs(dn.y)+r.z*Math.abs(dn.z),o=e.dot(dn),h=i.dot(dn),l=s.dot(dn);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const mn=yn();function yn(){const t=new ArrayBuffer(4),e=new Float32Array(t),i=new Uint32Array(t),s=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(s[t]=0,s[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(s[t]=1024>>-e-14,s[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(s[t]=e+15<<10,s[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(s[t]=31744,s[256|t]=64512,r[t]=24,r[256|t]=24):(s[t]=31744,s[256|t]=64512,r[t]=13,r[256|t]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,i=0;for(;!(8388608&e);)e<<=1,i-=8388608;e&=-8388609,i+=947912704,n[t]=e|i}for(let t=1024;t<2048;++t)n[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:i,baseTable:s,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function gn(t){Math.abs(t)>65504&&as("DataUtils.toHalfFloat(): Value out of range."),t=xs(t,-65504,65504),mn.floatView[0]=t;const e=mn.uint32View[0],i=e>>23&511;return mn.baseTable[i]+((8388607&e)>>mn.shiftTable[i])}function fn(t){const e=t>>10;return mn.uint32View[0]=mn.mantissaTable[mn.offsetTable[e]+(1023&t)]+mn.exponentTable[e],mn.floatView[0]}class xn{static toHalfFloat(t){return gn(t)}static fromHalfFloat(t){return fn(t)}}const bn=new Ts,vn=new _s;let wn=0;class Mn extends ds{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:wn++}),this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=Oi,this.updateRanges=[],this.gpuType=Pt,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let s=0,r=this.itemSize;sthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Pn.subVectors(t,this.center);const e=Pn.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(Pn,i/t),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(Rn.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Pn.copy(t.center).add(Rn)),this.expandByPoint(Pn.copy(t.center).sub(Rn))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let Vn=0;const En=new Qs,Ln=new Ar,Fn=new Ts,jn=new Qr,Dn=new Qr,Un=new Ts;class Wn extends ds{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Vn++}),this.uuid=fs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(function(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}(t)?In:zn)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return void 0!==this.attributes[t]}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(void 0!==i){const e=(new Is).getNormalMatrix(t);i.applyNormalMatrix(e),i.needsUpdate=!0}const s=this.attributes.tangent;return void 0!==s&&(s.transformDirection(t),s.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return En.makeRotationFromQuaternion(t),this.applyMatrix4(En),this}rotateX(t){return En.makeRotationX(t),this.applyMatrix4(En),this}rotateY(t){return En.makeRotationY(t),this.applyMatrix4(En),this}rotateZ(t){return En.makeRotationZ(t),this.applyMatrix4(En),this}translate(t,e,i){return En.makeTranslation(t,e,i),this.applyMatrix4(En),this}scale(t,e,i){return En.makeScale(t,e,i),this.applyMatrix4(En),this}lookAt(t){return Ln.lookAt(t),Ln.updateMatrix(),this.applyMatrix4(Ln.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Fn).negate(),this.translate(Fn.x,Fn.y,Fn.z),this}setFromPoints(t){const e=this.getAttribute("position");if(void 0===e){const e=[];for(let i=0,s=t.length;ie.count&&as("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Qr);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return os("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Ts(-1/0,-1/0,-1/0),new Ts(1/0,1/0,1/0));if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,i=e.length;t0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const i in e)void 0!==e[i]&&(t[i]=e[i]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const e in i){const s=i[e];t.data.attributes[e]=s.toJSON(t.data)}const s={};let r=!1;for(const e in this.morphAttributes){const i=this.morphAttributes[e],n=[];for(let e=0,s=i.length;e0&&(s[e]=n,r=!0)}r&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(t.data.groups=JSON.parse(JSON.stringify(n)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere=a.toJSON()),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;null!==i&&this.setIndex(i.clone());const s=t.attributes;for(const t in s){const i=s[t];this.setAttribute(t,i.clone(e))}const r=t.morphAttributes;for(const t in r){const i=[],s=r[t];for(let t=0,r=s.length;t0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const i=t[e];if(void 0===i){as(`Material: parameter '${e}' has value of undefined.`);continue}const s=this[e];void 0!==s?s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[e]=i:as(`Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function s(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),void 0!==this.dispersion&&(i.dispersion=this.dispersion),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(i.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapRotation&&(i.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),null!==this.shadowSide&&(i.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(i.blending=this.blending),0!==this.side&&(i.side=this.side),!0===this.vertexColors&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),!0===this.transparent&&(i.transparent=!0),204!==this.blendSrc&&(i.blendSrc=this.blendSrc),205!==this.blendDst&&(i.blendDst=this.blendDst),100!==this.blendEquation&&(i.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(i.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(i.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(i.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(i.depthFunc=this.depthFunc),!1===this.depthTest&&(i.depthTest=this.depthTest),!1===this.depthWrite&&(i.depthWrite=this.depthWrite),!1===this.colorWrite&&(i.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(i.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(i.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(i.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==li&&(i.stencilFail=this.stencilFail),this.stencilZFail!==li&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==li&&(i.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(i.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(i.rotation=this.rotation),!0===this.polygonOffset&&(i.polygonOffset=!0),0!==this.polygonOffsetFactor&&(i.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(i.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),!0===this.dithering&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),!0===this.alphaHash&&(i.alphaHash=!0),!0===this.alphaToCoverage&&(i.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(i.premultipliedAlpha=!0),!0===this.forceSinglePass&&(i.forceSinglePass=!0),!1===this.allowOverride&&(i.allowOverride=!1),!0===this.wireframe&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(i.flatShading=!0),!1===this.visible&&(i.visible=!1),!1===this.toneMapped&&(i.toneMapped=!1),!1===this.fog&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData),e){const e=s(t.textures),r=s(t.images);e.length>0&&(i.textures=e),r.length>0&&(i.images=r)}return i}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(null!==e){const t=e.length;i=new Array(t);for(let s=0;s!==t;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}}class Gn extends Zn{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Pr(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const $n=new Ts,Qn=new Ts,Kn=new Ts,ta=new _s,ea=new _s,ia=new Qs,sa=new Ts,ra=new Ts,na=new Ts,aa=new _s,oa=new _s,ha=new _s;class la extends Ar{constructor(t=new Gn){if(super(),this.isSprite=!0,this.type="Sprite",void 0===Yn){Yn=new Wn;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),e=new qn(t,5);Yn.setIndex([0,1,2,0,2,3]),Yn.setAttribute("position",new Xn(e,3,0,!1)),Yn.setAttribute("uv",new Xn(e,2,3,!1))}this.geometry=Yn,this.material=t,this.center=new _s(.5,.5),this.count=1}raycast(t,e){null===t.camera&&os('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Qn.setFromMatrixScale(this.matrixWorld),ia.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),Kn.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&Qn.multiplyScalar(-Kn.z);const i=this.material.rotation;let s,r;0!==i&&(r=Math.cos(i),s=Math.sin(i));const n=this.center;ca(sa.set(-.5,-.5,0),Kn,n,Qn,s,r),ca(ra.set(.5,-.5,0),Kn,n,Qn,s,r),ca(na.set(.5,.5,0),Kn,n,Qn,s,r),aa.set(0,0),oa.set(1,0),ha.set(1,1);let a=t.ray.intersectTriangle(sa,ra,na,!1,$n);if(null===a&&(ca(ra.set(-.5,.5,0),Kn,n,Qn,s,r),oa.set(0,1),a=t.ray.intersectTriangle(sa,na,ra,!1,$n),null===a))return;const o=t.ray.origin.distanceTo($n);ot.far||e.push({distance:o,point:$n.clone(),uv:$r.getInterpolation($n,sa,ra,na,aa,oa,ha,new _s),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function ca(t,e,i,s,r,n){ta.subVectors(t,i).addScalar(.5).multiply(s),void 0!==r?(ea.x=n*ta.x-r*ta.y,ea.y=r*ta.x+n*ta.y):ea.copy(ta),t.copy(e),t.x+=ea.x,t.y+=ea.y,t.applyMatrix4(ia)}const ua=new Ts,da=new Ts;class pa extends Ar{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,i=e.length;t0){let i,s;for(i=1,s=e.length;i0){ua.setFromMatrixPosition(this.matrixWorld);const i=t.ray.origin.distanceTo(ua);this.getObjectForDistance(i).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){ua.setFromMatrixPosition(t.matrixWorld),da.setFromMatrixPosition(this.matrixWorld);const i=ua.distanceTo(da)/t.zoom;let s,r;for(e[0].object.visible=!0,s=1,r=e.length;s=t))break;e[s-1].object.visible=!1,e[s].object.visible=!0}for(this._currentLevel=s-1;s0)if(c=n*o-a,u=n*a-o,p=r*l,c>=0)if(u>=-p)if(u<=p){const t=1/l;c*=t,u*=t,d=c*(c+n*u+2*a)+u*(n*c+u+2*o)+h}else u=r,c=Math.max(0,-(n*u+a)),d=-c*c+u*(u+2*o)+h;else u=-r,c=Math.max(0,-(n*u+a)),d=-c*c+u*(u+2*o)+h;else u<=-p?(c=Math.max(0,-(-n*r+a)),u=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+u*(u+2*o)+h):u<=p?(c=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+h):(c=Math.max(0,-(n*r+a)),u=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+u*(u+2*o)+h);else u=n>0?-r:r,c=Math.max(0,-(n*u+a)),d=-c*c+u*(u+2*o)+h;return i&&i.copy(this.origin).addScaledVector(this.direction,c),s&&s.copy(ya).addScaledVector(ga,u),d}intersectSphere(t,e){ma.subVectors(t.center,this.origin);const i=ma.dot(this.direction),s=ma.dot(ma)-i*i,r=t.radius*t.radius;if(s>r)return null;const n=Math.sqrt(r-s),a=i-n,o=i+n;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return!(t.radius<0)&&this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return null===i?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,s,r,n,a,o;const h=1/this.direction.x,l=1/this.direction.y,c=1/this.direction.z,u=this.origin;return h>=0?(i=(t.min.x-u.x)*h,s=(t.max.x-u.x)*h):(i=(t.max.x-u.x)*h,s=(t.min.x-u.x)*h),l>=0?(r=(t.min.y-u.y)*l,n=(t.max.y-u.y)*l):(r=(t.max.y-u.y)*l,n=(t.min.y-u.y)*l),i>n||r>s?null:((r>i||isNaN(i))&&(i=r),(n=0?(a=(t.min.z-u.z)*c,o=(t.max.z-u.z)*c):(a=(t.max.z-u.z)*c,o=(t.min.z-u.z)*c),i>o||a>s?null:((a>i||i!=i)&&(i=a),(o=0?i:s,e)))}intersectsBox(t){return null!==this.intersectBox(t,ma)}intersectTriangle(t,e,i,s,r){xa.subVectors(e,t),ba.subVectors(i,t),va.crossVectors(xa,ba);let n,a=this.direction.dot(va);if(a>0){if(s)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}fa.subVectors(this.origin,t);const o=n*this.direction.dot(ba.crossVectors(fa,ba));if(o<0)return null;const h=n*this.direction.dot(xa.cross(fa));if(h<0)return null;if(o+h>a)return null;const l=-n*fa.dot(va);return l<0?null:this.at(l/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class Ma extends Zn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Pr(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 hr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const Sa=new Qs,_a=new wa,Aa=new Nn,Ta=new Ts,za=new Ts,Ca=new Ts,Ia=new Ts,Ba=new Ts,ka=new Ts,Oa=new Ts,Pa=new Ts;class Ra extends Ar{constructor(t=new Wn,e=new Ma){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;t(t.far-t.near)**2)return}Sa.copy(r).invert(),_a.copy(t.ray).applyMatrix4(Sa),null!==i.boundingBox&&!1===_a.intersectsBox(i.boundingBox)||this._computeIntersections(t,e,_a)}}_computeIntersections(t,e,i){let s;const r=this.geometry,n=this.material,a=r.index,o=r.attributes.position,h=r.attributes.uv,l=r.attributes.uv1,c=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(n))for(let r=0,o=u.length;ri.far?null:{distance:l,point:Pa.clone(),object:t}}(t,e,i,s,za,Ca,Ia,Oa);if(c){const t=new Ts;$r.getBarycoord(Oa,za,Ca,Ia,t),r&&(c.uv=$r.getInterpolatedAttribute(r,o,h,l,t,new _s)),n&&(c.uv1=$r.getInterpolatedAttribute(n,o,h,l,t,new _s)),a&&(c.normal=$r.getInterpolatedAttribute(a,o,h,l,t,new Ts),c.normal.dot(s.direction)>0&&c.normal.multiplyScalar(-1));const e={a:o,b:h,c:l,normal:new Ts,materialIndex:0};$r.getNormal(za,Ca,Ia,e.normal),c.face=e,c.barycoord=t}return c}const Va=new Js,Ea=new Js,La=new Js,Fa=new Js,ja=new Qs,Da=new Ts,Ua=new Nn,Wa=new Qs,qa=new wa;class Ja extends Ra{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=at,this.bindMatrix=new Qs,this.bindMatrixInverse=new Qs,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;null===this.boundingBox&&(this.boundingBox=new Qr),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let t=0;t1?null:e.copy(t.start).addScaledVector(i,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||ho.getNormalMatrix(t),s=this.coplanarPoint(ao).applyMatrix4(t),r=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const co=new Nn,uo=new _s(.5,.5),po=new Ts;class mo{constructor(t=new lo,e=new lo,i=new lo,s=new lo,r=new lo,n=new lo){this.planes=[t,e,i,s,r,n]}set(t,e,i,s,r,n){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(s),a[4].copy(r),a[5].copy(n),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=2e3,i=!1){const s=this.planes,r=t.elements,n=r[0],a=r[1],o=r[2],h=r[3],l=r[4],c=r[5],u=r[6],d=r[7],p=r[8],m=r[9],y=r[10],g=r[11],f=r[12],x=r[13],b=r[14],v=r[15];if(s[0].setComponents(h-n,d-l,g-p,v-f).normalize(),s[1].setComponents(h+n,d+l,g+p,v+f).normalize(),s[2].setComponents(h+a,d+c,g+m,v+x).normalize(),s[3].setComponents(h-a,d-c,g-m,v-x).normalize(),i)s[4].setComponents(o,u,y,b).normalize(),s[5].setComponents(h-o,d-u,g-y,v-b).normalize();else if(s[4].setComponents(h-o,d-u,g-y,v-b).normalize(),e===Wi)s[5].setComponents(h+o,d+u,g+y,v+b).normalize();else{if(e!==qi)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);s[5].setComponents(o,u,y,b).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),co.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),co.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(co)}intersectsSprite(t){co.center.set(0,0,0);const e=uo.distanceTo(t.center);return co.radius=.7071067811865476+e,co.applyMatrix4(t.matrixWorld),this.intersectsSphere(co)}intersectsSphere(t){const e=this.planes,i=t.center,s=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(i)0?t.max.x:t.min.x,po.y=s.normal.y>0?t.max.y:t.min.y,po.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(po)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const yo=new Qs,go=new mo;class fo{constructor(){this.coordinateSystem=Wi}intersectsObject(t,e){if(!e.isArrayCamera||0===e.cameras.length)return!1;for(let i=0;i=r.length&&r.push({start:-1,count:-1,z:-1,index:-1});const a=r[this.index];n.push(a),this.index++,a.start=t,a.count=e,a.z=i,a.index=s}reset(){this.list.length=0,this.index=0}}const Mo=new Qs,So=new Pr(1,1,1),_o=new mo,Ao=new fo,To=new Qr,zo=new Nn,Co=new Ts,Io=new Ts,Bo=new Ts,ko=new wo,Oo=new Ra,Po=[];function Ro(t,e,i=0){const s=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const r=t.count;for(let n=0;n65535?new Uint32Array(s):new Uint16Array(s);e.setIndex(new Mn(t,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(Boolean(t.getIndex())!==Boolean(e.getIndex()))throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in e.attributes){if(!t.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=t.getAttribute(i),r=e.getAttribute(i);if(s.itemSize!==r.itemSize||s.normalized!==r.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(t){const e=this._instanceInfo;if(t<0||t>=e.length||!1===e[t].active)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${t}. Instance is either out of range or has been deleted.`)}validateGeometryId(t){const e=this._geometryInfo;if(t<0||t>=e.length||!1===e[t].active)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${t}. Geometry is either out of range or has been deleted.`)}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Qr);const t=this.boundingBox,e=this._instanceInfo;t.makeEmpty();for(let i=0,s=e.length;i=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const e={visible:!0,active:!0,geometryIndex:t};let i=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(xo),i=this._availableInstanceIds.shift(),this._instanceInfo[i]=e):(i=this._instanceInfo.length,this._instanceInfo.push(e));const s=this._matricesTexture;Mo.identity().toArray(s.image.data,16*i),s.needsUpdate=!0;const r=this._colorsTexture;return r&&(So.toArray(r.image.data,4*i),r.needsUpdate=!0),this._visibilityChanged=!0,i}addGeometry(t,e=-1,i=-1){this._initializeGeometry(t),this._validateGeometry(t);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},r=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=-1===e?t.getAttribute("position").count:e;const n=t.getIndex();if(null!==n&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=-1===i?n.count:i),-1!==s.indexStart&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let a;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(xo),a=this._availableGeometryIds.shift(),r[a]=s):(a=this._geometryCount,this._geometryCount++,r.push(s)),this.setGeometryAt(a,t),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,a}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const i=this.geometry,s=null!==i.getIndex(),r=i.getIndex(),n=e.getIndex(),a=this._geometryInfo[t];if(s&&n.count>a.reservedIndexCount||e.attributes.position.count>a.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,h=a.reservedVertexCount;a.vertexCount=e.getAttribute("position").count;for(const t in i.attributes){const s=e.getAttribute(t),r=i.getAttribute(t);Ro(s,r,o);const n=s.itemSize;for(let t=s.count,e=h;t=e.length||!1===e[t].active)return this;const i=this._instanceInfo;for(let e=0,s=i.length;ee).sort((t,e)=>i[t].vertexStart-i[e].vertexStart),r=this.geometry;for(let n=0,a=i.length;n=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[t];if(null===s.boundingBox){const t=new Qr,e=i.index,r=i.attributes.position;for(let i=s.start,n=s.start+s.count;i=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[t];if(null===s.boundingSphere){const e=new Nn;this.getBoundingBoxAt(t,To),To.getCenter(e.center);const r=i.index,n=i.attributes.position;let a=0;for(let t=s.start,i=s.start+s.count;tt.active);if(Math.max(...i.map(t=>t.vertexStart+t.reservedVertexCount))>t)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${e}. Cannot shrink further.`);if(this.geometry.index){if(Math.max(...i.map(t=>t.indexStart+t.reservedIndexCount))>e)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${e}. Cannot shrink further.`)}const s=this.geometry;s.dispose(),this._maxVertexCount=t,this._maxIndexCount=e,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Wn,this._initializeGeometry(s));const r=this.geometry;s.index&&No(s.index.array,r.index.array);for(const t in s.attributes)No(s.attributes[t].array,r.attributes[t].array)}raycast(t,e){const i=this._instanceInfo,s=this._geometryInfo,r=this.matrixWorld,n=this.geometry;Oo.material=this.material,Oo.geometry.index=n.index,Oo.geometry.attributes=n.attributes,null===Oo.geometry.boundingBox&&(Oo.geometry.boundingBox=new Qr),null===Oo.geometry.boundingSphere&&(Oo.geometry.boundingSphere=new Nn);for(let n=0,a=i.length;n({...t,boundingBox:null!==t.boundingBox?t.boundingBox.clone():null,boundingSphere:null!==t.boundingSphere?t.boundingSphere.clone():null})),this._instanceInfo=t._instanceInfo.map(t=>({...t})),this._availableInstanceIds=t._availableInstanceIds.slice(),this._availableGeometryIds=t._availableGeometryIds.slice(),this._nextIndexStart=t._nextIndexStart,this._nextVertexStart=t._nextVertexStart,this._geometryCount=t._geometryCount,this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._indirectTexture=t._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(t,e,i,s,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const n=s.getIndex();let a=null===n?1:n.array.BYTES_PER_ELEMENT,o=1;r.wireframe&&(o=2,a=s.attributes.position.count>65535?4:2);const h=this._instanceInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,u=this._geometryInfo,d=this.perObjectFrustumCulled,p=this._indirectTexture,m=p.image.data,y=i.isArrayCamera?Ao:_o;d&&!i.isArrayCamera&&(Mo.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),_o.setFromProjectionMatrix(Mo,i.coordinateSystem,i.reversedDepth));let g=0;if(this.sortObjects){Mo.copy(this.matrixWorld).invert(),Co.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Mo),Io.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Mo);for(let t=0,e=h.length;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;ts)return;Wo.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(Wo);return he.far?void 0:{distance:h,point:qo.clone().applyMatrix4(t.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:t}}const Yo=new Ts,Ho=new Ts;class Zo extends Jo{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,i=[];for(let t=0,s=e.count;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;tr.far)return;n.push({distance:h,distanceToRay:Math.sqrt(o),point:i,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class rh extends qs{constructor(t,e,i,s,r=1006,n=1006,a,o,h){super(t,e,i,s,r,n,a,o,h),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const l=this;"requestVideoFrameCallback"in t&&(this._requestVideoFrameCallbackId=t.requestVideoFrameCallback(function e(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=t.requestVideoFrameCallback(e)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;!1==="requestVideoFrameCallback"in t&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){0!==this._requestVideoFrameCallbackId&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class nh extends rh{constructor(t,e,i,s,r,n,a,o){super({},t,e,i,s,r,n,a,o),this.isVideoFrameTexture=!0}update(){}clone(){return(new this.constructor).copy(this)}setFrame(t){this.image=t,this.needsUpdate=!0}}class ah extends qs{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=ft,this.minFilter=ft,this.generateMipmaps=!1,this.needsUpdate=!0}}class oh extends qs{constructor(t,e,i,s,r,n,a,o,h,l,c,u){super(null,n,a,o,h,l,s,r,c,u),this.isCompressedTexture=!0,this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class hh extends oh{constructor(t,e,i,s,r,n){super(t,e,i,r,n),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=yt,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class lh extends oh{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,lt),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class ch extends qs{constructor(t=[],e=301,i,s,r,n,a,o,h,l){super(t,e,i,s,r,n,a,o,h,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class uh extends qs{constructor(t,e,i,s,r,n,a,o,h){super(t,e,i,s,r,n,a,o,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class dh extends qs{constructor(t,e,i,s,r,n,a,o,h){super(t,e,i,s,r,n,a,o,h),this.isHTMLTexture=!0,this.generateMipmaps=!1,this.needsUpdate=!0;const l=t?t.parentNode:null;null!==l&&"requestPaint"in l&&(l.onpaint=()=>{this.needsUpdate=!0},l.requestPaint())}dispose(){const t=this.image?this.image.parentNode:null;null!==t&&"onpaint"in t&&(t.onpaint=null),super.dispose()}}class ph extends qs{constructor(t,e,i=1014,s,r,n,a=1003,o=1003,h,l=1026,c=1){if(l!==Wt&&1027!==l)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:t,height:e,depth:c},s,r,n,a,o,l,i,h),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new js(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return null!==this.compareFunction&&(e.compareFunction=this.compareFunction),e}}class mh extends ph{constructor(t,e=1014,i=301,s,r,n=1003,a=1003,o,h=1026){const l={width:t,height:t,depth:1},c=[l,l,l,l,l,l];super(t,t,e,i,s,r,n,a,o,h),this.image=c,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class yh extends qs{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class gh extends Wn{constructor(t=1,e=1,i=1,s=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:s,heightSegments:r,depthSegments:n};const a=this;s=Math.floor(s),r=Math.floor(r),n=Math.floor(n);const o=[],h=[],l=[],c=[];let u=0,d=0;function p(t,e,i,s,r,n,p,m,y,g,f){const x=n/y,b=p/g,v=n/2,w=p/2,M=m/2,S=y+1,_=g+1;let A=0,T=0;const z=new Ts;for(let n=0;n<_;n++){const a=n*b-w;for(let o=0;o0?1:-1,l.push(z.x,z.y,z.z),c.push(o/y),c.push(1-n/g),A+=1}}for(let t=0;t0){const t=(f-1)*m;for(let e=0;e0||0!==s)&&(l.push(n,a,h),x+=3),(e>0||s!==r-1)&&(l.push(a,o,h),x+=3)}h.addGroup(g,x,0),g+=x}(),!1===n&&(t>0&&f(!0),e>0&&f(!1)),this.setIndex(l),this.setAttribute("position",new kn(c,3)),this.setAttribute("normal",new kn(u,3)),this.setAttribute("uv",new kn(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new bh(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class vh extends bh{constructor(t=1,e=1,i=32,s=1,r=!1,n=0,a=2*Math.PI){super(0,t,e,i,s,r,n,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:s,openEnded:r,thetaStart:n,thetaLength:a}}static fromJSON(t){return new vh(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class wh extends Wn{constructor(t=[],e=[],i=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:i,detail:s};const r=[],n=[];function a(t,e,i,s){const r=s+1,n=[];for(let s=0;s<=r;s++){n[s]=[];const a=t.clone().lerp(i,s/r),o=e.clone().lerp(i,s/r),h=r-s;for(let t=0;t<=h;t++)n[s][t]=0===t&&s===r?a:a.clone().lerp(o,t/h)}for(let t=0;t.9&&a<.1&&(e<.2&&(n[t+0]+=1),i<.2&&(n[t+2]+=1),s<.2&&(n[t+4]+=1))}}()}(),this.setAttribute("position",new kn(r,3)),this.setAttribute("normal",new kn(r.slice(),3)),this.setAttribute("uv",new kn(n,2)),0===s?this.computeVertexNormals():this.normalizeNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new wh(t.vertices,t.indices,t.radius,t.detail)}}class Mh extends wh{constructor(t=1,e=0){const i=(1+Math.sqrt(5))/2,s=1/i;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-s,-i,0,-s,i,0,s,-i,0,s,i,-s,-i,0,-s,i,0,s,-i,0,s,i,0,-i,0,-s,i,0,-s,-i,0,s,i,0,s],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Mh(t.radius,t.detail)}}const Sh=new Ts,_h=new Ts,Ah=new Ts,Th=new $r;class zh extends Wn{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const i=4,s=Math.pow(10,i),r=Math.cos(ys*e),n=t.getIndex(),a=t.getAttribute("position"),o=n?n.count:a.count,h=[0,0,0],l=["a","b","c"],c=new Array(3),u={},d=[];for(let t=0;t0)){h=s;break}h=s-1}if(s=h,i[s]===n)return s/(r-1);const l=i[s];return(s+(n-l)/(i[s+1]-l))/(r-1)}getTangent(t,e){const i=1e-4;let s=t-i,r=t+i;s<0&&(s=0),r>1&&(r=1);const n=this.getPoint(s),a=this.getPoint(r),o=e||(n.isVector2?new _s:new Ts);return o.copy(a).sub(n).normalize(),o}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e=!1){const i=new Ts,s=[],r=[],n=[],a=new Ts,o=new Qs;for(let e=0;e<=t;e++){const i=e/t;s[e]=this.getTangentAt(i,new Ts)}r[0]=new Ts,n[0]=new Ts;let h=Number.MAX_VALUE;const l=Math.abs(s[0].x),c=Math.abs(s[0].y),u=Math.abs(s[0].z);l<=h&&(h=l,i.set(1,0,0)),c<=h&&(h=c,i.set(0,1,0)),u<=h&&i.set(0,0,1),a.crossVectors(s[0],i).normalize(),r[0].crossVectors(s[0],a),n[0].crossVectors(s[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),n[e]=n[e-1].clone(),a.crossVectors(s[e-1],s[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(xs(s[e-1].dot(s[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}n[e].crossVectors(s[e],r[e])}if(!0===e){let e=Math.acos(xs(r[0].dot(r[t]),-1,1));e/=t,s[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let i=1;i<=t;i++)r[i].applyMatrix4(o.makeRotationAxis(s[i],e*i)),n[i].crossVectors(s[i],r[i])}return{tangents:s,normals:r,binormals:n}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Ih extends Ch{constructor(t=0,e=0,i=1,s=1,r=0,n=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=s,this.aStartAngle=r,this.aEndAngle=n,this.aClockwise=a,this.aRotation=o}getPoint(t,e=new _s){const i=e,s=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const n=Math.abs(r)s;)r-=s;r0?0:(Math.floor(Math.abs(h)/r)+1)*r:0===l&&h===r-1&&(h=r-2,l=1),this.closed||h>0?a=s[(h-1)%r]:(Ph.subVectors(s[0],s[1]).add(s[0]),a=Ph);const c=s[h%r],u=s[(h+1)%r];if(this.closed||h+2s.length-2?s.length-1:n+1],c=s[n>s.length-3?s.length-1:n+2];return i.set(Lh(a,o.x,h.x,l.x,c.x),Lh(a,o.y,h.y,l.y,c.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e=i){const t=s[r]-i,n=this.curves[r],a=n.getLength(),o=0===a?0:1-t/a;return n.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,s=this.curves.length;i1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e0){const t=h.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(h);const l=h.getPoint(1);return this.currentPoint.copy(l),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class $h extends Gh{constructor(t){super(t),this.uuid=fs(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,s=this.holes.length;i80*i){o=t[0],h=t[1];let e=o,s=h;for(let n=i;ne&&(e=i),r>s&&(s=r)}l=Math.max(e-o,s-h),l=0!==l?32767/l:0}return el(n,a,i,o,h,l,0),a}function Kh(t,e,i,s,r){let n;if(r===function(t,e,i,s){let r=0;for(let n=e,a=i-s;n0)for(let r=e;r=e;r-=s)n=wl(r/s|0,t[r],t[r+1],n);return n&&yl(n,n.next)&&(Ml(n),n=n.next),n}function tl(t,e){if(!t)return t;e||(e=t);let i,s=t;do{if(i=!1,s.steiner||!yl(s,s.next)&&0!==ml(s.prev,s,s.next))s=s.next;else{if(Ml(s),s=e=s.prev,s===s.next)break;i=!0}}while(i||s!==e);return e}function el(t,e,i,s,r,n,a){if(!t)return;!a&&n&&function(t,e,i,s){let r=t;do{0===r.z&&(r.z=ll(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,i=1;do{let s,r=t;t=null;let n=null;for(e=0;r;){e++;let a=r,o=0;for(let t=0;t0||h>0&&a;)0!==o&&(0===h||!a||r.z<=a.z)?(s=r,r=r.nextZ,o--):(s=a,a=a.nextZ,h--),n?n.nextZ=s:t=s,s.prevZ=n,n=s;r=a}n.nextZ=null,i*=2}while(e>1)}(r)}(t,s,r,n);let o=t;for(;t.prev!==t.next;){const h=t.prev,l=t.next;if(n?sl(t,s,r,n):il(t))e.push(h.i,t.i,l.i),Ml(t),t=l.next,o=l.next;else if((t=l)===o){a?1===a?el(t=rl(tl(t),e),e,i,s,r,n,2):2===a&&nl(t,e,i,s,r,n):el(tl(t),e,i,s,r,n,1);break}}}function il(t){const e=t.prev,i=t,s=t.next;if(ml(e,i,s)>=0)return!1;const r=e.x,n=i.x,a=s.x,o=e.y,h=i.y,l=s.y,c=Math.min(r,n,a),u=Math.min(o,h,l),d=Math.max(r,n,a),p=Math.max(o,h,l);let m=s.next;for(;m!==e;){if(m.x>=c&&m.x<=d&&m.y>=u&&m.y<=p&&dl(r,o,n,h,a,l,m.x,m.y)&&ml(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function sl(t,e,i,s){const r=t.prev,n=t,a=t.next;if(ml(r,n,a)>=0)return!1;const o=r.x,h=n.x,l=a.x,c=r.y,u=n.y,d=a.y,p=Math.min(o,h,l),m=Math.min(c,u,d),y=Math.max(o,h,l),g=Math.max(c,u,d),f=ll(p,m,e,i,s),x=ll(y,g,e,i,s);let b=t.prevZ,v=t.nextZ;for(;b&&b.z>=f&&v&&v.z<=x;){if(b.x>=p&&b.x<=y&&b.y>=m&&b.y<=g&&b!==r&&b!==a&&dl(o,c,h,u,l,d,b.x,b.y)&&ml(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=p&&v.x<=y&&v.y>=m&&v.y<=g&&v!==r&&v!==a&&dl(o,c,h,u,l,d,v.x,v.y)&&ml(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=f;){if(b.x>=p&&b.x<=y&&b.y>=m&&b.y<=g&&b!==r&&b!==a&&dl(o,c,h,u,l,d,b.x,b.y)&&ml(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=x;){if(v.x>=p&&v.x<=y&&v.y>=m&&v.y<=g&&v!==r&&v!==a&&dl(o,c,h,u,l,d,v.x,v.y)&&ml(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function rl(t,e){let i=t;do{const s=i.prev,r=i.next.next;!yl(s,r)&&gl(s,i,i.next,r)&&bl(s,r)&&bl(r,s)&&(e.push(s.i,i.i,r.i),Ml(i),Ml(i.next),i=t=r),i=i.next}while(i!==t);return tl(i)}function nl(t,e,i,s,r,n){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&pl(a,t)){let o=vl(a,t);return a=tl(a,a.next),o=tl(o,o.next),el(a,e,i,s,r,n,0),void el(o,e,i,s,r,n,0)}t=t.next}a=a.next}while(a!==t)}function al(t,e){let i=t.x-e.x;if(0===i&&(i=t.y-e.y,0===i)){i=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)}return i}function ol(t,e){const i=function(t,e){let i=e;const s=t.x,r=t.y;let n,a=-1/0;if(yl(t,i))return i;do{if(yl(t,i.next))return i.next;if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const t=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=s&&t>a&&(a=t,n=i.x=i.x&&i.x>=h&&s!==i.x&&ul(rn.x||i.x===n.x&&hl(n,i)))&&(n=i,c=e)}i=i.next}while(i!==o);return n}(t,e);if(!i)return e;const s=vl(i,t);return tl(s,s.next),tl(i,i.next)}function hl(t,e){return ml(t.prev,t,e.prev)<0&&ml(e.next,t,t.next)<0}function ll(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function cl(t){let e=t,i=t;do{(e.x=(t-a)*(n-o)&&(t-a)*(s-o)>=(i-a)*(e-o)&&(i-a)*(n-o)>=(r-a)*(s-o)}function dl(t,e,i,s,r,n,a,o){return!(t===a&&e===o)&&ul(t,e,i,s,r,n,a,o)}function pl(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&gl(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(bl(t,e)&&bl(e,t)&&function(t,e){let i=t,s=!1;const r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(ml(t.prev,t,e.prev)||ml(t,e.prev,e))||yl(t,e)&&ml(t.prev,t,t.next)>0&&ml(e.prev,e,e.next)>0)}function ml(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function yl(t,e){return t.x===e.x&&t.y===e.y}function gl(t,e,i,s){const r=xl(ml(t,e,i)),n=xl(ml(t,e,s)),a=xl(ml(i,s,t)),o=xl(ml(i,s,e));return r!==n&&a!==o||(!(0!==r||!fl(t,i,e))||(!(0!==n||!fl(t,s,e))||(!(0!==a||!fl(i,t,s))||!(0!==o||!fl(i,e,s)))))}function fl(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function xl(t){return t>0?1:t<0?-1:0}function bl(t,e){return ml(t.prev,t,t.next)<0?ml(t,e,t.next)>=0&&ml(t,t.prev,e)>=0:ml(t,e,t.prev)<0||ml(t,t.next,e)<0}function vl(t,e){const i=Sl(t.i,t.x,t.y),s=Sl(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function wl(t,e,i,s){const r=Sl(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function Ml(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Sl(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class _l{static triangulate(t,e,i=2){return Qh(t,e,i)}}class Al{static area(t){const e=t.length;let i=0;for(let s=e-1,r=0;r2&&t[e-1].equals(t[0])&&t.pop()}function zl(t,e){for(let i=0;iNumber.EPSILON){const u=Math.sqrt(c),d=Math.sqrt(h*h+l*l),p=e.x-o/u,m=e.y+a/u,y=((i.x-l/d-p)*l-(i.y+h/d-m)*h)/(a*l-o*h);s=p+a*y-t.x,r=m+o*y-t.y;const g=s*s+r*r;if(g<=2)return new _s(s,r);n=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?h>Number.EPSILON&&(t=!0):a<-Number.EPSILON?h<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(l)&&(t=!0),t?(s=-o,r=a,n=Math.sqrt(c)):(s=a,r=o,n=Math.sqrt(c/2))}return new _s(s/n,r/n)}const k=[];for(let t=0,e=z.length,i=e-1,s=t+1;t=0;t--){const e=t/p,i=c*Math.cos(e*Math.PI/2),s=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=z.length;t=0;){const s=i;let r=i-1;r<0&&(r=t.length-1);for(let t=0,i=o+2*p;t0)&&d.push(e,r,h),(t!==i-1||o0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const i={};for(const t in this.extensions)!0===this.extensions[t]&&(i[t]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}}class Gl extends Zl{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class $l extends Zn{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Pr(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 Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(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 hr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class Ql extends $l{constructor(t){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 _s(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return xs(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Pr(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 Pr(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Pr(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(t)}get anisotropy(){return this._anisotropy}set anisotropy(t){this._anisotropy>0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class Kl extends Zn{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Pr(16777215),this.specular=new Pr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class tc extends Zn{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Pr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class ec extends Zn{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class ic extends Zn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Pr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class sc extends Zn{constructor(t){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(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class rc extends Zn{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}class nc extends Zn{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Pr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(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(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ac extends Eo{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function oc(t,e){return t&&t.constructor!==e?"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t):t}function hc(t){const e=t.length,i=new Array(e);for(let t=0;t!==e;++t)i[t]=t;return i.sort(function(e,i){return t[e]-t[i]}),i}function lc(t,e,i){const s=t.length,r=new t.constructor(s);for(let n=0,a=0;a!==s;++n){const s=i[n]*e;for(let i=0;i!==e;++i)r[a++]=t[s+i]}return r}function cc(t,e,i,s){let r=1,n=t[0];for(;void 0!==n&&void 0===n[s];)n=t[r++];if(void 0===n)return;let a=n[s];if(void 0!==a)if(Array.isArray(a))do{a=n[s],void 0!==a&&(e.push(n.time),i.push(...a)),n=t[r++]}while(void 0!==n);else if(void 0!==a.toArray)do{a=n[s],void 0!==a&&(e.push(n.time),a.toArray(i,i.length)),n=t[r++]}while(void 0!==n);else do{a=n[s],void 0!==a&&(e.push(n.time),i.push(a)),n=t[r++]}while(void 0!==n)}class uc{static convertArray(t,e){return oc(t,e)}static isTypedArray(t){return $i(t)}static getKeyframeOrder(t){return hc(t)}static sortedArray(t,e,i){return lc(t,e,i)}static flattenJSON(t,e,i,s){cc(t,e,i,s)}static subclip(t,e,i,s,r=30){return function(t,e,i,s,r=30){const n=t.clone();n.name=e;const a=[];for(let t=0;t=s)){h.push(e.times[t]);for(let i=0;in.tracks[t].times[0]&&(o=n.tracks[t].times[0]);for(let t=0;t=s.times[u]){const t=u*h+o,e=t+h-o;d=s.values.slice(t,e)}else{const t=s.createInterpolant(),e=o,i=h-o;t.evaluate(n),d=t.resultBuffer.slice(e,i)}"quaternion"===r&&(new As).fromArray(d).normalize().conjugate().toArray(d);const p=a.times.length;for(let t=0;t=r)){const a=e[1];t=r)break e}n=i,i=0;break i}break t}for(;i>>1;te;)--n;if(++n,0!==r||n!==s){r>=n&&(n=Math.max(n,1),r=n-1);const t=this.getValueSize();this.times=i.slice(r,n),this.values=this.values.slice(r*t,n*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!==0&&(os("KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,s=this.values,r=i.length;0===r&&(os("KeyframeTrack: Track is empty.",this),t=!1);let n=null;for(let e=0;e!==r;e++){const s=i[e];if("number"==typeof s&&isNaN(s)){os("KeyframeTrack: Time is not a valid number.",this,e,s),t=!1;break}if(null!==n&&n>s){os("KeyframeTrack: Out of order keys.",this,e,s,n),t=!1;break}n=s}if(void 0!==s&&$i(s))for(let e=0,i=s.length;e!==i;++e){const i=s[e];if(isNaN(i)){os("KeyframeTrack: Value is not a valid number.",this,e,i),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===Le,r=t.length-1;let n=1;for(let a=1;a0){t[n]=t[r];for(let t=r*i,s=n*i,a=0;a!==i;++a)e[s+a]=e[t+a];++n}return n!==t.length?(this.times=t.slice(0,n),this.values=e.slice(0,n*i)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),i=new(0,this.constructor)(this.name,t,e);return i.createInterpolant=this.createInterpolant,i}}fc.prototype.ValueTypeName="",fc.prototype.TimeBufferType=Float32Array,fc.prototype.ValueBufferType=Float32Array,fc.prototype.DefaultInterpolation=Ee;class xc extends fc{constructor(t,e,i){super(t,e,i)}}xc.prototype.ValueTypeName="bool",xc.prototype.ValueBufferType=Array,xc.prototype.DefaultInterpolation=Ve,xc.prototype.InterpolantFactoryMethodLinear=void 0,xc.prototype.InterpolantFactoryMethodSmooth=void 0;class bc extends fc{constructor(t,e,i,s){super(t,e,i,s)}}bc.prototype.ValueTypeName="color";class vc extends fc{constructor(t,e,i,s){super(t,e,i,s)}}vc.prototype.ValueTypeName="number";class wc extends dc{constructor(t,e,i,s){super(t,e,i,s)}interpolate_(t,e,i,s){const r=this.resultBuffer,n=this.sampleValues,a=this.valueSize,o=(i-e)/(s-e);let h=t*a;for(let t=h+a;h!==t;h+=4)As.slerpFlat(r,0,n,h-a,n,h,o);return r}}class Mc extends fc{constructor(t,e,i,s){super(t,e,i,s)}InterpolantFactoryMethodLinear(t){return new wc(this.times,this.values,this.getValueSize(),t)}}Mc.prototype.ValueTypeName="quaternion",Mc.prototype.InterpolantFactoryMethodSmooth=void 0;class Sc extends fc{constructor(t,e,i){super(t,e,i)}}Sc.prototype.ValueTypeName="string",Sc.prototype.ValueBufferType=Array,Sc.prototype.DefaultInterpolation=Ve,Sc.prototype.InterpolantFactoryMethodLinear=void 0,Sc.prototype.InterpolantFactoryMethodSmooth=void 0;class _c extends fc{constructor(t,e,i,s){super(t,e,i,s)}}_c.prototype.ValueTypeName="vector";class Ac{constructor(t="",e=-1,i=[],s=2500){this.name=t,this.tracks=i,this.duration=e,this.blendMode=s,this.uuid=fs(),this.userData={},this.duration<0&&this.resetDuration()}static parse(t){const e=[],i=t.tracks,s=1/(t.fps||1);for(let t=0,r=i.length;t!==r;++t)e.push(Tc(i[t]).scale(s));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r.userData=JSON.parse(t.userData||"{}"),r}static toJSON(t){const e=[],i=t.tracks,s={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode,userData:JSON.stringify(t.userData)};for(let t=0,s=i.length;t!==s;++t)e.push(fc.toJSON(i[t]));return s}static CreateFromMorphTargetSequence(t,e,i,s){const r=e.length,n=[];for(let t=0;t1){const t=n[1];let e=s[t];e||(s[t]=e=[]),e.push(i)}}const n=[];for(const t in s)n.push(this.CreateFromMorphTargetSequence(t,s[t],e,i));return n}static parseAnimation(t,e){if(as("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!t)return os("AnimationClip: No animation in JSONLoader data."),null;const i=function(t,e,i,s,r){if(0!==i.length){const n=[],a=[];cc(i,n,a,s),0!==n.length&&r.push(new t(e,n,a))}},s=[],r=t.name||"default",n=t.fps||30,a=t.blendMode;let o=t.length||-1;const h=t.hierarchy||[];for(let t=0;t{e&&e(r),this.manager.itemEnd(t)},0),r;if(void 0!==Oc[t])return void Oc[t].push({onLoad:e,onProgress:i,onError:s});Oc[t]=[],Oc[t].push({onLoad:e,onProgress:i,onError:s});const n=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:"function"==typeof AbortSignal.any?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,o=this.responseType;fetch(n).then(e=>{if(200===e.status||0===e.status){if(0===e.status&&as("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const i=Oc[t],s=e.body.getReader(),r=e.headers.get("X-File-Size")||e.headers.get("Content-Length"),n=r?parseInt(r):0,a=0!==n;let o=0;const h=new ReadableStream({start(t){!function e(){s.read().then(({done:s,value:r})=>{if(s)t.close();else{o+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:n});for(let t=0,e=i.length;t{t.error(e)})}()}});return new Response(h)}throw new Pc(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`,e)}).then(t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then(t=>(new DOMParser).parseFromString(t,a));case"json":return t.json();default:if(""===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),i=e&&e[1]?e[1].toLowerCase():void 0,s=new TextDecoder(i);return t.arrayBuffer().then(t=>s.decode(t))}}}).then(e=>{zc.add(`file:${t}`,e);const i=Oc[t];delete Oc[t];for(let t=0,s=i.length;t{const i=Oc[t];if(void 0===i)throw this.manager.itemError(t),e;delete Oc[t];for(let t=0,s=i.length;t{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class Nc extends kc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new Rc(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(t,function(i){try{e(r.parse(JSON.parse(i)))}catch(e){s?s(e):os(e),r.manager.itemError(t)}},i,s)}parse(t){const e=[];for(let i=0;i0:s.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(s.uniforms[e]={},r.type){case"t":s.uniforms[e].value=i(r.value);break;case"c":s.uniforms[e].value=(new Pr).setHex(r.value);break;case"v2":s.uniforms[e].value=(new _s).fromArray(r.value);break;case"v3":s.uniforms[e].value=(new Ts).fromArray(r.value);break;case"v4":s.uniforms[e].value=(new Js).fromArray(r.value);break;case"m3":s.uniforms[e].value=(new Is).fromArray(r.value);break;case"m4":s.uniforms[e].value=(new Qs).fromArray(r.value);break;default:s.uniforms[e].value=r.value}}if(void 0!==t.defines&&(s.defines=t.defines),void 0!==t.vertexShader&&(s.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(s.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(s.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)s.extensions[e]=t.extensions[e];if(void 0!==t.lights&&(s.lights=t.lights),void 0!==t.clipping&&(s.clipping=t.clipping),void 0!==t.size&&(s.size=t.size),void 0!==t.sizeAttenuation&&(s.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(s.map=i(t.map)),void 0!==t.matcap&&(s.matcap=i(t.matcap)),void 0!==t.alphaMap&&(s.alphaMap=i(t.alphaMap)),void 0!==t.bumpMap&&(s.bumpMap=i(t.bumpMap)),void 0!==t.bumpScale&&(s.bumpScale=t.bumpScale),void 0!==t.normalMap&&(s.normalMap=i(t.normalMap)),void 0!==t.normalMapType&&(s.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),s.normalScale=(new _s).fromArray(e)}return void 0!==t.displacementMap&&(s.displacementMap=i(t.displacementMap)),void 0!==t.displacementScale&&(s.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(s.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(s.roughnessMap=i(t.roughnessMap)),void 0!==t.metalnessMap&&(s.metalnessMap=i(t.metalnessMap)),void 0!==t.emissiveMap&&(s.emissiveMap=i(t.emissiveMap)),void 0!==t.emissiveIntensity&&(s.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(s.specularMap=i(t.specularMap)),void 0!==t.specularIntensityMap&&(s.specularIntensityMap=i(t.specularIntensityMap)),void 0!==t.specularColorMap&&(s.specularColorMap=i(t.specularColorMap)),void 0!==t.envMap&&(s.envMap=i(t.envMap)),void 0!==t.envMapRotation&&s.envMapRotation.fromArray(t.envMapRotation),void 0!==t.envMapIntensity&&(s.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(s.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(s.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(s.lightMap=i(t.lightMap)),void 0!==t.lightMapIntensity&&(s.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(s.aoMap=i(t.aoMap)),void 0!==t.aoMapIntensity&&(s.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(s.gradientMap=i(t.gradientMap)),void 0!==t.clearcoatMap&&(s.clearcoatMap=i(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(s.clearcoatRoughnessMap=i(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(s.clearcoatNormalMap=i(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(s.clearcoatNormalScale=(new _s).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(s.iridescenceMap=i(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(s.iridescenceThicknessMap=i(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(s.transmissionMap=i(t.transmissionMap)),void 0!==t.thicknessMap&&(s.thicknessMap=i(t.thicknessMap)),void 0!==t.anisotropyMap&&(s.anisotropyMap=i(t.anisotropyMap)),void 0!==t.sheenColorMap&&(s.sheenColorMap=i(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(s.sheenRoughnessMap=i(t.sheenRoughnessMap)),s}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return pu.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:ql,SpriteMaterial:Gn,RawShaderMaterial:Gl,ShaderMaterial:Zl,PointsMaterial:$o,MeshPhysicalMaterial:Ql,MeshStandardMaterial:$l,MeshPhongMaterial:Kl,MeshToonMaterial:tc,MeshNormalMaterial:ec,MeshLambertMaterial:ic,MeshDepthMaterial:sc,MeshDistanceMaterial:rc,MeshBasicMaterial:Ma,MeshMatcapMaterial:nc,LineDashedMaterial:ac,LineBasicMaterial:Eo,Material:Zn}[t]}}class mu{static extractUrlBase(t){const e=t.lastIndexOf("/");return-1===e?"./":t.slice(0,e+1)}static resolveURL(t,e){return"string"!=typeof t||""===t?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}}class yu extends Wn{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}toJSON(){const t=super.toJSON();return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}class gu extends kc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new Rc(r.manager);n.setPath(r.path),n.setRequestHeader(r.requestHeader),n.setWithCredentials(r.withCredentials),n.load(t,function(i){try{e(r.parse(JSON.parse(i)))}catch(e){s?s(e):os(e),r.manager.itemError(t)}},i,s)}parse(t){const e={},i={};function s(t,s){if(void 0!==e[s])return e[s];const r=t.interleavedBuffers[s],n=function(t,e){if(void 0!==i[e])return i[e];const s=t.arrayBuffers,r=s[e],n=new Uint32Array(r).buffer;return i[e]=n,n}(t,r.buffer),a=Gi(r.type,n),o=new qn(a,r.stride);return o.uuid=r.uuid,e[s]=o,o}const r=t.isInstancedBufferGeometry?new yu:new Wn,n=t.data.index;if(void 0!==n){const t=Gi(n.type,n.array);r.setIndex(new Mn(t,1))}const a=t.data.attributes;for(const e in a){const i=a[e];let n;if(i.isInterleavedBufferAttribute){const e=s(t.data,i.data);n=new Xn(e,i.itemSize,i.offset,i.normalized)}else{const t=Gi(i.type,i.array);n=new(i.isInstancedBufferAttribute?$a:Mn)(t,i.itemSize,i.normalized)}void 0!==i.name&&(n.name=i.name),void 0!==i.usage&&n.setUsage(i.usage),r.setAttribute(e,n)}const o=t.data.morphAttributes;if(o)for(const e in o){const i=o[e],n=[];for(let e=0,r=i.length;e0){const i=new Ic(e);r=new Lc(i),r.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e0){s=new Lc(this.manager),s.setCrossOrigin(this.crossOrigin);for(let e=0,s=t.length;e{let e=null,i=null;return void 0!==t.boundingBox&&(e=(new Qr).fromJSON(t.boundingBox)),void 0!==t.boundingSphere&&(i=(new Nn).fromJSON(t.boundingSphere)),{...t,boundingBox:e,boundingSphere:i}}),n._instanceInfo=t.instanceInfo,n._availableInstanceIds=t._availableInstanceIds,n._availableGeometryIds=t._availableGeometryIds,n._nextIndexStart=t.nextIndexStart,n._nextVertexStart=t.nextVertexStart,n._geometryCount=t.geometryCount,n._maxInstanceCount=t.maxInstanceCount,n._maxVertexCount=t.maxVertexCount,n._maxIndexCount=t.maxIndexCount,n._geometryInitialized=t.geometryInitialized,n._matricesTexture=c(t.matricesTexture.uuid),n._indirectTexture=c(t.indirectTexture.uuid),void 0!==t.colorsTexture&&(n._colorsTexture=c(t.colorsTexture.uuid)),void 0!==t.boundingSphere&&(n.boundingSphere=(new Nn).fromJSON(t.boundingSphere)),void 0!==t.boundingBox&&(n.boundingBox=(new Qr).fromJSON(t.boundingBox));break;case"LOD":n=new pa;break;case"Line":n=new Jo(h(t.geometry),l(t.material));break;case"LineLoop":n=new Go(h(t.geometry),l(t.material));break;case"LineSegments":n=new Zo(h(t.geometry),l(t.material));break;case"PointCloud":case"Points":n=new ih(h(t.geometry),l(t.material));break;case"Sprite":n=new la(l(t.material));break;case"Group":n=new Tr;break;case"Bone":n=new Xa;break;default:n=new Ar}if(n.uuid=t.uuid,void 0!==t.name&&(n.name=t.name),void 0!==t.matrix?(n.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(n.matrixAutoUpdate=t.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==t.position&&n.position.fromArray(t.position),void 0!==t.rotation&&n.rotation.fromArray(t.rotation),void 0!==t.quaternion&&n.quaternion.fromArray(t.quaternion),void 0!==t.scale&&n.scale.fromArray(t.scale)),void 0!==t.up&&n.up.fromArray(t.up),void 0!==t.pivot&&(n.pivot=(new Ts).fromArray(t.pivot)),void 0!==t.morphTargetDictionary&&(n.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),void 0!==t.morphTargetInfluences&&(n.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.castShadow&&(n.castShadow=t.castShadow),void 0!==t.receiveShadow&&(n.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(n.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(n.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(n.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(n.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&n.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(n.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(n.visible=t.visible),void 0!==t.frustumCulled&&(n.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(n.renderOrder=t.renderOrder),void 0!==t.static&&(n.static=t.static),void 0!==t.userData&&(n.userData=t.userData),void 0!==t.layers&&(n.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t{if(!0!==Mu.has(n))return e&&e(i),r.manager.itemEnd(t),i;s&&s(Mu.get(n)),r.manager.itemError(t),r.manager.itemEnd(t)}):(setTimeout(function(){e&&e(n),r.manager.itemEnd(t)},0),n);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader,a.signal="function"==typeof AbortSignal.any?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const o=fetch(t,a).then(function(t){return t.blob()}).then(function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(i){return zc.add(`image-bitmap:${t}`,i),e&&e(i),r.manager.itemEnd(t),i}).catch(function(e){s&&s(e),Mu.set(o,e),zc.remove(`image-bitmap:${t}`),r.manager.itemError(t),r.manager.itemEnd(t)});zc.add(`image-bitmap:${t}`,o),r.manager.itemStart(t)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let _u;class Au{static getContext(){return void 0===_u&&(_u=new(window.AudioContext||window.webkitAudioContext)),_u}static setContext(t){_u=t}}class Tu extends kc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new Rc(this.manager);function a(e){s?s(e):os(e),r.manager.itemError(t)}n.setResponseType("arraybuffer"),n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(t,function(t){try{const i=t.slice(0);Au.getContext().decodeAudioData(i,function(t){e(t)}).catch(a)}catch(t){a(t)}},i,s)}}const zu=new Qs,Cu=new Qs,Iu=new Qs;class Bu{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new eu,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new eu,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(t){const e=this._cache;if(e.focus!==t.focus||e.fov!==t.fov||e.aspect!==t.aspect*this.aspect||e.near!==t.near||e.far!==t.far||e.zoom!==t.zoom||e.eyeSep!==this.eyeSep){e.focus=t.focus,e.fov=t.fov,e.aspect=t.aspect*this.aspect,e.near=t.near,e.far=t.far,e.zoom=t.zoom,e.eyeSep=this.eyeSep,Iu.copy(t.projectionMatrix);const i=e.eyeSep/2,s=i*e.near/e.focus,r=e.near*Math.tan(ys*e.fov*.5)/e.zoom;let n,a;Cu.elements[12]=-i,zu.elements[12]=i,n=-r*e.aspect+s,a=r*e.aspect+s,Iu.elements[0]=2*e.near/(a-n),Iu.elements[8]=(a+n)/(a-n),this.cameraL.projectionMatrix.copy(Iu),n=-r*e.aspect-s,a=r*e.aspect-s,Iu.elements[0]=2*e.near/(a-n),Iu.elements[8]=(a+n)/(a-n),this.cameraR.projectionMatrix.copy(Iu)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Cu),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(zu)}}const ku=-90;class Ou extends Ar{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new eu(ku,1,t,e);s.layers=this.layers,this.add(s);const r=new eu(ku,1,t,e);r.layers=this.layers,this.add(r);const n=new eu(ku,1,t,e);n.layers=this.layers,this.add(n);const a=new eu(ku,1,t,e);a.layers=this.layers,this.add(a);const o=new eu(ku,1,t,e);o.layers=this.layers,this.add(o);const h=new eu(ku,1,t,e);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[i,s,r,n,a,o]=e;for(const t of e)this.remove(t);if(t===Wi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==qi)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,n,a,o,h,l]=this.children,c=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let y=!1;y=!0===t.isWebGLRenderer?t.state.buffers.depth.getReversed():t.reversedDepthBuffer,t.setRenderTarget(i,0,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,r),t.setRenderTarget(i,1,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,n),t.setRenderTarget(i,2,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,a),t.setRenderTarget(i,3,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,o),t.setRenderTarget(i,4,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,h),i.texture.generateMipmaps=m,t.setRenderTarget(i,5,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,l),t.setRenderTarget(c,u,d),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class Pu extends eu{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class Ru{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(t){this._document=t,void 0!==t.hidden&&(this._pageVisibilityHandler=Nu.bind(this),t.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(t){return this._timescale=t,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(t){return null!==this._pageVisibilityHandler&&!0===this._document.hidden?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(void 0!==t?t:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}}function Nu(){!1===this._document.hidden&&this.reset()}const Vu=new Ts,Eu=new As,Lu=new Ts,Fu=new Ts,ju=new Ts;class Du extends Ar{constructor(){super(),this.type="AudioListener",this.context=Au.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new Ru}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(t){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=t,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}updateMatrixWorld(t){super.updateMatrixWorld(t),this._timer.update();const e=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(Vu,Eu,Lu),Fu.set(0,0,-1).applyQuaternion(Eu),ju.set(0,1,0).applyQuaternion(Eu),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(Vu.x,t),e.positionY.linearRampToValueAtTime(Vu.y,t),e.positionZ.linearRampToValueAtTime(Vu.z,t),e.forwardX.linearRampToValueAtTime(Fu.x,t),e.forwardY.linearRampToValueAtTime(Fu.y,t),e.forwardZ.linearRampToValueAtTime(Fu.z,t),e.upX.linearRampToValueAtTime(ju.x,t),e.upY.linearRampToValueAtTime(ju.y,t),e.upZ.linearRampToValueAtTime(ju.z,t)}else e.setPosition(Vu.x,Vu.y,Vu.z),e.setOrientation(Fu.x,Fu.y,Fu.z,ju.x,ju.y,ju.z)}}class Uu extends Ar{constructor(t){super(),this.type="Audio",this.listener=t,this.context=t.context,this.gain=this.context.createGain(),this.gain.connect(t.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(t){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=t,this.connect(),this}setMediaElementSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(t),this.connect(),this}setMediaStreamSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(t),this.connect(),this}setBuffer(t){return this.buffer=t,this.sourceType="buffer",this.autoplay&&this.play(),this}play(t=0){if(!0===this.isPlaying)return void as("Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void as("Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+t;const e=this.context.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.onended=this.onEnded.bind(this),e.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=e,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;as("Audio: this Audio has no playback control.")}stop(t=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+t),this.source.onended=null),this.isPlaying=!1,this;as("Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(i,s,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(i[t]!==i[t+e]){a.setValue(i,s);break}}saveOriginalState(){const t=this.binding,e=this.buffer,i=this.valueSize,s=i*this._origIndex;t.getValue(e,s);for(let t=i,r=s;t!==r;++t)e[t]=e[s+t%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let i=t;i=.5)for(let s=0;s!==r;++s)t[e+s]=t[i+s]}_slerp(t,e,i,s){As.slerpFlat(t,e,t,e,t,i,s)}_slerpAdditive(t,e,i,s,r){const n=this._workIndex*r;As.multiplyQuaternionsFlat(t,n,t,e,t,i),As.slerpFlat(t,e,t,e,t,n,s)}_lerp(t,e,i,s,r){const n=1-s;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*n+t[i+a]*s}}_lerpAdditive(t,e,i,s,r){for(let n=0;n!==r;++n){const r=e+n;t[r]=t[r]+t[i+n]*s}}}const Gu="\\[\\]\\.:\\/",$u=new RegExp("["+Gu+"]","g"),Qu="[^"+Gu+"]",Ku="[^"+Gu.replace("\\.","")+"]",td=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Qu)+/(WCOD+)?/.source.replace("WCOD",Ku)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Qu)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Qu)+"$"),ed=["material","materials","bones","map"];class id{constructor(t,e,i){this.path=e,this.parsedPath=i||id.parseTrackName(e),this.node=id.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,i){return t&&t.isAnimationObjectGroup?new id.Composite(t,e,i):new id(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace($u,"")}static parseTrackName(t){const e=td.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const i={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(void 0!==s&&-1!==s){const t=i.nodeName.substring(s+1);-1!==ed.indexOf(t)&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=t)}if(null===i.propertyName||0===i.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return i}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const i=t.skeleton.getBoneByName(e);if(void 0!==i)return i}if(t.children){const i=function(t){for(let s=0;s=r){const n=r++,l=t[n];e[l.uuid]=h,t[h]=l,e[o]=n,t[n]=a;for(let t=0,e=s;t!==e;++t){const e=i[t],s=e[n],r=e[h];e[h]=s,e[n]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,i=this._bindings,s=i.length;let r=this.nCachedObjects_,n=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,h=e[o];if(void 0!==h)if(delete e[o],h0&&(e[a.uuid]=h),t[h]=a,t.pop();for(let t=0,e=s;t!==e;++t){const e=i[t];e[h]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const i=this._bindingsIndicesByPath;let s=i[t];const r=this._bindings;if(void 0!==s)return r[s];const n=this._paths,a=this._parsedPaths,o=this._objects,h=o.length,l=this.nCachedObjects_,c=new Array(h);s=r.length,i[t]=s,n.push(t),a.push(e),r.push(c);for(let i=l,s=o.length;i!==s;++i){const s=o[i];c[i]=new id(s,t,e)}return c}unsubscribe_(t){const e=this._bindingsIndicesByPath,i=e[t];if(void 0!==i){const s=this._paths,r=this._parsedPaths,n=this._bindings,a=n.length-1,o=n[a];e[t[a]]=i,n[i]=o,n.pop(),r[i]=r[a],r.pop(),s[i]=s[a],s.pop()}}}class rd{constructor(t,e,i=null,s=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=i,this.blendMode=s;const r=e.tracks,n=r.length,a=new Array(n),o={endingStart:je,endingEnd:je};for(let t=0;t!==n;++t){const e=r[t].createInterpolant(null);a[t]=e,e.settings&&Object.assign(o,e.settings),e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(n),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,i=!1){if(t.fadeOut(e),this.fadeIn(e),!0===i){const i=this._clip.duration,s=t._clip.duration,r=s/i,n=i/s;t.warp(1,r,e),this.warp(n,1,e)}return this}crossFadeTo(t,e,i=!1){return t.crossFadeFrom(this,e,i)}stopFading(){const t=this._weightInterpolant;return null!==t&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,i){const s=this._mixer,r=s.time,n=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=s._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,h=a.sampleValues;return o[0]=r,o[1]=r+i,h[0]=t/n,h[1]=e/n,this}stopWarping(){const t=this._timeScaleInterpolant;return null!==t&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,i,s){if(!this.enabled)return void this._updateWeight(t);const r=this._startTime;if(null!==r){const s=(t-r)*i;s<0||0===i?e=0:(this._startTime=null,e=i*s)}e*=this._updateTimeScale(t);const n=this._updateTime(e),a=this._updateWeight(t);if(a>0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===qe)for(let i=0,s=t.length;i!==s;++i)t[i].evaluate(n),e[i].accumulateAdditive(a);else for(let i=0,r=t.length;i!==r;++i)t[i].evaluate(n),e[i].accumulate(s,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const i=this._weightInterpolant;if(null!==i){const s=i.evaluate(t)[0];e*=s,t>i.parameterPositions[1]&&(this.stopFading(),0===s&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const i=this._timeScaleInterpolant;if(null!==i){e*=i.evaluate(t)[0],t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,i=this.loop;let s=this.time+t,r=this._loopCount;const n=2202===i;if(0===t)return-1===r||!n||1&~r?s:e-s;if(2200===i){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(s>=e)s=e;else{if(!(s<0)){this.time=s;break t}s=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,n)):this._setEndings(0===this.repetitions,!0,n)),s>=e||s<0){const i=Math.floor(s/e);s-=e*i,r+=Math.abs(i);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=t>0?e:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,n)}else this._setEndings(!1,!1,n);this._loopCount=r,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:i})}}else this._loopCount=r,this.time=s;if(n&&!(1&~r))return e-s}return s}_setEndings(t,e,i){const s=this._interpolantSettings;i?(s.endingStart=De,s.endingEnd=De):(s.endingStart=t?this.zeroSlopeAtStart?De:je:Ue,s.endingEnd=e?this.zeroSlopeAtEnd?De:je:Ue)}_scheduleFading(t,e,i){const s=this._mixer,r=s.time;let n=this._weightInterpolant;null===n&&(n=s._lendControlInterpolant(),this._weightInterpolant=n);const a=n.parameterPositions,o=n.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=i,this}}const nd=new Float32Array(1);class ad extends ds{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(t,e){const i=t._localRoot||this._root,s=t._clip.tracks,r=s.length,n=t._propertyBindings,a=t._interpolants,o=i.uuid,h=this._bindingsByRootAndName;let l=h[o];void 0===l&&(l={},h[o]=l);for(let t=0;t!==r;++t){const r=s[t],h=r.name;let c=l[h];if(void 0!==c)++c.referenceCount,n[t]=c;else{if(c=n[t],void 0!==c){null===c._cacheIndex&&(++c.referenceCount,this._addInactiveBinding(c,o,h));continue}const s=e&&e._propertyBindings[t].binding.parsedPath;c=new Zu(id.create(i,h,s),r.ValueTypeName,r.getValueSize()),++c.referenceCount,this._addInactiveBinding(c,o,h),n[t]=c}a[t].resultBuffer=c.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){const e=(t._localRoot||this._root).uuid,i=t._clip.uuid,s=this._actionsByClip[i];this._bindAction(t,s&&s.knownActions[0]),this._addInactiveAction(t,i,e)}const e=t._propertyBindings;for(let t=0,i=e.length;t!==i;++t){const i=e[t];0===i.useCount++&&(this._lendBinding(i),i.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let t=0,i=e.length;t!==i;++t){const i=e[t];0===--i.useCount&&(i.restoreOriginalState(),this._takeBackBinding(i))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return null!==e&&e=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,i=this._nActiveActions,s=this.time+=t,r=Math.sign(t),n=this._accuIndex^=1;for(let a=0;a!==i;++a){e[a]._update(s,t,r,n)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(n);return this}setTime(t){this.time=0;for(let t=0;t=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,wd).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Sd=new Ts,_d=new Ts,Ad=new Ts,Td=new Ts,zd=new Ts,Cd=new Ts,Id=new Ts;class Bd{constructor(t=new Ts,e=new Ts){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Sd.subVectors(t,this.start),_d.subVectors(this.end,this.start);const i=_d.dot(_d);if(0===i)return 0;let s=_d.dot(Sd)/i;return e&&(s=xs(s,0,1)),s}closestPointToPoint(t,e,i){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(t,e=Cd,i=Id){const s=1e-8*1e-8;let r,n;const a=this.start,o=t.start,h=this.end,l=t.end;Ad.subVectors(h,a),Td.subVectors(l,o),zd.subVectors(a,o);const c=Ad.dot(Ad),u=Td.dot(Td),d=Td.dot(zd);if(c<=s&&u<=s)return e.copy(a),i.copy(o),e.sub(i),e.dot(e);if(c<=s)r=0,n=d/u,n=xs(n,0,1);else{const t=Ad.dot(zd);if(u<=s)n=0,r=xs(-t/c,0,1);else{const e=Ad.dot(Td),i=c*u-e*e;r=0!==i?xs((e*d-t*u)/i,0,1):0,n=(e*r+d)/u,n<0?(n=0,r=xs(-t/c,0,1)):n>1&&(n=1,r=xs((e-t)/c,0,1))}}return e.copy(a).addScaledVector(Ad,r),i.copy(o).addScaledVector(Td,n),e.distanceToSquared(i)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const kd=new Ts;class Od extends Ar{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const i=new Wn,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let t=0,e=1,i=32;t1)for(let i=0;i.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{sp.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(sp,e)}}setLength(t,e=.2*t,i=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class op extends Zo{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],i=new Wn;i.setAttribute("position",new kn(e,3)),i.setAttribute("color",new kn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(i,new Eo({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,i){const s=new Pr,r=this.geometry.attributes.color.array;return s.set(t),s.toArray(r,0),s.toArray(r,3),s.set(e),s.toArray(r,6),s.toArray(r,9),s.set(i),s.toArray(r,12),s.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class hp{constructor(){this.type="ShapePath",this.color=new Pr,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new Gh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(t,e),this}lineTo(t,e){return this.currentPath.lineTo(t,e),this}quadraticCurveTo(t,e,i,s){return this.currentPath.quadraticCurveTo(t,e,i,s),this}bezierCurveTo(t,e,i,s,r,n){return this.currentPath.bezierCurveTo(t,e,i,s,r,n),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t){function e(t,e){const i=e.length;let s=!1;for(let r=i-1,n=0;nNumber.EPSILON){if(h<0&&(i=e[n],o=-o,a=e[r],h=-h),t.ya.y)continue;if(t.y===i.y){if(t.x===i.x)return!0}else{const e=h*(t.x-i.x)-o*(t.y-i.y);if(0===e)return!0;if(e<0)continue;s=!s}}else{if(t.y!==i.y)continue;if(a.x<=t.x&&t.x<=i.x||i.x<=t.x&&t.x<=a.x)return!0}}return s}const i=Al.isClockWise,s=this.subPaths;if(0===s.length)return[];let r,n,a;const o=[];if(1===s.length)return n=s[0],a=new $h,a.curves=n.curves,o.push(a),o;let h=!i(s[0].getPoints());h=t?!h:h;const l=[],c=[];let u,d,p=[],m=0;c[m]=void 0,p[m]=[];for(let e=0,a=s.length;e1){let t=!1,i=0;for(let t=0,e=c.length;t0&&!1===t&&(p=l)}for(let t=0,e=c.length;te?(t.repeat.x=1,t.repeat.y=i/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2):(t.repeat.x=e/i,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0),t}(t,e)}static cover(t,e){return function(t,e){const i=t.image&&t.image.width?t.image.width/t.image.height:1;return i>e?(t.repeat.x=e/i,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0):(t.repeat.x=1,t.repeat.y=i/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2),t}(t,e)}static fill(t){return function(t){return t.repeat.x=1,t.repeat.y=1,t.offset.x=0,t.offset.y=0,t}(t)}static getByteLength(t,e,i,s){return cp(t,e,i,s)}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:t}})),"undefined"!=typeof window&&(window.__THREE__?as("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=t);export{it as ACESFilmicToneMapping,w as AddEquation,$ as AddOperation,qe as AdditiveAnimationBlendMode,g as AdditiveBlending,rt as AgXToneMapping,jt as AlphaFormat,ki as AlwaysCompare,U as AlwaysDepth,Si as AlwaysStencilFunc,lu as AmbientLight,rd as AnimationAction,Ac as AnimationClip,Nc as AnimationLoader,ad as AnimationMixer,sd as AnimationObjectGroup,uc as AnimationUtils,Bh as ArcCurve,Pu as ArrayCamera,ap as ArrowHelper,at as AttachedBindMode,Uu as Audio,Hu as AudioAnalyser,Au as AudioContext,Du as AudioListener,Tu as AudioLoader,op as AxesHelper,d as BackSide,He as BasicDepthPacking,o as BasicShadowMap,Vo as BatchedMesh,gc as BezierInterpolant,Xa as Bone,xc as BooleanKeyframeTrack,Md as Box2,Qr as Box3,ep as Box3Helper,gh as BoxGeometry,tp as BoxHelper,Mn as BufferAttribute,Wn as BufferGeometry,gu as BufferGeometryLoader,Ct as ByteType,zc as Cache,$c as Camera,$d as CameraHelper,uh as CanvasTexture,fh as CapsuleGeometry,Eh as CatmullRomCurve3,et as CineonToneMapping,xh as CircleGeometry,yt as ClampToEdgeWrapping,fd as Clock,Pr as Color,bc as ColorKeyframeTrack,Rs as ColorManagement,Hi as Compatibility,hh as CompressedArrayTexture,lh as CompressedCubeTexture,oh as CompressedTexture,Vc as CompressedTextureLoader,vh as ConeGeometry,F as ConstantAlphaFactor,E as ConstantColorFactor,lp as Controls,Ou as CubeCamera,mh as CubeDepthTexture,lt as CubeReflectionMapping,ct as CubeRefractionMapping,ch as CubeTexture,Fc as CubeTextureLoader,pt as CubeUVReflectionMapping,Dh as CubicBezierCurve,Uh as CubicBezierCurve3,pc as CubicInterpolant,r as CullFaceBack,n as CullFaceFront,a as CullFaceFrontBack,s as CullFaceNone,Ch as Curve,Zh as CurvePath,b as CustomBlending,st as CustomToneMapping,bh as CylinderGeometry,bd as Cylindrical,Gs as Data3DTexture,Hs as DataArrayTexture,Ya as DataTexture,jc as DataTextureLoader,xn as DataUtils,di as DecrementStencilOp,mi as DecrementWrapStencilOp,Bc as DefaultLoadingManager,Wt as DepthFormat,qt as DepthStencilFormat,ph as DepthTexture,ot as DetachedBindMode,hu as DirectionalLight,Hd as DirectionalLightHelper,yc as DiscreteInterpolant,Mh as DodecahedronGeometry,p as DoubleSide,O as DstAlphaFactor,R as DstColorFactor,Fi as DynamicCopyUsage,Pi as DynamicDrawUsage,Vi as DynamicReadUsage,zh as EdgesGeometry,Ih as EllipseCurve,Ti as EqualCompare,J as EqualDepth,xi as EqualStencilFunc,ut as EquirectangularReflectionMapping,dt as EquirectangularRefractionMapping,hr as Euler,ds as EventDispatcher,yh as ExternalTexture,Cl as ExtrudeGeometry,Rc as FileLoader,Bn as Float16BufferAttribute,kn as Float32BufferAttribute,Pt as FloatType,Vr as Fog,Nr as FogExp2,ah as FramebufferTexture,u as FrontSide,mo as Frustum,fo as FrustumArray,dd as GLBufferAttribute,Di as GLSL1,Ui as GLSL3,Ci as GreaterCompare,Y as GreaterDepth,Bi as GreaterEqualCompare,X as GreaterEqualDepth,Mi as GreaterEqualStencilFunc,vi as GreaterStencilFunc,Wd as GridHelper,Tr as Group,dh as HTMLTexture,Rt as HalfFloatType,Wc as HemisphereLight,Ud as HemisphereLightHelper,Bl as IcosahedronGeometry,Su as ImageBitmapLoader,Lc as ImageLoader,Ls as ImageUtils,ui as IncrementStencilOp,pi as IncrementWrapStencilOp,$a as InstancedBufferAttribute,yu as InstancedBufferGeometry,ud as InstancedInterleavedBuffer,no as InstancedMesh,Tn as Int16BufferAttribute,Cn as Int32BufferAttribute,Sn as Int8BufferAttribute,kt as IntType,qn as InterleavedBuffer,Xn as InterleavedBufferAttribute,dc as Interpolant,Fe as InterpolateBezier,Ve as InterpolateDiscrete,Ee as InterpolateLinear,Le as InterpolateSmooth,Yi as InterpolationSamplingMode,Xi as InterpolationSamplingType,yi as InvertStencilOp,li as KeepStencilOp,fc as KeyframeTrack,pa as LOD,kl as LatheGeometry,lr as Layers,Ai as LessCompare,W as LessDepth,zi as LessEqualCompare,q as LessEqualDepth,bi as LessEqualStencilFunc,fi as LessStencilFunc,Uc as Light,du as LightProbe,Jo as Line,Bd as Line3,Eo as LineBasicMaterial,Wh as LineCurve,qh as LineCurve3,ac as LineDashedMaterial,Go as LineLoop,Zo as LineSegments,Mt as LinearFilter,mc as LinearInterpolant,Tt as LinearMipMapLinearFilter,_t as LinearMipMapNearestFilter,At as LinearMipmapLinearFilter,St as LinearMipmapNearestFilter,ii as LinearSRGBColorSpace,K as LinearToneMapping,si as LinearTransfer,kc as Loader,mu as LoaderUtils,Ic as LoadingManager,Pe as LoopOnce,Ne as LoopPingPong,Re as LoopRepeat,e as MOUSE,Zn as Material,v as MaterialBlending,pu as MaterialLoader,Ss as MathUtils,vd as Matrix2,Is as Matrix3,Qs as Matrix4,A as MaxEquation,Ra as Mesh,Ma as MeshBasicMaterial,sc as MeshDepthMaterial,rc as MeshDistanceMaterial,ic as MeshLambertMaterial,nc as MeshMatcapMaterial,ec as MeshNormalMaterial,Kl as MeshPhongMaterial,Ql as MeshPhysicalMaterial,$l as MeshStandardMaterial,tc as MeshToonMaterial,_ as MinEquation,gt as MirroredRepeatWrapping,G as MixOperation,x as MultiplyBlending,Z as MultiplyOperation,ft as NearestFilter,wt as NearestMipMapLinearFilter,bt as NearestMipMapNearestFilter,vt as NearestMipmapLinearFilter,xt as NearestMipmapNearestFilter,nt as NeutralToneMapping,_i as NeverCompare,D as NeverDepth,gi as NeverStencilFunc,m as NoBlending,ti as NoColorSpace,ni as NoNormalPacking,Q as NoToneMapping,We as NormalAnimationBlendMode,y as NormalBlending,oi as NormalGAPacking,ai as NormalRGPacking,Ii as NotEqualCompare,H as NotEqualDepth,wi as NotEqualStencilFunc,vc as NumberKeyframeTrack,Ar as Object3D,xu as ObjectLoader,Ke as ObjectSpaceNormalMap,Ol as OctahedronGeometry,z as OneFactor,j as OneMinusConstantAlphaFactor,L as OneMinusConstantColorFactor,P as OneMinusDstAlphaFactor,N as OneMinusDstColorFactor,k as OneMinusSrcAlphaFactor,I as OneMinusSrcColorFactor,au as OrthographicCamera,h as PCFShadowMap,l as PCFSoftShadowMap,Gh as Path,eu as PerspectiveCamera,lo as Plane,Pl as PlaneGeometry,ip as PlaneHelper,nu as PointLight,Ld as PointLightHelper,ih as Points,$o as PointsMaterial,qd as PolarGridHelper,wh as PolyhedronGeometry,Yu as PositionalAudio,id as PropertyBinding,Zu as PropertyMixer,Jh as QuadraticBezierCurve,Xh as QuadraticBezierCurve3,As as Quaternion,Mc as QuaternionKeyframeTrack,wc as QuaternionLinearInterpolant,he as R11_EAC_Format,gs as RAD2DEG,ke as RED_GREEN_RGTC2_Format,Ie as RED_RGTC1_Format,t as REVISION,ce as RG11_EAC_Format,Ze as RGBADepthPacking,Ut as RGBAFormat,Gt as RGBAIntegerFormat,Se as RGBA_ASTC_10x10_Format,ve as RGBA_ASTC_10x5_Format,we as RGBA_ASTC_10x6_Format,Me as RGBA_ASTC_10x8_Format,_e as RGBA_ASTC_12x10_Format,Ae as RGBA_ASTC_12x12_Format,de as RGBA_ASTC_4x4_Format,pe as RGBA_ASTC_5x4_Format,me as RGBA_ASTC_5x5_Format,ye as RGBA_ASTC_6x5_Format,ge as RGBA_ASTC_6x6_Format,fe as RGBA_ASTC_8x5_Format,xe as RGBA_ASTC_8x6_Format,be as RGBA_ASTC_8x8_Format,Te as RGBA_BPTC_Format,oe as RGBA_ETC2_EAC_Format,re as RGBA_PVRTC_2BPPV1_Format,se as RGBA_PVRTC_4BPPV1_Format,Qt as RGBA_S3TC_DXT1_Format,Kt as RGBA_S3TC_DXT3_Format,te as RGBA_S3TC_DXT5_Format,Ge as RGBDepthPacking,Dt as RGBFormat,Zt as RGBIntegerFormat,ze as RGB_BPTC_SIGNED_Format,Ce as RGB_BPTC_UNSIGNED_Format,ne as RGB_ETC1_Format,ae as RGB_ETC2_Format,ie as RGB_PVRTC_2BPPV1_Format,ee as RGB_PVRTC_4BPPV1_Format,$t as RGB_S3TC_DXT1_Format,$e as RGDepthPacking,Yt as RGFormat,Ht as RGIntegerFormat,Gl as RawShaderMaterial,wa as Ray,md as Raycaster,cu as RectAreaLight,Jt as RedFormat,Xt as RedIntegerFormat,tt as ReinhardToneMapping,Xs as RenderTarget,od as RenderTarget3D,mt as RepeatWrapping,ci as ReplaceStencilOp,S as ReverseSubtractEquation,us as ReversedDepthFuncs,Rl as RingGeometry,le as SIGNED_R11_EAC_Format,Oe as SIGNED_RED_GREEN_RGTC2_Format,Be as SIGNED_RED_RGTC1_Format,ue as SIGNED_RG11_EAC_Format,ei as SRGBColorSpace,ri as SRGBTransfer,Er as Scene,Zl as ShaderMaterial,ql as ShadowMaterial,$h as Shape,Nl as ShapeGeometry,hp as ShapePath,Al as ShapeUtils,It as ShortType,Ga as Skeleton,Vd as SkeletonHelper,Ja as SkinnedMesh,js as Source,Nn as Sphere,Vl as SphereGeometry,xd as Spherical,uu as SphericalHarmonics3,Yh as SplineCurve,su as SpotLight,Od as SpotLightHelper,la as Sprite,Gn as SpriteMaterial,B as SrcAlphaFactor,V as SrcAlphaSaturateFactor,C as SrcColorFactor,Li as StaticCopyUsage,Oi as StaticDrawUsage,Ni as StaticReadUsage,Bu as StereoCamera,ji as StreamCopyUsage,Ri as StreamDrawUsage,Ei as StreamReadUsage,Sc as StringKeyframeTrack,M as SubtractEquation,f as SubtractiveBlending,i as TOUCH,Qe as TangentSpaceNormalMap,El as TetrahedronGeometry,qs as Texture,Dc as TextureLoader,up as TextureUtils,Ru as Timer,Ji as TimestampQuery,Ll as TorusGeometry,Fl as TorusKnotGeometry,$r as Triangle,Ye as TriangleFanDrawMode,Xe as TriangleStripDrawMode,Je as TrianglesDrawMode,jl as TubeGeometry,ht as UVMapping,zn as Uint16BufferAttribute,In as Uint32BufferAttribute,_n as Uint8BufferAttribute,An as Uint8ClampedBufferAttribute,hd as Uniform,cd as UniformsGroup,Hl as UniformsUtils,zt as UnsignedByteType,Ft as UnsignedInt101111Type,Et as UnsignedInt248Type,Lt as UnsignedInt5999Type,Ot as UnsignedIntType,Nt as UnsignedShort4444Type,Vt as UnsignedShort5551Type,Bt as UnsignedShortType,c as VSMShadowMap,_s as Vector2,Ts as Vector3,Js as Vector4,_c as VectorKeyframeTrack,nh as VideoFrameTexture,rh as VideoTexture,$s as WebGL3DRenderTarget,Zs as WebGLArrayRenderTarget,Wi as WebGLCoordinateSystem,Ys as WebGLRenderTarget,qi as WebGPUCoordinateSystem,Cr as WebXRController,Dl as WireframeGeometry,Ue as WrapAroundEnding,je as ZeroCurvatureEnding,T as ZeroFactor,De as ZeroSlopeEnding,hi as ZeroStencilOp,Jl as cloneUniforms,Ki as createCanvasElement,Qi as createElementNS,os as error,cp as getByteLength,ss as getConsoleFunction,Yl as getUnlitUniformColorSpace,$i as isTypedArray,rs as log,Xl as mergeUniforms,cs as probeAsync,is as setConsoleFunction,as as warn,hs as warnOnce,ls as yieldToMain}; +const t="184dev",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},i={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},s=0,r=1,n=2,a=3,o=0,h=1,l=2,c=3,u=0,d=1,p=2,m=0,y=1,g=2,f=3,x=4,b=5,v=6,w=100,M=101,S=102,_=103,A=104,T=200,z=201,C=202,I=203,B=204,k=205,O=206,P=207,R=208,N=209,V=210,E=211,L=212,F=213,j=214,D=0,U=1,W=2,q=3,J=4,X=5,Y=6,H=7,Z=0,G=1,$=2,Q=0,K=1,tt=2,et=3,it=4,st=5,rt=6,nt=7,at="attached",ot="detached",ht=300,lt=301,ct=302,ut=303,dt=304,pt=306,mt=1e3,yt=1001,gt=1002,ft=1003,xt=1004,bt=1004,vt=1005,wt=1005,Mt=1006,St=1007,_t=1007,At=1008,Tt=1008,zt=1009,Ct=1010,It=1011,Bt=1012,kt=1013,Ot=1014,Pt=1015,Rt=1016,Nt=1017,Vt=1018,Et=1020,Lt=35902,Ft=35899,jt=1021,Dt=1022,Ut=1023,Wt=1026,qt=1027,Jt=1028,Xt=1029,Yt=1030,Ht=1031,Zt=1032,Gt=1033,$t=33776,Qt=33777,Kt=33778,te=33779,ee=35840,ie=35841,se=35842,re=35843,ne=36196,ae=37492,oe=37496,he=37488,le=37489,ce=37490,ue=37491,de=37808,pe=37809,me=37810,ye=37811,ge=37812,fe=37813,xe=37814,be=37815,ve=37816,we=37817,Me=37818,Se=37819,_e=37820,Ae=37821,Te=36492,ze=36494,Ce=36495,Ie=36283,Be=36284,ke=36285,Oe=36286,Pe=2200,Re=2201,Ne=2202,Ve=2300,Ee=2301,Le=2302,Fe=2303,je=2400,De=2401,Ue=2402,We=2500,qe=2501,Je=0,Xe=1,Ye=2,He=3200,Ze=3201,Ge=3202,$e=3203,Qe=0,Ke=1,ti="",ei="srgb",ii="srgb-linear",si="linear",ri="srgb",ni="",ai="rg",oi="ga",hi=0,li=7680,ci=7681,ui=7682,di=7683,pi=34055,mi=34056,yi=5386,gi=512,fi=513,xi=514,bi=515,vi=516,wi=517,Mi=518,Si=519,_i=512,Ai=513,Ti=514,zi=515,Ci=516,Ii=517,Bi=518,ki=519,Oi=35044,Pi=35048,Ri=35040,Ni=35045,Vi=35049,Ei=35041,Li=35046,Fi=35050,ji=35042,Di="100",Ui="300 es",Wi=2e3,qi=2001,Ji={COMPUTE:"compute",RENDER:"render"},Xi={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Yi={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"},Hi={TEXTURE_COMPARE:"depthTextureCompare"};const Zi={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Gi(t,e){return new Zi[t](e)}function $i(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Qi(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Ki(){const t=Qi("canvas");return t.style.display="block",t}const ts={};let es=null;function is(t){es=t}function ss(){return es}function rs(...t){const e="THREE."+t.shift();es?es("log",e,...t):console.log(e,...t)}function ns(t){const e=t[0];if("string"==typeof e&&e.startsWith("TSL:")){const e=t[1];e&&e.isStackTrace?t[0]+=" "+e.getLocation():t[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return t}function as(...t){const e="THREE."+(t=ns(t)).shift();if(es)es("warn",e,...t);else{const i=t[0];i&&i.isStackTrace?console.warn(i.getError(e)):console.warn(e,...t)}}function os(...t){const e="THREE."+(t=ns(t)).shift();if(es)es("error",e,...t);else{const i=t[0];i&&i.isStackTrace?console.error(i.getError(e)):console.error(e,...t)}}function hs(...t){const e=t.join(" ");e in ts||(ts[e]=!0,as(...t))}function ls(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(t=>{requestAnimationFrame(t)})}function cs(t,e,i){return new Promise(function(s,r){setTimeout(function n(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:r();break;case t.TIMEOUT_EXPIRED:setTimeout(n,i);break;default:s()}},i)})}const us={[D]:1,[W]:6,[J]:7,[q]:5,[U]:0,[Y]:2,[H]:4,[X]:3};class ds{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return void 0!==i&&(void 0!==i[t]&&-1!==i[t].indexOf(e))}removeEventListener(t,e){const i=this._listeners;if(void 0===i)return;const s=i[t];if(void 0!==s){const t=s.indexOf(e);-1!==t&&s.splice(t,1)}}dispatchEvent(t){const e=this._listeners;if(void 0===e)return;const i=e[t.type];if(void 0!==i){t.target=this;const e=i.slice(0);for(let i=0,s=e.length;i>8&255]+ps[t>>16&255]+ps[t>>24&255]+"-"+ps[255&e]+ps[e>>8&255]+"-"+ps[e>>16&15|64]+ps[e>>24&255]+"-"+ps[63&i|128]+ps[i>>8&255]+"-"+ps[i>>16&255]+ps[i>>24&255]+ps[255&s]+ps[s>>8&255]+ps[s>>16&255]+ps[s>>24&255]).toLowerCase()}function xs(t,e,i){return Math.max(e,Math.min(i,t))}function bs(t,e){return(t%e+e)%e}function vs(t,e,i){return(1-i)*t+i*e}function ws(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Ms(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Ss={DEG2RAD:ys,RAD2DEG:gs,generateUUID:fs,clamp:xs,euclideanModulo:bs,mapLinear:function(t,e,i,s,r){return s+(t-e)*(r-s)/(i-e)},inverseLerp:function(t,e,i){return t!==e?(i-t)/(e-t):0},lerp:vs,damp:function(t,e,i,s){return vs(t,e,1-Math.exp(-i*s))},pingpong:function(t,e=1){return e-Math.abs(bs(t,2*e)-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(ms=t);let e=ms+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*ys},radToDeg:function(t){return t*gs},isPowerOfTwo:function(t){return!(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,i,s,r){const n=Math.cos,a=Math.sin,o=n(i/2),h=a(i/2),l=n((e+s)/2),c=a((e+s)/2),u=n((e-s)/2),d=a((e-s)/2),p=n((s-e)/2),m=a((s-e)/2);switch(r){case"XYX":t.set(o*c,h*u,h*d,o*l);break;case"YZY":t.set(h*d,o*c,h*u,o*l);break;case"ZXZ":t.set(h*u,h*d,o*c,o*l);break;case"XZX":t.set(o*c,h*m,h*p,o*l);break;case"YXY":t.set(h*p,o*c,h*m,o*l);break;case"ZYZ":t.set(h*m,h*p,o*c,o*l);break;default:as("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Ms,denormalize:ws};class _s{static{_s.prototype.isVector2=!0}constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=xs(this.x,t.x,e.x),this.y=xs(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=xs(this.x,t,e),this.y=xs(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(xs(i,t,e))}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(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.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(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(xs(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),r=this.x-t.x,n=this.y-t.y;return this.x=r*i-n*s+t.x,this.y=r*s+n*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class As{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,r,n,a){let o=i[s+0],h=i[s+1],l=i[s+2],c=i[s+3],u=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(c!==m||o!==u||h!==d||l!==p){let t=o*u+h*d+l*p+c*m;t<0&&(u=-u,d=-d,p=-p,m=-m,t=-t);let e=1-a;if(t<.9995){const i=Math.acos(t),s=Math.sin(i);e=Math.sin(e*i)/s,o=o*e+u*(a=Math.sin(a*i)/s),h=h*e+d*a,l=l*e+p*a,c=c*e+m*a}else{o=o*e+u*a,h=h*e+d*a,l=l*e+p*a,c=c*e+m*a;const t=1/Math.sqrt(o*o+h*h+l*l+c*c);o*=t,h*=t,l*=t,c*=t}}t[e]=o,t[e+1]=h,t[e+2]=l,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,r,n){const a=i[s],o=i[s+1],h=i[s+2],l=i[s+3],c=r[n],u=r[n+1],d=r[n+2],p=r[n+3];return t[e]=a*p+l*c+o*d-h*u,t[e+1]=o*p+l*u+h*c-a*d,t[e+2]=h*p+l*d+a*u-o*c,t[e+3]=l*p-a*c-o*u-h*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,r=t._z,n=t._order,a=Math.cos,o=Math.sin,h=a(i/2),l=a(s/2),c=a(r/2),u=o(i/2),d=o(s/2),p=o(r/2);switch(n){case"XYZ":this._x=u*l*c+h*d*p,this._y=h*d*c-u*l*p,this._z=h*l*p+u*d*c,this._w=h*l*c-u*d*p;break;case"YXZ":this._x=u*l*c+h*d*p,this._y=h*d*c-u*l*p,this._z=h*l*p-u*d*c,this._w=h*l*c+u*d*p;break;case"ZXY":this._x=u*l*c-h*d*p,this._y=h*d*c+u*l*p,this._z=h*l*p+u*d*c,this._w=h*l*c-u*d*p;break;case"ZYX":this._x=u*l*c-h*d*p,this._y=h*d*c+u*l*p,this._z=h*l*p-u*d*c,this._w=h*l*c+u*d*p;break;case"YZX":this._x=u*l*c+h*d*p,this._y=h*d*c+u*l*p,this._z=h*l*p-u*d*c,this._w=h*l*c-u*d*p;break;case"XZY":this._x=u*l*c-h*d*p,this._y=h*d*c-u*l*p,this._z=h*l*p+u*d*c,this._w=h*l*c+u*d*p;break;default:as("Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],r=e[8],n=e[1],a=e[5],o=e[9],h=e[2],l=e[6],c=e[10],u=i+a+c;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(l-o)*t,this._y=(r-h)*t,this._z=(n-s)*t}else if(i>a&&i>c){const t=2*Math.sqrt(1+i-a-c);this._w=(l-o)/t,this._x=.25*t,this._y=(s+n)/t,this._z=(r+h)/t}else if(a>c){const t=2*Math.sqrt(1+a-i-c);this._w=(r-h)/t,this._x=(s+n)/t,this._y=.25*t,this._z=(o+l)/t}else{const t=2*Math.sqrt(1+c-i-a);this._w=(n-s)/t,this._x=(r+h)/t,this._y=(o+l)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(xs(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._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 t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,r=t._z,n=t._w,a=e._x,o=e._y,h=e._z,l=e._w;return this._x=i*l+n*a+s*h-r*o,this._y=s*l+n*o+r*a-i*h,this._z=r*l+n*h+i*o-s*a,this._w=n*l-i*a-s*o-r*h,this._onChangeCallback(),this}slerp(t,e){let i=t._x,s=t._y,r=t._z,n=t._w,a=this.dot(t);a<0&&(i=-i,s=-s,r=-r,n=-n,a=-a);let o=1-e;if(a<.9995){const t=Math.acos(a),h=Math.sin(t);o=Math.sin(o*t)/h,e=Math.sin(e*t)/h,this._x=this._x*o+i*e,this._y=this._y*o+s*e,this._z=this._z*o+r*e,this._w=this._w*o+n*e,this._onChangeCallback()}else this._x=this._x*o+i*e,this._y=this._y*o+s*e,this._z=this._z*o+r*e,this._w=this._w*o+n*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ts{static{Ts.prototype.isVector3=!0}constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Cs.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Cs.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*s,this.y=r[1]*e+r[4]*i+r[7]*s,this.z=r[2]*e+r[5]*i+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=t.elements,n=1/(r[3]*e+r[7]*i+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*s+r[12])*n,this.y=(r[1]*e+r[5]*i+r[9]*s+r[13])*n,this.z=(r[2]*e+r[6]*i+r[10]*s+r[14])*n,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,r=t.x,n=t.y,a=t.z,o=t.w,h=2*(n*s-a*i),l=2*(a*e-r*s),c=2*(r*i-n*e);return this.x=e+o*h+n*c-a*l,this.y=i+o*l+a*h-r*c,this.z=s+o*c+r*l-n*h,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s,this.y=r[1]*e+r[5]*i+r[9]*s,this.z=r[2]*e+r[6]*i+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=xs(this.x,t.x,e.x),this.y=xs(this.y,t.y,e.y),this.z=xs(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=xs(this.x,t,e),this.y=xs(this.y,t,e),this.z=xs(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(xs(i,t,e))}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(t){return this.x*t.x+this.y*t.y+this.z*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,r=t.z,n=e.x,a=e.y,o=e.z;return this.x=s*o-r*a,this.y=r*n-i*o,this.z=i*a-s*n,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return zs.copy(this).projectOnVector(t),this.sub(zs)}reflect(t){return this.sub(zs.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(xs(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const zs=new Ts,Cs=new As;class Is{static{Is.prototype.isMatrix3=!0}constructor(t,e,i,s,r,n,a,o,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,r,n,a,o,h)}set(t,e,i,s,r,n,a,o,h){const l=this.elements;return l[0]=t,l[1]=s,l[2]=a,l[3]=e,l[4]=r,l[5]=o,l[6]=i,l[7]=n,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,r=this.elements,n=i[0],a=i[3],o=i[6],h=i[1],l=i[4],c=i[7],u=i[2],d=i[5],p=i[8],m=s[0],y=s[3],g=s[6],f=s[1],x=s[4],b=s[7],v=s[2],w=s[5],M=s[8];return r[0]=n*m+a*f+o*v,r[3]=n*y+a*x+o*w,r[6]=n*g+a*b+o*M,r[1]=h*m+l*f+c*v,r[4]=h*y+l*x+c*w,r[7]=h*g+l*b+c*M,r[2]=u*m+d*f+p*v,r[5]=u*y+d*x+p*w,r[8]=u*g+d*b+p*M,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],o=t[6],h=t[7],l=t[8];return e*n*l-e*a*h-i*r*l+i*a*o+s*r*h-s*n*o}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],o=t[6],h=t[7],l=t[8],c=l*n-a*h,u=a*o-l*r,d=h*r-n*o,p=e*c+i*u+s*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=c*m,t[1]=(s*h-l*i)*m,t[2]=(a*i-s*n)*m,t[3]=u*m,t[4]=(l*e-s*o)*m,t[5]=(s*r-a*e)*m,t[6]=d*m,t[7]=(i*o-h*e)*m,t[8]=(n*e-i*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,r,n,a){const o=Math.cos(r),h=Math.sin(r);return this.set(i*o,i*h,-i*(o*n+h*a)+n+t,-s*h,s*o,-s*(-h*n+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(Bs.makeScale(t,e)),this}rotate(t){return this.premultiply(Bs.makeRotation(-t)),this}translate(t,e){return this.premultiply(Bs.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const Bs=new Is,ks=(new Is).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Os=(new Is).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ps(){const t={enabled:!0,workingColorSpace:ii,spaces:{},convert:function(t,e,i){return!1!==this.enabled&&e!==i&&e&&i?(this.spaces[e].transfer===ri&&(t.r=Ns(t.r),t.g=Ns(t.g),t.b=Ns(t.b)),this.spaces[e].primaries!==this.spaces[i].primaries&&(t.applyMatrix3(this.spaces[e].toXYZ),t.applyMatrix3(this.spaces[i].fromXYZ)),this.spaces[i].transfer===ri&&(t.r=Vs(t.r),t.g=Vs(t.g),t.b=Vs(t.b)),t):t},workingToColorSpace:function(t,e){return this.convert(t,this.workingColorSpace,e)},colorSpaceToWorking:function(t,e){return this.convert(t,e,this.workingColorSpace)},getPrimaries:function(t){return this.spaces[t].primaries},getTransfer:function(t){return""===t?si:this.spaces[t].transfer},getToneMappingMode:function(t){return this.spaces[t].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(t,e=this.workingColorSpace){return t.fromArray(this.spaces[e].luminanceCoefficients)},define:function(t){Object.assign(this.spaces,t)},_getMatrix:function(t,e,i){return t.copy(this.spaces[e].toXYZ).multiply(this.spaces[i].fromXYZ)},_getDrawingBufferColorSpace:function(t){return this.spaces[t].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(t=this.workingColorSpace){return this.spaces[t].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(e,i){return hs("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(e,i)},toWorkingColorSpace:function(e,i){return hs("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(e,i)}},e=[.64,.33,.3,.6,.15,.06],i=[.2126,.7152,.0722],s=[.3127,.329];return t.define({[ii]:{primaries:e,whitePoint:s,transfer:si,toXYZ:ks,fromXYZ:Os,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:ei},outputColorSpaceConfig:{drawingBufferColorSpace:ei}},[ei]:{primaries:e,whitePoint:s,transfer:ri,toXYZ:ks,fromXYZ:Os,luminanceCoefficients:i,outputColorSpaceConfig:{drawingBufferColorSpace:ei}}}),t}const Rs=Ps();function Ns(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function Vs(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let Es;class Ls{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{void 0===Es&&(Es=Qi("canvas")),Es.width=t.width,Es.height=t.height;const e=Es.getContext("2d");t instanceof ImageData?e.putImageData(t,0,0):e.drawImage(t,0,0,t.width,t.height),i=Es}return i.toDataURL(e)}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=Qi("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height),r=s.data;for(let t=0;t1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Ws).x}get height(){return this.source.getSize(Ws).y}get depth(){return this.source.getSize(Ws).z}get image(){return this.source.data}set image(t){this.source.data=t}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(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(void 0===i){as(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const s=this[e];void 0!==s?s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[e]=i:as(`Texture.setValues(): property '${e}' does not exist.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).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&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==ht)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case mt:t.x=t.x-Math.floor(t.x);break;case yt:t.x=t.x<0?0:1;break;case gt:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case mt:t.y=t.y-Math.floor(t.y);break;case yt:t.y=t.y<0?0:1;break;case gt:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}qs.DEFAULT_IMAGE=null,qs.DEFAULT_MAPPING=ht,qs.DEFAULT_ANISOTROPY=1;class Js{static{Js.prototype.isVector4=!0}constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=this.w,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s+n[12]*r,this.y=n[1]*e+n[5]*i+n[9]*s+n[13]*r,this.z=n[2]*e+n[6]*i+n[10]*s+n[14]*r,this.w=n[3]*e+n[7]*i+n[11]*s+n[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,r;const n=.01,a=.1,o=t.elements,h=o[0],l=o[4],c=o[8],u=o[1],d=o[5],p=o[9],m=o[2],y=o[6],g=o[10];if(Math.abs(l-u)o&&t>f?tf?o1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return(new this.constructor).copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,i=t.textures.length;e>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),null!==this.pivot&&(s.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(s.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(s.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(s.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox?t.boundingBox.toJSON():void 0,boundingSphere:t.boundingSphere?t.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(t=>({...t})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),null!==this._colorsTexture&&(s.colorsTexture=this._colorsTexture.toJSON(t)),null!==this.boundingSphere&&(s.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(s.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const i=e.shapes;if(Array.isArray(i))for(let e=0,s=i.length;e0){s.children=[];for(let e=0;e0){s.animations=[];for(let e=0;e0&&(i.geometries=e),s.length>0&&(i.materials=s),r.length>0&&(i.textures=r),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),h.length>0&&(i.skeletons=h),l.length>0&&(i.animations=l),c.length>0&&(i.nodes=c)}return i.object=s,i;function n(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=null!==t.pivot?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;eo+l?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!h.inputState.pinching&&a<=o-l&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,i),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:t,target:this})));null!==a&&(s=e.getPose(t.targetRaySpace,i),null===s&&null!==r&&(s=r),null!==s&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(zr)))}return null!==a&&(a.visible=null!==s),null!==o&&(o.visible=null!==r),null!==h&&(h.visible=null!==n),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const i=new Tr;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}const Ir={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},Br={h:0,s:0,l:0},kr={h:0,s:0,l:0};function Or(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}class Pr{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(void 0===e&&void 0===i){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=ei){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,Rs.colorSpaceToWorking(this,e),this}setRGB(t,e,i,s=Rs.workingColorSpace){return this.r=t,this.g=e,this.b=i,Rs.colorSpaceToWorking(this,s),this}setHSL(t,e,i,s=Rs.workingColorSpace){if(t=bs(t,1),e=xs(e,0,1),i=xs(i,0,1),0===e)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,r=2*i-s;this.r=Or(r,s,t+1/3),this.g=Or(r,s,t),this.b=Or(r,s,t-1/3)}return Rs.colorSpaceToWorking(this,s),this}setStyle(t,e=ei){function i(e){void 0!==e&&parseFloat(e)<1&&as("Color: Alpha component of "+t+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let r;const n=s[1],a=s[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(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,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(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,e);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 i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:as("Color: Unknown color model "+t)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){const i=s[1],r=i.length;if(3===r)return this.setRGB(parseInt(i.charAt(0),16)/15,parseInt(i.charAt(1),16)/15,parseInt(i.charAt(2),16)/15,e);if(6===r)return this.setHex(parseInt(i,16),e);as("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=ei){const i=Ir[t.toLowerCase()];return void 0!==i?this.setHex(i,e):as("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Ns(t.r),this.g=Ns(t.g),this.b=Ns(t.b),this}copyLinearToSRGB(t){return this.r=Vs(t.r),this.g=Vs(t.g),this.b=Vs(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=ei){return Rs.workingToColorSpace(Rr.copy(this),t),65536*Math.round(xs(255*Rr.r,0,255))+256*Math.round(xs(255*Rr.g,0,255))+Math.round(xs(255*Rr.b,0,255))}getHexString(t=ei){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Rs.workingColorSpace){Rs.workingToColorSpace(Rr.copy(this),e);const i=Rr.r,s=Rr.g,r=Rr.b,n=Math.max(i,s,r),a=Math.min(i,s,r);let o,h;const l=(a+n)/2;if(a===n)o=0,h=0;else{const t=n-a;switch(h=l<=.5?t/(n+a):t/(2-n-a),n){case i:o=(s-r)/t+(s0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const Lr=new Ts,Fr=new Ts,jr=new Ts,Dr=new Ts,Ur=new Ts,Wr=new Ts,qr=new Ts,Jr=new Ts,Xr=new Ts,Yr=new Ts,Hr=new Js,Zr=new Js,Gr=new Js;class $r{constructor(t=new Ts,e=new Ts,i=new Ts){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,s){s.subVectors(i,e),Lr.subVectors(t,e),s.cross(Lr);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,i,s,r){Lr.subVectors(s,e),Fr.subVectors(i,e),jr.subVectors(t,e);const n=Lr.dot(Lr),a=Lr.dot(Fr),o=Lr.dot(jr),h=Fr.dot(Fr),l=Fr.dot(jr),c=n*h-a*a;if(0===c)return r.set(0,0,0),null;const u=1/c,d=(h*o-a*l)*u,p=(n*l-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,i,s){return null!==this.getBarycoord(t,e,i,s,Dr)&&(Dr.x>=0&&Dr.y>=0&&Dr.x+Dr.y<=1)}static getInterpolation(t,e,i,s,r,n,a,o){return null===this.getBarycoord(t,e,i,s,Dr)?(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,Dr.x),o.addScaledVector(n,Dr.y),o.addScaledVector(a,Dr.z),o)}static getInterpolatedAttribute(t,e,i,s,r,n){return Hr.setScalar(0),Zr.setScalar(0),Gr.setScalar(0),Hr.fromBufferAttribute(t,e),Zr.fromBufferAttribute(t,i),Gr.fromBufferAttribute(t,s),n.setScalar(0),n.addScaledVector(Hr,r.x),n.addScaledVector(Zr,r.y),n.addScaledVector(Gr,r.z),n}static isFrontFacing(t,e,i,s){return Lr.subVectors(i,e),Fr.subVectors(t,e),Lr.cross(Fr).dot(s)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,s){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,i,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,s),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Lr.subVectors(this.c,this.b),Fr.subVectors(this.a,this.b),.5*Lr.cross(Fr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return $r.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return $r.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,s,r){return $r.getInterpolation(t,this.a,this.b,this.c,e,i,s,r)}containsPoint(t){return $r.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return $r.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,s=this.b,r=this.c;let n,a;Ur.subVectors(s,i),Wr.subVectors(r,i),Jr.subVectors(t,i);const o=Ur.dot(Jr),h=Wr.dot(Jr);if(o<=0&&h<=0)return e.copy(i);Xr.subVectors(t,s);const l=Ur.dot(Xr),c=Wr.dot(Xr);if(l>=0&&c<=l)return e.copy(s);const u=o*c-l*h;if(u<=0&&o>=0&&l<=0)return n=o/(o-l),e.copy(i).addScaledVector(Ur,n);Yr.subVectors(t,r);const d=Ur.dot(Yr),p=Wr.dot(Yr);if(p>=0&&d<=p)return e.copy(r);const m=d*h-o*p;if(m<=0&&h>=0&&p<=0)return a=h/(h-p),e.copy(i).addScaledVector(Wr,a);const y=l*p-d*c;if(y<=0&&c-l>=0&&d-p>=0)return qr.subVectors(r,s),a=(c-l)/(c-l+(d-p)),e.copy(s).addScaledVector(qr,a);const g=1/(y+m+u);return n=m*g,a=u*g,e.copy(i).addScaledVector(Ur,n).addScaledVector(Wr,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class Qr{constructor(t=new Ts(1/0,1/0,1/0),e=new Ts(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,tn),tn.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(ln),cn.subVectors(this.max,ln),sn.subVectors(t.a,ln),rn.subVectors(t.b,ln),nn.subVectors(t.c,ln),an.subVectors(rn,sn),on.subVectors(nn,rn),hn.subVectors(sn,nn);let e=[0,-an.z,an.y,0,-on.z,on.y,0,-hn.z,hn.y,an.z,0,-an.x,on.z,0,-on.x,hn.z,0,-hn.x,-an.y,an.x,0,-on.y,on.x,0,-hn.y,hn.x,0];return!!pn(e,sn,rn,nn,cn)&&(e=[1,0,0,0,1,0,0,0,1],!!pn(e,sn,rn,nn,cn)&&(un.crossVectors(an,on),e=[un.x,un.y,un.z],pn(e,sn,rn,nn,cn)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,tn).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(tn).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Kr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Kr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Kr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Kr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Kr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Kr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Kr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Kr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Kr)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Kr=[new Ts,new Ts,new Ts,new Ts,new Ts,new Ts,new Ts,new Ts],tn=new Ts,en=new Qr,sn=new Ts,rn=new Ts,nn=new Ts,an=new Ts,on=new Ts,hn=new Ts,ln=new Ts,cn=new Ts,un=new Ts,dn=new Ts;function pn(t,e,i,s,r){for(let n=0,a=t.length-3;n<=a;n+=3){dn.fromArray(t,n);const a=r.x*Math.abs(dn.x)+r.y*Math.abs(dn.y)+r.z*Math.abs(dn.z),o=e.dot(dn),h=i.dot(dn),l=s.dot(dn);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const mn=yn();function yn(){const t=new ArrayBuffer(4),e=new Float32Array(t),i=new Uint32Array(t),s=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(s[t]=0,s[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(s[t]=1024>>-e-14,s[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(s[t]=e+15<<10,s[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(s[t]=31744,s[256|t]=64512,r[t]=24,r[256|t]=24):(s[t]=31744,s[256|t]=64512,r[t]=13,r[256|t]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,i=0;for(;!(8388608&e);)e<<=1,i-=8388608;e&=-8388609,i+=947912704,n[t]=e|i}for(let t=1024;t<2048;++t)n[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:i,baseTable:s,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function gn(t){Math.abs(t)>65504&&as("DataUtils.toHalfFloat(): Value out of range."),t=xs(t,-65504,65504),mn.floatView[0]=t;const e=mn.uint32View[0],i=e>>23&511;return mn.baseTable[i]+((8388607&e)>>mn.shiftTable[i])}function fn(t){const e=t>>10;return mn.uint32View[0]=mn.mantissaTable[mn.offsetTable[e]+(1023&t)]+mn.exponentTable[e],mn.floatView[0]}class xn{static toHalfFloat(t){return gn(t)}static fromHalfFloat(t){return fn(t)}}const bn=new Ts,vn=new _s;let wn=0;class Mn extends ds{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:wn++}),this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=Oi,this.updateRanges=[],this.gpuType=Pt,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let s=0,r=this.itemSize;sthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Pn.subVectors(t,this.center);const e=Pn.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(Pn,i/t),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(Rn.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Pn.copy(t.center).add(Rn)),this.expandByPoint(Pn.copy(t.center).sub(Rn))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let Vn=0;const En=new Qs,Ln=new Ar,Fn=new Ts,jn=new Qr,Dn=new Qr,Un=new Ts;class Wn extends ds{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Vn++}),this.uuid=fs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(function(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}(t)?In:zn)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return void 0!==this.attributes[t]}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(void 0!==i){const e=(new Is).getNormalMatrix(t);i.applyNormalMatrix(e),i.needsUpdate=!0}const s=this.attributes.tangent;return void 0!==s&&(s.transformDirection(t),s.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return En.makeRotationFromQuaternion(t),this.applyMatrix4(En),this}rotateX(t){return En.makeRotationX(t),this.applyMatrix4(En),this}rotateY(t){return En.makeRotationY(t),this.applyMatrix4(En),this}rotateZ(t){return En.makeRotationZ(t),this.applyMatrix4(En),this}translate(t,e,i){return En.makeTranslation(t,e,i),this.applyMatrix4(En),this}scale(t,e,i){return En.makeScale(t,e,i),this.applyMatrix4(En),this}lookAt(t){return Ln.lookAt(t),Ln.updateMatrix(),this.applyMatrix4(Ln.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Fn).negate(),this.translate(Fn.x,Fn.y,Fn.z),this}setFromPoints(t){const e=this.getAttribute("position");if(void 0===e){const e=[];for(let i=0,s=t.length;ie.count&&as("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Qr);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return os("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Ts(-1/0,-1/0,-1/0),new Ts(1/0,1/0,1/0));if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,i=e.length;t0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const i in e)void 0!==e[i]&&(t[i]=e[i]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const e in i){const s=i[e];t.data.attributes[e]=s.toJSON(t.data)}const s={};let r=!1;for(const e in this.morphAttributes){const i=this.morphAttributes[e],n=[];for(let e=0,s=i.length;e0&&(s[e]=n,r=!0)}r&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(t.data.groups=JSON.parse(JSON.stringify(n)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere=a.toJSON()),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;null!==i&&this.setIndex(i.clone());const s=t.attributes;for(const t in s){const i=s[t];this.setAttribute(t,i.clone(e))}const r=t.morphAttributes;for(const t in r){const i=[],s=r[t];for(let t=0,r=s.length;t0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const i=t[e];if(void 0===i){as(`Material: parameter '${e}' has value of undefined.`);continue}const s=this[e];void 0!==s?s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[e]=i:as(`Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function s(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),void 0!==this.dispersion&&(i.dispersion=this.dispersion),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(i.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapRotation&&(i.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),null!==this.shadowSide&&(i.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(i.blending=this.blending),0!==this.side&&(i.side=this.side),!0===this.vertexColors&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),!0===this.transparent&&(i.transparent=!0),204!==this.blendSrc&&(i.blendSrc=this.blendSrc),205!==this.blendDst&&(i.blendDst=this.blendDst),100!==this.blendEquation&&(i.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(i.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(i.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(i.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(i.depthFunc=this.depthFunc),!1===this.depthTest&&(i.depthTest=this.depthTest),!1===this.depthWrite&&(i.depthWrite=this.depthWrite),!1===this.colorWrite&&(i.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(i.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(i.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(i.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==li&&(i.stencilFail=this.stencilFail),this.stencilZFail!==li&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==li&&(i.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(i.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(i.rotation=this.rotation),!0===this.polygonOffset&&(i.polygonOffset=!0),0!==this.polygonOffsetFactor&&(i.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(i.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),!0===this.dithering&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),!0===this.alphaHash&&(i.alphaHash=!0),!0===this.alphaToCoverage&&(i.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(i.premultipliedAlpha=!0),!0===this.forceSinglePass&&(i.forceSinglePass=!0),!1===this.allowOverride&&(i.allowOverride=!1),!0===this.wireframe&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(i.flatShading=!0),!1===this.visible&&(i.visible=!1),!1===this.toneMapped&&(i.toneMapped=!1),!1===this.fog&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData),e){const e=s(t.textures),r=s(t.images);e.length>0&&(i.textures=e),r.length>0&&(i.images=r)}return i}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(null!==e){const t=e.length;i=new Array(t);for(let s=0;s!==t;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}}class Gn extends Zn{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Pr(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const $n=new Ts,Qn=new Ts,Kn=new Ts,ta=new _s,ea=new _s,ia=new Qs,sa=new Ts,ra=new Ts,na=new Ts,aa=new _s,oa=new _s,ha=new _s;class la extends Ar{constructor(t=new Gn){if(super(),this.isSprite=!0,this.type="Sprite",void 0===Yn){Yn=new Wn;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),e=new qn(t,5);Yn.setIndex([0,1,2,0,2,3]),Yn.setAttribute("position",new Xn(e,3,0,!1)),Yn.setAttribute("uv",new Xn(e,2,3,!1))}this.geometry=Yn,this.material=t,this.center=new _s(.5,.5),this.count=1}raycast(t,e){null===t.camera&&os('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Qn.setFromMatrixScale(this.matrixWorld),ia.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),Kn.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&Qn.multiplyScalar(-Kn.z);const i=this.material.rotation;let s,r;0!==i&&(r=Math.cos(i),s=Math.sin(i));const n=this.center;ca(sa.set(-.5,-.5,0),Kn,n,Qn,s,r),ca(ra.set(.5,-.5,0),Kn,n,Qn,s,r),ca(na.set(.5,.5,0),Kn,n,Qn,s,r),aa.set(0,0),oa.set(1,0),ha.set(1,1);let a=t.ray.intersectTriangle(sa,ra,na,!1,$n);if(null===a&&(ca(ra.set(-.5,.5,0),Kn,n,Qn,s,r),oa.set(0,1),a=t.ray.intersectTriangle(sa,na,ra,!1,$n),null===a))return;const o=t.ray.origin.distanceTo($n);ot.far||e.push({distance:o,point:$n.clone(),uv:$r.getInterpolation($n,sa,ra,na,aa,oa,ha,new _s),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function ca(t,e,i,s,r,n){ta.subVectors(t,i).addScalar(.5).multiply(s),void 0!==r?(ea.x=n*ta.x-r*ta.y,ea.y=r*ta.x+n*ta.y):ea.copy(ta),t.copy(e),t.x+=ea.x,t.y+=ea.y,t.applyMatrix4(ia)}const ua=new Ts,da=new Ts;class pa extends Ar{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,i=e.length;t0){let i,s;for(i=1,s=e.length;i0){ua.setFromMatrixPosition(this.matrixWorld);const i=t.ray.origin.distanceTo(ua);this.getObjectForDistance(i).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){ua.setFromMatrixPosition(t.matrixWorld),da.setFromMatrixPosition(this.matrixWorld);const i=ua.distanceTo(da)/t.zoom;let s,r;for(e[0].object.visible=!0,s=1,r=e.length;s=t))break;e[s-1].object.visible=!1,e[s].object.visible=!0}for(this._currentLevel=s-1;s0)if(c=n*o-a,u=n*a-o,p=r*l,c>=0)if(u>=-p)if(u<=p){const t=1/l;c*=t,u*=t,d=c*(c+n*u+2*a)+u*(n*c+u+2*o)+h}else u=r,c=Math.max(0,-(n*u+a)),d=-c*c+u*(u+2*o)+h;else u=-r,c=Math.max(0,-(n*u+a)),d=-c*c+u*(u+2*o)+h;else u<=-p?(c=Math.max(0,-(-n*r+a)),u=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+u*(u+2*o)+h):u<=p?(c=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+h):(c=Math.max(0,-(n*r+a)),u=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+u*(u+2*o)+h);else u=n>0?-r:r,c=Math.max(0,-(n*u+a)),d=-c*c+u*(u+2*o)+h;return i&&i.copy(this.origin).addScaledVector(this.direction,c),s&&s.copy(ya).addScaledVector(ga,u),d}intersectSphere(t,e){ma.subVectors(t.center,this.origin);const i=ma.dot(this.direction),s=ma.dot(ma)-i*i,r=t.radius*t.radius;if(s>r)return null;const n=Math.sqrt(r-s),a=i-n,o=i+n;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return!(t.radius<0)&&this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return null===i?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,s,r,n,a,o;const h=1/this.direction.x,l=1/this.direction.y,c=1/this.direction.z,u=this.origin;return h>=0?(i=(t.min.x-u.x)*h,s=(t.max.x-u.x)*h):(i=(t.max.x-u.x)*h,s=(t.min.x-u.x)*h),l>=0?(r=(t.min.y-u.y)*l,n=(t.max.y-u.y)*l):(r=(t.max.y-u.y)*l,n=(t.min.y-u.y)*l),i>n||r>s?null:((r>i||isNaN(i))&&(i=r),(n=0?(a=(t.min.z-u.z)*c,o=(t.max.z-u.z)*c):(a=(t.max.z-u.z)*c,o=(t.min.z-u.z)*c),i>o||a>s?null:((a>i||i!=i)&&(i=a),(o=0?i:s,e)))}intersectsBox(t){return null!==this.intersectBox(t,ma)}intersectTriangle(t,e,i,s,r){xa.subVectors(e,t),ba.subVectors(i,t),va.crossVectors(xa,ba);let n,a=this.direction.dot(va);if(a>0){if(s)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}fa.subVectors(this.origin,t);const o=n*this.direction.dot(ba.crossVectors(fa,ba));if(o<0)return null;const h=n*this.direction.dot(xa.cross(fa));if(h<0)return null;if(o+h>a)return null;const l=-n*fa.dot(va);return l<0?null:this.at(l/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class Ma extends Zn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Pr(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 hr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const Sa=new Qs,_a=new wa,Aa=new Nn,Ta=new Ts,za=new Ts,Ca=new Ts,Ia=new Ts,Ba=new Ts,ka=new Ts,Oa=new Ts,Pa=new Ts;class Ra extends Ar{constructor(t=new Wn,e=new Ma){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;t(t.far-t.near)**2)return}Sa.copy(r).invert(),_a.copy(t.ray).applyMatrix4(Sa),null!==i.boundingBox&&!1===_a.intersectsBox(i.boundingBox)||this._computeIntersections(t,e,_a)}}_computeIntersections(t,e,i){let s;const r=this.geometry,n=this.material,a=r.index,o=r.attributes.position,h=r.attributes.uv,l=r.attributes.uv1,c=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(n))for(let r=0,o=u.length;ri.far?null:{distance:l,point:Pa.clone(),object:t}}(t,e,i,s,za,Ca,Ia,Oa);if(c){const t=new Ts;$r.getBarycoord(Oa,za,Ca,Ia,t),r&&(c.uv=$r.getInterpolatedAttribute(r,o,h,l,t,new _s)),n&&(c.uv1=$r.getInterpolatedAttribute(n,o,h,l,t,new _s)),a&&(c.normal=$r.getInterpolatedAttribute(a,o,h,l,t,new Ts),c.normal.dot(s.direction)>0&&c.normal.multiplyScalar(-1));const e={a:o,b:h,c:l,normal:new Ts,materialIndex:0};$r.getNormal(za,Ca,Ia,e.normal),c.face=e,c.barycoord=t}return c}const Va=new Js,Ea=new Js,La=new Js,Fa=new Js,ja=new Qs,Da=new Ts,Ua=new Nn,Wa=new Qs,qa=new wa;class Ja extends Ra{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=at,this.bindMatrix=new Qs,this.bindMatrixInverse=new Qs,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;null===this.boundingBox&&(this.boundingBox=new Qr),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let t=0;t1?null:e.copy(t.start).addScaledVector(i,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||ho.getNormalMatrix(t),s=this.coplanarPoint(ao).applyMatrix4(t),r=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const co=new Nn,uo=new _s(.5,.5),po=new Ts;class mo{constructor(t=new lo,e=new lo,i=new lo,s=new lo,r=new lo,n=new lo){this.planes=[t,e,i,s,r,n]}set(t,e,i,s,r,n){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(s),a[4].copy(r),a[5].copy(n),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=2e3,i=!1){const s=this.planes,r=t.elements,n=r[0],a=r[1],o=r[2],h=r[3],l=r[4],c=r[5],u=r[6],d=r[7],p=r[8],m=r[9],y=r[10],g=r[11],f=r[12],x=r[13],b=r[14],v=r[15];if(s[0].setComponents(h-n,d-l,g-p,v-f).normalize(),s[1].setComponents(h+n,d+l,g+p,v+f).normalize(),s[2].setComponents(h+a,d+c,g+m,v+x).normalize(),s[3].setComponents(h-a,d-c,g-m,v-x).normalize(),i)s[4].setComponents(o,u,y,b).normalize(),s[5].setComponents(h-o,d-u,g-y,v-b).normalize();else if(s[4].setComponents(h-o,d-u,g-y,v-b).normalize(),e===Wi)s[5].setComponents(h+o,d+u,g+y,v+b).normalize();else{if(e!==qi)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);s[5].setComponents(o,u,y,b).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),co.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),co.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(co)}intersectsSprite(t){co.center.set(0,0,0);const e=uo.distanceTo(t.center);return co.radius=.7071067811865476+e,co.applyMatrix4(t.matrixWorld),this.intersectsSphere(co)}intersectsSphere(t){const e=this.planes,i=t.center,s=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(i)0?t.max.x:t.min.x,po.y=s.normal.y>0?t.max.y:t.min.y,po.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(po)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const yo=new Qs,go=new mo;class fo{constructor(){this.coordinateSystem=Wi}intersectsObject(t,e){if(!e.isArrayCamera||0===e.cameras.length)return!1;for(let i=0;i=r.length&&r.push({start:-1,count:-1,z:-1,index:-1});const a=r[this.index];n.push(a),this.index++,a.start=t,a.count=e,a.z=i,a.index=s}reset(){this.list.length=0,this.index=0}}const Mo=new Qs,So=new Pr(1,1,1),_o=new mo,Ao=new fo,To=new Qr,zo=new Nn,Co=new Ts,Io=new Ts,Bo=new Ts,ko=new wo,Oo=new Ra,Po=[];function Ro(t,e,i=0){const s=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const r=t.count;for(let n=0;n65535?new Uint32Array(s):new Uint16Array(s);e.setIndex(new Mn(t,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(Boolean(t.getIndex())!==Boolean(e.getIndex()))throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in e.attributes){if(!t.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=t.getAttribute(i),r=e.getAttribute(i);if(s.itemSize!==r.itemSize||s.normalized!==r.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(t){const e=this._instanceInfo;if(t<0||t>=e.length||!1===e[t].active)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${t}. Instance is either out of range or has been deleted.`)}validateGeometryId(t){const e=this._geometryInfo;if(t<0||t>=e.length||!1===e[t].active)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${t}. Geometry is either out of range or has been deleted.`)}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Qr);const t=this.boundingBox,e=this._instanceInfo;t.makeEmpty();for(let i=0,s=e.length;i=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const e={visible:!0,active:!0,geometryIndex:t};let i=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(xo),i=this._availableInstanceIds.shift(),this._instanceInfo[i]=e):(i=this._instanceInfo.length,this._instanceInfo.push(e));const s=this._matricesTexture;Mo.identity().toArray(s.image.data,16*i),s.needsUpdate=!0;const r=this._colorsTexture;return r&&(So.toArray(r.image.data,4*i),r.needsUpdate=!0),this._visibilityChanged=!0,i}addGeometry(t,e=-1,i=-1){this._initializeGeometry(t),this._validateGeometry(t);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},r=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=-1===e?t.getAttribute("position").count:e;const n=t.getIndex();if(null!==n&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=-1===i?n.count:i),-1!==s.indexStart&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let a;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(xo),a=this._availableGeometryIds.shift(),r[a]=s):(a=this._geometryCount,this._geometryCount++,r.push(s)),this.setGeometryAt(a,t),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,a}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const i=this.geometry,s=null!==i.getIndex(),r=i.getIndex(),n=e.getIndex(),a=this._geometryInfo[t];if(s&&n.count>a.reservedIndexCount||e.attributes.position.count>a.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,h=a.reservedVertexCount;a.vertexCount=e.getAttribute("position").count;for(const t in i.attributes){const s=e.getAttribute(t),r=i.getAttribute(t);Ro(s,r,o);const n=s.itemSize;for(let t=s.count,e=h;t=e.length||!1===e[t].active)return this;const i=this._instanceInfo;for(let e=0,s=i.length;ee).sort((t,e)=>i[t].vertexStart-i[e].vertexStart),r=this.geometry;for(let n=0,a=i.length;n=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[t];if(null===s.boundingBox){const t=new Qr,e=i.index,r=i.attributes.position;for(let i=s.start,n=s.start+s.count;i=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[t];if(null===s.boundingSphere){const e=new Nn;this.getBoundingBoxAt(t,To),To.getCenter(e.center);const r=i.index,n=i.attributes.position;let a=0;for(let t=s.start,i=s.start+s.count;tt.active);if(Math.max(...i.map(t=>t.vertexStart+t.reservedVertexCount))>t)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${e}. Cannot shrink further.`);if(this.geometry.index){if(Math.max(...i.map(t=>t.indexStart+t.reservedIndexCount))>e)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${e}. Cannot shrink further.`)}const s=this.geometry;s.dispose(),this._maxVertexCount=t,this._maxIndexCount=e,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Wn,this._initializeGeometry(s));const r=this.geometry;s.index&&No(s.index.array,r.index.array);for(const t in s.attributes)No(s.attributes[t].array,r.attributes[t].array)}raycast(t,e){const i=this._instanceInfo,s=this._geometryInfo,r=this.matrixWorld,n=this.geometry;Oo.material=this.material,Oo.geometry.index=n.index,Oo.geometry.attributes=n.attributes,null===Oo.geometry.boundingBox&&(Oo.geometry.boundingBox=new Qr),null===Oo.geometry.boundingSphere&&(Oo.geometry.boundingSphere=new Nn);for(let n=0,a=i.length;n({...t,boundingBox:null!==t.boundingBox?t.boundingBox.clone():null,boundingSphere:null!==t.boundingSphere?t.boundingSphere.clone():null})),this._instanceInfo=t._instanceInfo.map(t=>({...t})),this._availableInstanceIds=t._availableInstanceIds.slice(),this._availableGeometryIds=t._availableGeometryIds.slice(),this._nextIndexStart=t._nextIndexStart,this._nextVertexStart=t._nextVertexStart,this._geometryCount=t._geometryCount,this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._indirectTexture=t._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(t,e,i,s,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const n=s.getIndex();let a=null===n?1:n.array.BYTES_PER_ELEMENT,o=1;r.wireframe&&(o=2,a=s.attributes.position.count>65535?4:2);const h=this._instanceInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,u=this._geometryInfo,d=this.perObjectFrustumCulled,p=this._indirectTexture,m=p.image.data,y=i.isArrayCamera?Ao:_o;d&&!i.isArrayCamera&&(Mo.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),_o.setFromProjectionMatrix(Mo,i.coordinateSystem,i.reversedDepth));let g=0;if(this.sortObjects){Mo.copy(this.matrixWorld).invert(),Co.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Mo),Io.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Mo);for(let t=0,e=h.length;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;ts)return;Wo.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(Wo);return he.far?void 0:{distance:h,point:qo.clone().applyMatrix4(t.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:t}}const Yo=new Ts,Ho=new Ts;class Zo extends Jo{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,i=[];for(let t=0,s=e.count;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;tr.far)return;n.push({distance:h,distanceToRay:Math.sqrt(o),point:i,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class rh extends qs{constructor(t,e,i,s,r=1006,n=1006,a,o,h){super(t,e,i,s,r,n,a,o,h),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const l=this;"requestVideoFrameCallback"in t&&(this._requestVideoFrameCallbackId=t.requestVideoFrameCallback(function e(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=t.requestVideoFrameCallback(e)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;!1==="requestVideoFrameCallback"in t&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){0!==this._requestVideoFrameCallbackId&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class nh extends rh{constructor(t,e,i,s,r,n,a,o){super({},t,e,i,s,r,n,a,o),this.isVideoFrameTexture=!0}update(){}clone(){return(new this.constructor).copy(this)}setFrame(t){this.image=t,this.needsUpdate=!0}}class ah extends qs{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=ft,this.minFilter=ft,this.generateMipmaps=!1,this.needsUpdate=!0}}class oh extends qs{constructor(t,e,i,s,r,n,a,o,h,l,c,u){super(null,n,a,o,h,l,s,r,c,u),this.isCompressedTexture=!0,this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class hh extends oh{constructor(t,e,i,s,r,n){super(t,e,i,r,n),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=yt,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class lh extends oh{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,lt),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class ch extends qs{constructor(t=[],e=301,i,s,r,n,a,o,h,l){super(t,e,i,s,r,n,a,o,h,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class uh extends qs{constructor(t,e,i,s,r,n,a,o,h){super(t,e,i,s,r,n,a,o,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class dh extends qs{constructor(t,e,i,s,r,n,a,o,h){super(t,e,i,s,r,n,a,o,h),this.isHTMLTexture=!0,this.generateMipmaps=!1,this.needsUpdate=!0;const l=t?t.parentNode:null;null!==l&&"requestPaint"in l&&(l.onpaint=()=>{this.needsUpdate=!0},l.requestPaint())}dispose(){const t=this.image?this.image.parentNode:null;null!==t&&"onpaint"in t&&(t.onpaint=null),super.dispose()}}class ph extends qs{constructor(t,e,i=1014,s,r,n,a=1003,o=1003,h,l=1026,c=1){if(l!==Wt&&1027!==l)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:t,height:e,depth:c},s,r,n,a,o,l,i,h),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new js(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return null!==this.compareFunction&&(e.compareFunction=this.compareFunction),e}}class mh extends ph{constructor(t,e=1014,i=301,s,r,n=1003,a=1003,o,h=1026){const l={width:t,height:t,depth:1},c=[l,l,l,l,l,l];super(t,t,e,i,s,r,n,a,o,h),this.image=c,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class yh extends qs{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class gh extends Wn{constructor(t=1,e=1,i=1,s=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:s,heightSegments:r,depthSegments:n};const a=this;s=Math.floor(s),r=Math.floor(r),n=Math.floor(n);const o=[],h=[],l=[],c=[];let u=0,d=0;function p(t,e,i,s,r,n,p,m,y,g,f){const x=n/y,b=p/g,v=n/2,w=p/2,M=m/2,S=y+1,_=g+1;let A=0,T=0;const z=new Ts;for(let n=0;n<_;n++){const a=n*b-w;for(let o=0;o0?1:-1,l.push(z.x,z.y,z.z),c.push(o/y),c.push(1-n/g),A+=1}}for(let t=0;t0){const t=(f-1)*m;for(let e=0;e0||0!==s)&&(l.push(n,a,h),x+=3),(e>0||s!==r-1)&&(l.push(a,o,h),x+=3)}h.addGroup(g,x,0),g+=x}(),!1===n&&(t>0&&f(!0),e>0&&f(!1)),this.setIndex(l),this.setAttribute("position",new kn(c,3)),this.setAttribute("normal",new kn(u,3)),this.setAttribute("uv",new kn(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new bh(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class vh extends bh{constructor(t=1,e=1,i=32,s=1,r=!1,n=0,a=2*Math.PI){super(0,t,e,i,s,r,n,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:s,openEnded:r,thetaStart:n,thetaLength:a}}static fromJSON(t){return new vh(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class wh extends Wn{constructor(t=[],e=[],i=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:i,detail:s};const r=[],n=[];function a(t,e,i,s){const r=s+1,n=[];for(let s=0;s<=r;s++){n[s]=[];const a=t.clone().lerp(i,s/r),o=e.clone().lerp(i,s/r),h=r-s;for(let t=0;t<=h;t++)n[s][t]=0===t&&s===r?a:a.clone().lerp(o,t/h)}for(let t=0;t.9&&a<.1&&(e<.2&&(n[t+0]+=1),i<.2&&(n[t+2]+=1),s<.2&&(n[t+4]+=1))}}()}(),this.setAttribute("position",new kn(r,3)),this.setAttribute("normal",new kn(r.slice(),3)),this.setAttribute("uv",new kn(n,2)),0===s?this.computeVertexNormals():this.normalizeNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new wh(t.vertices,t.indices,t.radius,t.detail)}}class Mh extends wh{constructor(t=1,e=0){const i=(1+Math.sqrt(5))/2,s=1/i;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-s,-i,0,-s,i,0,s,-i,0,s,i,-s,-i,0,-s,i,0,s,-i,0,s,i,0,-i,0,-s,i,0,-s,-i,0,s,i,0,s],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Mh(t.radius,t.detail)}}const Sh=new Ts,_h=new Ts,Ah=new Ts,Th=new $r;class zh extends Wn{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const i=4,s=Math.pow(10,i),r=Math.cos(ys*e),n=t.getIndex(),a=t.getAttribute("position"),o=n?n.count:a.count,h=[0,0,0],l=["a","b","c"],c=new Array(3),u={},d=[];for(let t=0;t0)){h=s;break}h=s-1}if(s=h,i[s]===n)return s/(r-1);const l=i[s];return(s+(n-l)/(i[s+1]-l))/(r-1)}getTangent(t,e){const i=1e-4;let s=t-i,r=t+i;s<0&&(s=0),r>1&&(r=1);const n=this.getPoint(s),a=this.getPoint(r),o=e||(n.isVector2?new _s:new Ts);return o.copy(a).sub(n).normalize(),o}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e=!1){const i=new Ts,s=[],r=[],n=[],a=new Ts,o=new Qs;for(let e=0;e<=t;e++){const i=e/t;s[e]=this.getTangentAt(i,new Ts)}r[0]=new Ts,n[0]=new Ts;let h=Number.MAX_VALUE;const l=Math.abs(s[0].x),c=Math.abs(s[0].y),u=Math.abs(s[0].z);l<=h&&(h=l,i.set(1,0,0)),c<=h&&(h=c,i.set(0,1,0)),u<=h&&i.set(0,0,1),a.crossVectors(s[0],i).normalize(),r[0].crossVectors(s[0],a),n[0].crossVectors(s[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),n[e]=n[e-1].clone(),a.crossVectors(s[e-1],s[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(xs(s[e-1].dot(s[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}n[e].crossVectors(s[e],r[e])}if(!0===e){let e=Math.acos(xs(r[0].dot(r[t]),-1,1));e/=t,s[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let i=1;i<=t;i++)r[i].applyMatrix4(o.makeRotationAxis(s[i],e*i)),n[i].crossVectors(s[i],r[i])}return{tangents:s,normals:r,binormals:n}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Ih extends Ch{constructor(t=0,e=0,i=1,s=1,r=0,n=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=s,this.aStartAngle=r,this.aEndAngle=n,this.aClockwise=a,this.aRotation=o}getPoint(t,e=new _s){const i=e,s=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const n=Math.abs(r)s;)r-=s;r0?0:(Math.floor(Math.abs(h)/r)+1)*r:0===l&&h===r-1&&(h=r-2,l=1),this.closed||h>0?a=s[(h-1)%r]:(Ph.subVectors(s[0],s[1]).add(s[0]),a=Ph);const c=s[h%r],u=s[(h+1)%r];if(this.closed||h+2s.length-2?s.length-1:n+1],c=s[n>s.length-3?s.length-1:n+2];return i.set(Lh(a,o.x,h.x,l.x,c.x),Lh(a,o.y,h.y,l.y,c.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e=i){const t=s[r]-i,n=this.curves[r],a=n.getLength(),o=0===a?0:1-t/a;return n.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,s=this.curves.length;i1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e0){const t=h.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(h);const l=h.getPoint(1);return this.currentPoint.copy(l),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class $h extends Gh{constructor(t){super(t),this.uuid=fs(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,s=this.holes.length;i80*i){o=t[0],h=t[1];let e=o,s=h;for(let n=i;ne&&(e=i),r>s&&(s=r)}l=Math.max(e-o,s-h),l=0!==l?32767/l:0}return el(n,a,i,o,h,l,0),a}function Kh(t,e,i,s,r){let n;if(r===function(t,e,i,s){let r=0;for(let n=e,a=i-s;n0)for(let r=e;r=e;r-=s)n=wl(r/s|0,t[r],t[r+1],n);return n&&yl(n,n.next)&&(Ml(n),n=n.next),n}function tl(t,e){if(!t)return t;e||(e=t);let i,s=t;do{if(i=!1,s.steiner||!yl(s,s.next)&&0!==ml(s.prev,s,s.next))s=s.next;else{if(Ml(s),s=e=s.prev,s===s.next)break;i=!0}}while(i||s!==e);return e}function el(t,e,i,s,r,n,a){if(!t)return;!a&&n&&function(t,e,i,s){let r=t;do{0===r.z&&(r.z=ll(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,i=1;do{let s,r=t;t=null;let n=null;for(e=0;r;){e++;let a=r,o=0;for(let t=0;t0||h>0&&a;)0!==o&&(0===h||!a||r.z<=a.z)?(s=r,r=r.nextZ,o--):(s=a,a=a.nextZ,h--),n?n.nextZ=s:t=s,s.prevZ=n,n=s;r=a}n.nextZ=null,i*=2}while(e>1)}(r)}(t,s,r,n);let o=t;for(;t.prev!==t.next;){const h=t.prev,l=t.next;if(n?sl(t,s,r,n):il(t))e.push(h.i,t.i,l.i),Ml(t),t=l.next,o=l.next;else if((t=l)===o){a?1===a?el(t=rl(tl(t),e),e,i,s,r,n,2):2===a&&nl(t,e,i,s,r,n):el(tl(t),e,i,s,r,n,1);break}}}function il(t){const e=t.prev,i=t,s=t.next;if(ml(e,i,s)>=0)return!1;const r=e.x,n=i.x,a=s.x,o=e.y,h=i.y,l=s.y,c=Math.min(r,n,a),u=Math.min(o,h,l),d=Math.max(r,n,a),p=Math.max(o,h,l);let m=s.next;for(;m!==e;){if(m.x>=c&&m.x<=d&&m.y>=u&&m.y<=p&&dl(r,o,n,h,a,l,m.x,m.y)&&ml(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function sl(t,e,i,s){const r=t.prev,n=t,a=t.next;if(ml(r,n,a)>=0)return!1;const o=r.x,h=n.x,l=a.x,c=r.y,u=n.y,d=a.y,p=Math.min(o,h,l),m=Math.min(c,u,d),y=Math.max(o,h,l),g=Math.max(c,u,d),f=ll(p,m,e,i,s),x=ll(y,g,e,i,s);let b=t.prevZ,v=t.nextZ;for(;b&&b.z>=f&&v&&v.z<=x;){if(b.x>=p&&b.x<=y&&b.y>=m&&b.y<=g&&b!==r&&b!==a&&dl(o,c,h,u,l,d,b.x,b.y)&&ml(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=p&&v.x<=y&&v.y>=m&&v.y<=g&&v!==r&&v!==a&&dl(o,c,h,u,l,d,v.x,v.y)&&ml(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=f;){if(b.x>=p&&b.x<=y&&b.y>=m&&b.y<=g&&b!==r&&b!==a&&dl(o,c,h,u,l,d,b.x,b.y)&&ml(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=x;){if(v.x>=p&&v.x<=y&&v.y>=m&&v.y<=g&&v!==r&&v!==a&&dl(o,c,h,u,l,d,v.x,v.y)&&ml(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function rl(t,e){let i=t;do{const s=i.prev,r=i.next.next;!yl(s,r)&&gl(s,i,i.next,r)&&bl(s,r)&&bl(r,s)&&(e.push(s.i,i.i,r.i),Ml(i),Ml(i.next),i=t=r),i=i.next}while(i!==t);return tl(i)}function nl(t,e,i,s,r,n){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&pl(a,t)){let o=vl(a,t);return a=tl(a,a.next),o=tl(o,o.next),el(a,e,i,s,r,n,0),void el(o,e,i,s,r,n,0)}t=t.next}a=a.next}while(a!==t)}function al(t,e){let i=t.x-e.x;if(0===i&&(i=t.y-e.y,0===i)){i=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)}return i}function ol(t,e){const i=function(t,e){let i=e;const s=t.x,r=t.y;let n,a=-1/0;if(yl(t,i))return i;do{if(yl(t,i.next))return i.next;if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const t=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=s&&t>a&&(a=t,n=i.x=i.x&&i.x>=h&&s!==i.x&&ul(rn.x||i.x===n.x&&hl(n,i)))&&(n=i,c=e)}i=i.next}while(i!==o);return n}(t,e);if(!i)return e;const s=vl(i,t);return tl(s,s.next),tl(i,i.next)}function hl(t,e){return ml(t.prev,t,e.prev)<0&&ml(e.next,t,t.next)<0}function ll(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function cl(t){let e=t,i=t;do{(e.x=(t-a)*(n-o)&&(t-a)*(s-o)>=(i-a)*(e-o)&&(i-a)*(n-o)>=(r-a)*(s-o)}function dl(t,e,i,s,r,n,a,o){return!(t===a&&e===o)&&ul(t,e,i,s,r,n,a,o)}function pl(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&gl(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(bl(t,e)&&bl(e,t)&&function(t,e){let i=t,s=!1;const r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(ml(t.prev,t,e.prev)||ml(t,e.prev,e))||yl(t,e)&&ml(t.prev,t,t.next)>0&&ml(e.prev,e,e.next)>0)}function ml(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function yl(t,e){return t.x===e.x&&t.y===e.y}function gl(t,e,i,s){const r=xl(ml(t,e,i)),n=xl(ml(t,e,s)),a=xl(ml(i,s,t)),o=xl(ml(i,s,e));return r!==n&&a!==o||(!(0!==r||!fl(t,i,e))||(!(0!==n||!fl(t,s,e))||(!(0!==a||!fl(i,t,s))||!(0!==o||!fl(i,e,s)))))}function fl(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function xl(t){return t>0?1:t<0?-1:0}function bl(t,e){return ml(t.prev,t,t.next)<0?ml(t,e,t.next)>=0&&ml(t,t.prev,e)>=0:ml(t,e,t.prev)<0||ml(t,t.next,e)<0}function vl(t,e){const i=Sl(t.i,t.x,t.y),s=Sl(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function wl(t,e,i,s){const r=Sl(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function Ml(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Sl(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class _l{static triangulate(t,e,i=2){return Qh(t,e,i)}}class Al{static area(t){const e=t.length;let i=0;for(let s=e-1,r=0;r2&&t[e-1].equals(t[0])&&t.pop()}function zl(t,e){for(let i=0;iNumber.EPSILON){const u=Math.sqrt(c),d=Math.sqrt(h*h+l*l),p=e.x-o/u,m=e.y+a/u,y=((i.x-l/d-p)*l-(i.y+h/d-m)*h)/(a*l-o*h);s=p+a*y-t.x,r=m+o*y-t.y;const g=s*s+r*r;if(g<=2)return new _s(s,r);n=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?h>Number.EPSILON&&(t=!0):a<-Number.EPSILON?h<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(l)&&(t=!0),t?(s=-o,r=a,n=Math.sqrt(c)):(s=a,r=o,n=Math.sqrt(c/2))}return new _s(s/n,r/n)}const k=[];for(let t=0,e=z.length,i=e-1,s=t+1;t=0;t--){const e=t/p,i=c*Math.cos(e*Math.PI/2),s=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=z.length;t=0;){const s=i;let r=i-1;r<0&&(r=t.length-1);for(let t=0,i=o+2*p;t0)&&d.push(e,r,h),(t!==i-1||o0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const i={};for(const t in this.extensions)!0===this.extensions[t]&&(i[t]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}}class $l extends Gl{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ql extends Zn{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Pr(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 Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(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 hr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class Kl extends Ql{constructor(t){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 _s(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return xs(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Pr(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 Pr(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Pr(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(t)}get anisotropy(){return this._anisotropy}set anisotropy(t){this._anisotropy>0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class tc extends Zn{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Pr(16777215),this.specular=new Pr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ec extends Zn{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Pr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class ic extends Zn{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class sc extends Zn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Pr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class rc extends Zn{constructor(t){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(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class nc extends Zn{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}class ac extends Zn{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Pr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new _s(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(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this.fog=t.fog,this}}class oc extends Eo{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function hc(t,e){return t&&t.constructor!==e?"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t):t}function lc(t){const e=t.length,i=new Array(e);for(let t=0;t!==e;++t)i[t]=t;return i.sort(function(e,i){return t[e]-t[i]}),i}function cc(t,e,i){const s=t.length,r=new t.constructor(s);for(let n=0,a=0;a!==s;++n){const s=i[n]*e;for(let i=0;i!==e;++i)r[a++]=t[s+i]}return r}function uc(t,e,i,s){let r=1,n=t[0];for(;void 0!==n&&void 0===n[s];)n=t[r++];if(void 0===n)return;let a=n[s];if(void 0!==a)if(Array.isArray(a))do{a=n[s],void 0!==a&&(e.push(n.time),i.push(...a)),n=t[r++]}while(void 0!==n);else if(void 0!==a.toArray)do{a=n[s],void 0!==a&&(e.push(n.time),a.toArray(i,i.length)),n=t[r++]}while(void 0!==n);else do{a=n[s],void 0!==a&&(e.push(n.time),i.push(a)),n=t[r++]}while(void 0!==n)}class dc{static convertArray(t,e){return hc(t,e)}static isTypedArray(t){return $i(t)}static getKeyframeOrder(t){return lc(t)}static sortedArray(t,e,i){return cc(t,e,i)}static flattenJSON(t,e,i,s){uc(t,e,i,s)}static subclip(t,e,i,s,r=30){return function(t,e,i,s,r=30){const n=t.clone();n.name=e;const a=[];for(let t=0;t=s)){h.push(e.times[t]);for(let i=0;in.tracks[t].times[0]&&(o=n.tracks[t].times[0]);for(let t=0;t=s.times[u]){const t=u*h+o,e=t+h-o;d=s.values.slice(t,e)}else{const t=s.createInterpolant(),e=o,i=h-o;t.evaluate(n),d=t.resultBuffer.slice(e,i)}"quaternion"===r&&(new As).fromArray(d).normalize().conjugate().toArray(d);const p=a.times.length;for(let t=0;t=r)){const a=e[1];t=r)break e}n=i,i=0;break i}break t}for(;i>>1;te;)--n;if(++n,0!==r||n!==s){r>=n&&(n=Math.max(n,1),r=n-1);const t=this.getValueSize();this.times=i.slice(r,n),this.values=this.values.slice(r*t,n*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!==0&&(os("KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,s=this.values,r=i.length;0===r&&(os("KeyframeTrack: Track is empty.",this),t=!1);let n=null;for(let e=0;e!==r;e++){const s=i[e];if("number"==typeof s&&isNaN(s)){os("KeyframeTrack: Time is not a valid number.",this,e,s),t=!1;break}if(null!==n&&n>s){os("KeyframeTrack: Out of order keys.",this,e,s,n),t=!1;break}n=s}if(void 0!==s&&$i(s))for(let e=0,i=s.length;e!==i;++e){const i=s[e];if(isNaN(i)){os("KeyframeTrack: Value is not a valid number.",this,e,i),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===Le,r=t.length-1;let n=1;for(let a=1;a0){t[n]=t[r];for(let t=r*i,s=n*i,a=0;a!==i;++a)e[s+a]=e[t+a];++n}return n!==t.length?(this.times=t.slice(0,n),this.values=e.slice(0,n*i)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),i=new(0,this.constructor)(this.name,t,e);return i.createInterpolant=this.createInterpolant,i}}xc.prototype.ValueTypeName="",xc.prototype.TimeBufferType=Float32Array,xc.prototype.ValueBufferType=Float32Array,xc.prototype.DefaultInterpolation=Ee;class bc extends xc{constructor(t,e,i){super(t,e,i)}}bc.prototype.ValueTypeName="bool",bc.prototype.ValueBufferType=Array,bc.prototype.DefaultInterpolation=Ve,bc.prototype.InterpolantFactoryMethodLinear=void 0,bc.prototype.InterpolantFactoryMethodSmooth=void 0;class vc extends xc{constructor(t,e,i,s){super(t,e,i,s)}}vc.prototype.ValueTypeName="color";class wc extends xc{constructor(t,e,i,s){super(t,e,i,s)}}wc.prototype.ValueTypeName="number";class Mc extends pc{constructor(t,e,i,s){super(t,e,i,s)}interpolate_(t,e,i,s){const r=this.resultBuffer,n=this.sampleValues,a=this.valueSize,o=(i-e)/(s-e);let h=t*a;for(let t=h+a;h!==t;h+=4)As.slerpFlat(r,0,n,h-a,n,h,o);return r}}class Sc extends xc{constructor(t,e,i,s){super(t,e,i,s)}InterpolantFactoryMethodLinear(t){return new Mc(this.times,this.values,this.getValueSize(),t)}}Sc.prototype.ValueTypeName="quaternion",Sc.prototype.InterpolantFactoryMethodSmooth=void 0;class _c extends xc{constructor(t,e,i){super(t,e,i)}}_c.prototype.ValueTypeName="string",_c.prototype.ValueBufferType=Array,_c.prototype.DefaultInterpolation=Ve,_c.prototype.InterpolantFactoryMethodLinear=void 0,_c.prototype.InterpolantFactoryMethodSmooth=void 0;class Ac extends xc{constructor(t,e,i,s){super(t,e,i,s)}}Ac.prototype.ValueTypeName="vector";class Tc{constructor(t="",e=-1,i=[],s=2500){this.name=t,this.tracks=i,this.duration=e,this.blendMode=s,this.uuid=fs(),this.userData={},this.duration<0&&this.resetDuration()}static parse(t){const e=[],i=t.tracks,s=1/(t.fps||1);for(let t=0,r=i.length;t!==r;++t)e.push(zc(i[t]).scale(s));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r.userData=JSON.parse(t.userData||"{}"),r}static toJSON(t){const e=[],i=t.tracks,s={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode,userData:JSON.stringify(t.userData)};for(let t=0,s=i.length;t!==s;++t)e.push(xc.toJSON(i[t]));return s}static CreateFromMorphTargetSequence(t,e,i,s){const r=e.length,n=[];for(let t=0;t1){const t=n[1];let e=s[t];e||(s[t]=e=[]),e.push(i)}}const n=[];for(const t in s)n.push(this.CreateFromMorphTargetSequence(t,s[t],e,i));return n}static parseAnimation(t,e){if(as("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!t)return os("AnimationClip: No animation in JSONLoader data."),null;const i=function(t,e,i,s,r){if(0!==i.length){const n=[],a=[];uc(i,n,a,s),0!==n.length&&r.push(new t(e,n,a))}},s=[],r=t.name||"default",n=t.fps||30,a=t.blendMode;let o=t.length||-1;const h=t.hierarchy||[];for(let t=0;t{e&&e(r),this.manager.itemEnd(t)},0);if(void 0!==Pc[t])return void Pc[t].push({onLoad:e,onProgress:i,onError:s});Pc[t]=[],Pc[t].push({onLoad:e,onProgress:i,onError:s});const n=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:"function"==typeof AbortSignal.any?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,o=this.responseType;fetch(n).then(e=>{if(200===e.status||0===e.status){if(0===e.status&&as("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const i=Pc[t],s=e.body.getReader(),r=e.headers.get("X-File-Size")||e.headers.get("Content-Length"),n=r?parseInt(r):0,a=0!==n;let o=0;const h=new ReadableStream({start(t){!function e(){s.read().then(({done:s,value:r})=>{if(s)t.close();else{o+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:n});for(let t=0,e=i.length;t{t.error(e)})}()}});return new Response(h)}throw new Rc(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`,e)}).then(t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then(t=>(new DOMParser).parseFromString(t,a));case"json":return t.json();default:if(""===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),i=e&&e[1]?e[1].toLowerCase():void 0,s=new TextDecoder(i);return t.arrayBuffer().then(t=>s.decode(t))}}}).then(e=>{Cc.add(`file:${t}`,e);const i=Pc[t];delete Pc[t];for(let t=0,s=i.length;t{const i=Pc[t];if(void 0===i)throw this.manager.itemError(t),e;delete Pc[t];for(let t=0,s=i.length;t{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class Vc extends Oc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new Nc(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(t,function(i){try{e(r.parse(JSON.parse(i)))}catch(e){s?s(e):os(e),r.manager.itemError(t)}},i,s)}parse(t){const e=[];for(let i=0;i0:s.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(s.uniforms[e]={},r.type){case"t":s.uniforms[e].value=i(r.value);break;case"c":s.uniforms[e].value=(new Pr).setHex(r.value);break;case"v2":s.uniforms[e].value=(new _s).fromArray(r.value);break;case"v3":s.uniforms[e].value=(new Ts).fromArray(r.value);break;case"v4":s.uniforms[e].value=(new Js).fromArray(r.value);break;case"m3":s.uniforms[e].value=(new Is).fromArray(r.value);break;case"m4":s.uniforms[e].value=(new Qs).fromArray(r.value);break;default:s.uniforms[e].value=r.value}}if(void 0!==t.defines&&(s.defines=t.defines),void 0!==t.vertexShader&&(s.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(s.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(s.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)s.extensions[e]=t.extensions[e];if(void 0!==t.lights&&(s.lights=t.lights),void 0!==t.clipping&&(s.clipping=t.clipping),void 0!==t.size&&(s.size=t.size),void 0!==t.sizeAttenuation&&(s.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(s.map=i(t.map)),void 0!==t.matcap&&(s.matcap=i(t.matcap)),void 0!==t.alphaMap&&(s.alphaMap=i(t.alphaMap)),void 0!==t.bumpMap&&(s.bumpMap=i(t.bumpMap)),void 0!==t.bumpScale&&(s.bumpScale=t.bumpScale),void 0!==t.normalMap&&(s.normalMap=i(t.normalMap)),void 0!==t.normalMapType&&(s.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),s.normalScale=(new _s).fromArray(e)}return void 0!==t.displacementMap&&(s.displacementMap=i(t.displacementMap)),void 0!==t.displacementScale&&(s.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(s.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(s.roughnessMap=i(t.roughnessMap)),void 0!==t.metalnessMap&&(s.metalnessMap=i(t.metalnessMap)),void 0!==t.emissiveMap&&(s.emissiveMap=i(t.emissiveMap)),void 0!==t.emissiveIntensity&&(s.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(s.specularMap=i(t.specularMap)),void 0!==t.specularIntensityMap&&(s.specularIntensityMap=i(t.specularIntensityMap)),void 0!==t.specularColorMap&&(s.specularColorMap=i(t.specularColorMap)),void 0!==t.envMap&&(s.envMap=i(t.envMap)),void 0!==t.envMapRotation&&s.envMapRotation.fromArray(t.envMapRotation),void 0!==t.envMapIntensity&&(s.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(s.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(s.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(s.lightMap=i(t.lightMap)),void 0!==t.lightMapIntensity&&(s.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(s.aoMap=i(t.aoMap)),void 0!==t.aoMapIntensity&&(s.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(s.gradientMap=i(t.gradientMap)),void 0!==t.clearcoatMap&&(s.clearcoatMap=i(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(s.clearcoatRoughnessMap=i(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(s.clearcoatNormalMap=i(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(s.clearcoatNormalScale=(new _s).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(s.iridescenceMap=i(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(s.iridescenceThicknessMap=i(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(s.transmissionMap=i(t.transmissionMap)),void 0!==t.thicknessMap&&(s.thicknessMap=i(t.thicknessMap)),void 0!==t.anisotropyMap&&(s.anisotropyMap=i(t.anisotropyMap)),void 0!==t.sheenColorMap&&(s.sheenColorMap=i(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(s.sheenRoughnessMap=i(t.sheenRoughnessMap)),s}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return mu.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:ql,SpriteMaterial:Gn,RawShaderMaterial:$l,ShaderMaterial:Gl,PointsMaterial:$o,MeshPhysicalMaterial:Kl,MeshStandardMaterial:Ql,MeshPhongMaterial:tc,MeshToonMaterial:ec,MeshNormalMaterial:ic,MeshLambertMaterial:sc,MeshDepthMaterial:rc,MeshDistanceMaterial:nc,MeshBasicMaterial:Ma,MeshMatcapMaterial:ac,LineDashedMaterial:oc,LineBasicMaterial:Eo,Material:Zn}[t]}}class yu{static extractUrlBase(t){const e=t.lastIndexOf("/");return-1===e?"./":t.slice(0,e+1)}static resolveURL(t,e){return"string"!=typeof t||""===t?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}}class gu extends Wn{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}toJSON(){const t=super.toJSON();return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}class fu extends Oc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new Nc(r.manager);n.setPath(r.path),n.setRequestHeader(r.requestHeader),n.setWithCredentials(r.withCredentials),n.load(t,function(i){try{e(r.parse(JSON.parse(i)))}catch(e){s?s(e):os(e),r.manager.itemError(t)}},i,s)}parse(t){const e={},i={};function s(t,s){if(void 0!==e[s])return e[s];const r=t.interleavedBuffers[s],n=function(t,e){if(void 0!==i[e])return i[e];const s=t.arrayBuffers,r=s[e],n=new Uint32Array(r).buffer;return i[e]=n,n}(t,r.buffer),a=Gi(r.type,n),o=new qn(a,r.stride);return o.uuid=r.uuid,e[s]=o,o}const r=t.isInstancedBufferGeometry?new gu:new Wn,n=t.data.index;if(void 0!==n){const t=Gi(n.type,n.array);r.setIndex(new Mn(t,1))}const a=t.data.attributes;for(const e in a){const i=a[e];let n;if(i.isInterleavedBufferAttribute){const e=s(t.data,i.data);n=new Xn(e,i.itemSize,i.offset,i.normalized)}else{const t=Gi(i.type,i.array);n=new(i.isInstancedBufferAttribute?$a:Mn)(t,i.itemSize,i.normalized)}void 0!==i.name&&(n.name=i.name),void 0!==i.usage&&n.setUsage(i.usage),r.setAttribute(e,n)}const o=t.data.morphAttributes;if(o)for(const e in o){const i=o[e],n=[];for(let e=0,r=i.length;e0){const i=new Bc(e);r=new Fc(i),r.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e0){s=new Fc(this.manager),s.setCrossOrigin(this.crossOrigin);for(let e=0,s=t.length;e{let e=null,i=null;return void 0!==t.boundingBox&&(e=(new Qr).fromJSON(t.boundingBox)),void 0!==t.boundingSphere&&(i=(new Nn).fromJSON(t.boundingSphere)),{...t,boundingBox:e,boundingSphere:i}}),n._instanceInfo=t.instanceInfo,n._availableInstanceIds=t._availableInstanceIds,n._availableGeometryIds=t._availableGeometryIds,n._nextIndexStart=t.nextIndexStart,n._nextVertexStart=t.nextVertexStart,n._geometryCount=t.geometryCount,n._maxInstanceCount=t.maxInstanceCount,n._maxVertexCount=t.maxVertexCount,n._maxIndexCount=t.maxIndexCount,n._geometryInitialized=t.geometryInitialized,n._matricesTexture=c(t.matricesTexture.uuid),n._indirectTexture=c(t.indirectTexture.uuid),void 0!==t.colorsTexture&&(n._colorsTexture=c(t.colorsTexture.uuid)),void 0!==t.boundingSphere&&(n.boundingSphere=(new Nn).fromJSON(t.boundingSphere)),void 0!==t.boundingBox&&(n.boundingBox=(new Qr).fromJSON(t.boundingBox));break;case"LOD":n=new pa;break;case"Line":n=new Jo(h(t.geometry),l(t.material));break;case"LineLoop":n=new Go(h(t.geometry),l(t.material));break;case"LineSegments":n=new Zo(h(t.geometry),l(t.material));break;case"PointCloud":case"Points":n=new ih(h(t.geometry),l(t.material));break;case"Sprite":n=new la(l(t.material));break;case"Group":n=new Tr;break;case"Bone":n=new Xa;break;default:n=new Ar}if(n.uuid=t.uuid,void 0!==t.name&&(n.name=t.name),void 0!==t.matrix?(n.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(n.matrixAutoUpdate=t.matrixAutoUpdate),n.matrixAutoUpdate&&n.matrix.decompose(n.position,n.quaternion,n.scale)):(void 0!==t.position&&n.position.fromArray(t.position),void 0!==t.rotation&&n.rotation.fromArray(t.rotation),void 0!==t.quaternion&&n.quaternion.fromArray(t.quaternion),void 0!==t.scale&&n.scale.fromArray(t.scale)),void 0!==t.up&&n.up.fromArray(t.up),void 0!==t.pivot&&(n.pivot=(new Ts).fromArray(t.pivot)),void 0!==t.morphTargetDictionary&&(n.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),void 0!==t.morphTargetInfluences&&(n.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.castShadow&&(n.castShadow=t.castShadow),void 0!==t.receiveShadow&&(n.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(n.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(n.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(n.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(n.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&n.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(n.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(n.visible=t.visible),void 0!==t.frustumCulled&&(n.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(n.renderOrder=t.renderOrder),void 0!==t.static&&(n.static=t.static),void 0!==t.userData&&(n.userData=t.userData),void 0!==t.layers&&(n.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t{!0===Su.has(n)?(s&&s(Su.get(n)),r.manager.itemError(t),r.manager.itemEnd(t)):(e&&e(i),r.manager.itemEnd(t))}):void setTimeout(function(){e&&e(n),r.manager.itemEnd(t)},0);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader,a.signal="function"==typeof AbortSignal.any?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const o=fetch(t,a).then(function(t){return t.blob()}).then(function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(i){Cc.add(`image-bitmap:${t}`,i),e&&e(i),r.manager.itemEnd(t)}).catch(function(e){s&&s(e),Su.set(o,e),Cc.remove(`image-bitmap:${t}`),r.manager.itemError(t),r.manager.itemEnd(t)});Cc.add(`image-bitmap:${t}`,o),r.manager.itemStart(t)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let Au;class Tu{static getContext(){return void 0===Au&&(Au=new(window.AudioContext||window.webkitAudioContext)),Au}static setContext(t){Au=t}}class zu extends Oc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new Nc(this.manager);function a(e){s?s(e):os(e),r.manager.itemError(t)}n.setResponseType("arraybuffer"),n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(t,function(i){try{const s=i.slice(0),n=Tu.getContext(),o=t+"#decode";r.manager.itemStart(o),n.decodeAudioData(s,function(t){e(t),r.manager.itemEnd(o)}).catch(function(t){a(t),r.manager.itemEnd(o)})}catch(t){a(t)}},i,s)}}const Cu=new Qs,Iu=new Qs,Bu=new Qs;class ku{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new iu,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new iu,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(t){const e=this._cache;if(e.focus!==t.focus||e.fov!==t.fov||e.aspect!==t.aspect*this.aspect||e.near!==t.near||e.far!==t.far||e.zoom!==t.zoom||e.eyeSep!==this.eyeSep){e.focus=t.focus,e.fov=t.fov,e.aspect=t.aspect*this.aspect,e.near=t.near,e.far=t.far,e.zoom=t.zoom,e.eyeSep=this.eyeSep,Bu.copy(t.projectionMatrix);const i=e.eyeSep/2,s=i*e.near/e.focus,r=e.near*Math.tan(ys*e.fov*.5)/e.zoom;let n,a;Iu.elements[12]=-i,Cu.elements[12]=i,n=-r*e.aspect+s,a=r*e.aspect+s,Bu.elements[0]=2*e.near/(a-n),Bu.elements[8]=(a+n)/(a-n),this.cameraL.projectionMatrix.copy(Bu),n=-r*e.aspect-s,a=r*e.aspect-s,Bu.elements[0]=2*e.near/(a-n),Bu.elements[8]=(a+n)/(a-n),this.cameraR.projectionMatrix.copy(Bu)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Iu),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(Cu)}}const Ou=-90;class Pu extends Ar{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new iu(Ou,1,t,e);s.layers=this.layers,this.add(s);const r=new iu(Ou,1,t,e);r.layers=this.layers,this.add(r);const n=new iu(Ou,1,t,e);n.layers=this.layers,this.add(n);const a=new iu(Ou,1,t,e);a.layers=this.layers,this.add(a);const o=new iu(Ou,1,t,e);o.layers=this.layers,this.add(o);const h=new iu(Ou,1,t,e);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[i,s,r,n,a,o]=e;for(const t of e)this.remove(t);if(t===Wi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==qi)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,n,a,o,h,l]=this.children,c=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let y=!1;y=!0===t.isWebGLRenderer?t.state.buffers.depth.getReversed():t.reversedDepthBuffer,t.setRenderTarget(i,0,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,r),t.setRenderTarget(i,1,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,n),t.setRenderTarget(i,2,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,a),t.setRenderTarget(i,3,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,o),t.setRenderTarget(i,4,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,h),i.texture.generateMipmaps=m,t.setRenderTarget(i,5,s),y&&!1===t.autoClear&&t.clearDepth(),t.render(e,l),t.setRenderTarget(c,u,d),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class Ru extends iu{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class Nu{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(t){this._document=t,void 0!==t.hidden&&(this._pageVisibilityHandler=Vu.bind(this),t.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(t){return this._timescale=t,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(t){return null!==this._pageVisibilityHandler&&!0===this._document.hidden?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(void 0!==t?t:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}}function Vu(){!1===this._document.hidden&&this.reset()}const Eu=new Ts,Lu=new As,Fu=new Ts,ju=new Ts,Du=new Ts;class Uu extends Ar{constructor(){super(),this.type="AudioListener",this.context=Tu.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new Nu}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(t){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=t,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}updateMatrixWorld(t){super.updateMatrixWorld(t),this._timer.update();const e=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(Eu,Lu,Fu),ju.set(0,0,-1).applyQuaternion(Lu),Du.set(0,1,0).applyQuaternion(Lu),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(Eu.x,t),e.positionY.linearRampToValueAtTime(Eu.y,t),e.positionZ.linearRampToValueAtTime(Eu.z,t),e.forwardX.linearRampToValueAtTime(ju.x,t),e.forwardY.linearRampToValueAtTime(ju.y,t),e.forwardZ.linearRampToValueAtTime(ju.z,t),e.upX.linearRampToValueAtTime(Du.x,t),e.upY.linearRampToValueAtTime(Du.y,t),e.upZ.linearRampToValueAtTime(Du.z,t)}else e.setPosition(Eu.x,Eu.y,Eu.z),e.setOrientation(ju.x,ju.y,ju.z,Du.x,Du.y,Du.z)}}class Wu extends Ar{constructor(t){super(),this.type="Audio",this.listener=t,this.context=t.context,this.gain=this.context.createGain(),this.gain.connect(t.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(t){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=t,this.connect(),this}setMediaElementSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(t),this.connect(),this}setMediaStreamSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(t),this.connect(),this}setBuffer(t){return this.buffer=t,this.sourceType="buffer",this.autoplay&&this.play(),this}play(t=0){if(!0===this.isPlaying)return void as("Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void as("Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+t;const e=this.context.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.onended=this.onEnded.bind(this),e.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=e,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;as("Audio: this Audio has no playback control.")}stop(t=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+t),this.source.onended=null),this.isPlaying=!1,this;as("Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(i,s,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(i[t]!==i[t+e]){a.setValue(i,s);break}}saveOriginalState(){const t=this.binding,e=this.buffer,i=this.valueSize,s=i*this._origIndex;t.getValue(e,s);for(let t=i,r=s;t!==r;++t)e[t]=e[s+t%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let i=t;i=.5)for(let s=0;s!==r;++s)t[e+s]=t[i+s]}_slerp(t,e,i,s){As.slerpFlat(t,e,t,e,t,i,s)}_slerpAdditive(t,e,i,s,r){const n=this._workIndex*r;As.multiplyQuaternionsFlat(t,n,t,e,t,i),As.slerpFlat(t,e,t,e,t,n,s)}_lerp(t,e,i,s,r){const n=1-s;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*n+t[i+a]*s}}_lerpAdditive(t,e,i,s,r){for(let n=0;n!==r;++n){const r=e+n;t[r]=t[r]+t[i+n]*s}}}const $u="\\[\\]\\.:\\/",Qu=new RegExp("["+$u+"]","g"),Ku="[^"+$u+"]",td="[^"+$u.replace("\\.","")+"]",ed=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Ku)+/(WCOD+)?/.source.replace("WCOD",td)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Ku)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Ku)+"$"),id=["material","materials","bones","map"];class sd{constructor(t,e,i){this.path=e,this.parsedPath=i||sd.parseTrackName(e),this.node=sd.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,i){return t&&t.isAnimationObjectGroup?new sd.Composite(t,e,i):new sd(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(Qu,"")}static parseTrackName(t){const e=ed.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const i={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(void 0!==s&&-1!==s){const t=i.nodeName.substring(s+1);-1!==id.indexOf(t)&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=t)}if(null===i.propertyName||0===i.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return i}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const i=t.skeleton.getBoneByName(e);if(void 0!==i)return i}if(t.children){const i=function(t){for(let s=0;s=r){const n=r++,l=t[n];e[l.uuid]=h,t[h]=l,e[o]=n,t[n]=a;for(let t=0,e=s;t!==e;++t){const e=i[t],s=e[n],r=e[h];e[h]=s,e[n]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,i=this._bindings,s=i.length;let r=this.nCachedObjects_,n=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,h=e[o];if(void 0!==h)if(delete e[o],h0&&(e[a.uuid]=h),t[h]=a,t.pop();for(let t=0,e=s;t!==e;++t){const e=i[t];e[h]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const i=this._bindingsIndicesByPath;let s=i[t];const r=this._bindings;if(void 0!==s)return r[s];const n=this._paths,a=this._parsedPaths,o=this._objects,h=o.length,l=this.nCachedObjects_,c=new Array(h);s=r.length,i[t]=s,n.push(t),a.push(e),r.push(c);for(let i=l,s=o.length;i!==s;++i){const s=o[i];c[i]=new sd(s,t,e)}return c}unsubscribe_(t){const e=this._bindingsIndicesByPath,i=e[t];if(void 0!==i){const s=this._paths,r=this._parsedPaths,n=this._bindings,a=n.length-1,o=n[a];e[t[a]]=i,n[i]=o,n.pop(),r[i]=r[a],r.pop(),s[i]=s[a],s.pop()}}}class nd{constructor(t,e,i=null,s=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=i,this.blendMode=s;const r=e.tracks,n=r.length,a=new Array(n),o={endingStart:je,endingEnd:je};for(let t=0;t!==n;++t){const e=r[t].createInterpolant(null);a[t]=e,e.settings&&Object.assign(o,e.settings),e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(n),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,i=!1){if(t.fadeOut(e),this.fadeIn(e),!0===i){const i=this._clip.duration,s=t._clip.duration,r=s/i,n=i/s;t.warp(1,r,e),this.warp(n,1,e)}return this}crossFadeTo(t,e,i=!1){return t.crossFadeFrom(this,e,i)}stopFading(){const t=this._weightInterpolant;return null!==t&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,i){const s=this._mixer,r=s.time,n=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=s._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,h=a.sampleValues;return o[0]=r,o[1]=r+i,h[0]=t/n,h[1]=e/n,this}stopWarping(){const t=this._timeScaleInterpolant;return null!==t&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,i,s){if(!this.enabled)return void this._updateWeight(t);const r=this._startTime;if(null!==r){const s=(t-r)*i;s<0||0===i?e=0:(this._startTime=null,e=i*s)}e*=this._updateTimeScale(t);const n=this._updateTime(e),a=this._updateWeight(t);if(a>0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===qe)for(let i=0,s=t.length;i!==s;++i)t[i].evaluate(n),e[i].accumulateAdditive(a);else for(let i=0,r=t.length;i!==r;++i)t[i].evaluate(n),e[i].accumulate(s,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const i=this._weightInterpolant;if(null!==i){const s=i.evaluate(t)[0];e*=s,t>i.parameterPositions[1]&&(this.stopFading(),0===s&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const i=this._timeScaleInterpolant;if(null!==i){e*=i.evaluate(t)[0],t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,i=this.loop;let s=this.time+t,r=this._loopCount;const n=2202===i;if(0===t)return-1===r||!n||1&~r?s:e-s;if(2200===i){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(s>=e)s=e;else{if(!(s<0)){this.time=s;break t}s=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,n)):this._setEndings(0===this.repetitions,!0,n)),s>=e||s<0){const i=Math.floor(s/e);s-=e*i,r+=Math.abs(i);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=t>0?e:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,n)}else this._setEndings(!1,!1,n);this._loopCount=r,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:i})}}else this._loopCount=r,this.time=s;if(n&&!(1&~r))return e-s}return s}_setEndings(t,e,i){const s=this._interpolantSettings;i?(s.endingStart=De,s.endingEnd=De):(s.endingStart=t?this.zeroSlopeAtStart?De:je:Ue,s.endingEnd=e?this.zeroSlopeAtEnd?De:je:Ue)}_scheduleFading(t,e,i){const s=this._mixer,r=s.time;let n=this._weightInterpolant;null===n&&(n=s._lendControlInterpolant(),this._weightInterpolant=n);const a=n.parameterPositions,o=n.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=i,this}}const ad=new Float32Array(1);class od extends ds{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(t,e){const i=t._localRoot||this._root,s=t._clip.tracks,r=s.length,n=t._propertyBindings,a=t._interpolants,o=i.uuid,h=this._bindingsByRootAndName;let l=h[o];void 0===l&&(l={},h[o]=l);for(let t=0;t!==r;++t){const r=s[t],h=r.name;let c=l[h];if(void 0!==c)++c.referenceCount,n[t]=c;else{if(c=n[t],void 0!==c){null===c._cacheIndex&&(++c.referenceCount,this._addInactiveBinding(c,o,h));continue}const s=e&&e._propertyBindings[t].binding.parsedPath;c=new Gu(sd.create(i,h,s),r.ValueTypeName,r.getValueSize()),++c.referenceCount,this._addInactiveBinding(c,o,h),n[t]=c}a[t].resultBuffer=c.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){const e=(t._localRoot||this._root).uuid,i=t._clip.uuid,s=this._actionsByClip[i];this._bindAction(t,s&&s.knownActions[0]),this._addInactiveAction(t,i,e)}const e=t._propertyBindings;for(let t=0,i=e.length;t!==i;++t){const i=e[t];0===i.useCount++&&(this._lendBinding(i),i.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let t=0,i=e.length;t!==i;++t){const i=e[t];0===--i.useCount&&(i.restoreOriginalState(),this._takeBackBinding(i))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return null!==e&&e=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,i=this._nActiveActions,s=this.time+=t,r=Math.sign(t),n=this._accuIndex^=1;for(let a=0;a!==i;++a){e[a]._update(s,t,r,n)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(n);return this}setTime(t){this.time=0;for(let t=0;t=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Md).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const _d=new Ts,Ad=new Ts,Td=new Ts,zd=new Ts,Cd=new Ts,Id=new Ts,Bd=new Ts;class kd{constructor(t=new Ts,e=new Ts){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){_d.subVectors(t,this.start),Ad.subVectors(this.end,this.start);const i=Ad.dot(Ad);if(0===i)return 0;let s=Ad.dot(_d)/i;return e&&(s=xs(s,0,1)),s}closestPointToPoint(t,e,i){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(t,e=Id,i=Bd){const s=1e-8*1e-8;let r,n;const a=this.start,o=t.start,h=this.end,l=t.end;Td.subVectors(h,a),zd.subVectors(l,o),Cd.subVectors(a,o);const c=Td.dot(Td),u=zd.dot(zd),d=zd.dot(Cd);if(c<=s&&u<=s)return e.copy(a),i.copy(o),e.sub(i),e.dot(e);if(c<=s)r=0,n=d/u,n=xs(n,0,1);else{const t=Td.dot(Cd);if(u<=s)n=0,r=xs(-t/c,0,1);else{const e=Td.dot(zd),i=c*u-e*e;r=0!==i?xs((e*d-t*u)/i,0,1):0,n=(e*r+d)/u,n<0?(n=0,r=xs(-t/c,0,1)):n>1&&(n=1,r=xs((e-t)/c,0,1))}}return e.copy(a).addScaledVector(Td,r),i.copy(o).addScaledVector(zd,n),e.distanceToSquared(i)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Od=new Ts;class Pd extends Ar{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const i=new Wn,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let t=0,e=1,i=32;t1)for(let i=0;i.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{rp.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(rp,e)}}setLength(t,e=.2*t,i=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class hp extends Zo{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],i=new Wn;i.setAttribute("position",new kn(e,3)),i.setAttribute("color",new kn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(i,new Eo({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,i){const s=new Pr,r=this.geometry.attributes.color.array;return s.set(t),s.toArray(r,0),s.toArray(r,3),s.set(e),s.toArray(r,6),s.toArray(r,9),s.set(i),s.toArray(r,12),s.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class lp{constructor(){this.type="ShapePath",this.color=new Pr,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new Gh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(t,e),this}lineTo(t,e){return this.currentPath.lineTo(t,e),this}quadraticCurveTo(t,e,i,s){return this.currentPath.quadraticCurveTo(t,e,i,s),this}bezierCurveTo(t,e,i,s,r,n){return this.currentPath.bezierCurveTo(t,e,i,s,r,n),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t){function e(t,e){const i=e.length;let s=!1;for(let r=i-1,n=0;nNumber.EPSILON){if(h<0&&(i=e[n],o=-o,a=e[r],h=-h),t.ya.y)continue;if(t.y===i.y){if(t.x===i.x)return!0}else{const e=h*(t.x-i.x)-o*(t.y-i.y);if(0===e)return!0;if(e<0)continue;s=!s}}else{if(t.y!==i.y)continue;if(a.x<=t.x&&t.x<=i.x||i.x<=t.x&&t.x<=a.x)return!0}}return s}const i=Al.isClockWise,s=this.subPaths;if(0===s.length)return[];let r,n,a;const o=[];if(1===s.length)return n=s[0],a=new $h,a.curves=n.curves,o.push(a),o;let h=!i(s[0].getPoints());h=t?!h:h;const l=[],c=[];let u,d,p=[],m=0;c[m]=void 0,p[m]=[];for(let e=0,a=s.length;e1){let t=!1,i=0;for(let t=0,e=c.length;t0&&!1===t&&(p=l)}for(let t=0,e=c.length;te?(t.repeat.x=1,t.repeat.y=i/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2):(t.repeat.x=e/i,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0),t}(t,e)}static cover(t,e){return function(t,e){const i=t.image&&t.image.width?t.image.width/t.image.height:1;return i>e?(t.repeat.x=e/i,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0):(t.repeat.x=1,t.repeat.y=i/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2),t}(t,e)}static fill(t){return function(t){return t.repeat.x=1,t.repeat.y=1,t.offset.x=0,t.offset.y=0,t}(t)}static getByteLength(t,e,i,s){return up(t,e,i,s)}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:t}})),"undefined"!=typeof window&&(window.__THREE__?as("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=t);export{it as ACESFilmicToneMapping,w as AddEquation,$ as AddOperation,qe as AdditiveAnimationBlendMode,g as AdditiveBlending,rt as AgXToneMapping,jt as AlphaFormat,ki as AlwaysCompare,U as AlwaysDepth,Si as AlwaysStencilFunc,cu as AmbientLight,nd as AnimationAction,Tc as AnimationClip,Vc as AnimationLoader,od as AnimationMixer,rd as AnimationObjectGroup,dc as AnimationUtils,Bh as ArcCurve,Ru as ArrayCamera,op as ArrowHelper,at as AttachedBindMode,Wu as Audio,Zu as AudioAnalyser,Tu as AudioContext,Uu as AudioListener,zu as AudioLoader,hp as AxesHelper,d as BackSide,He as BasicDepthPacking,o as BasicShadowMap,Vo as BatchedMesh,fc as BezierInterpolant,Xa as Bone,bc as BooleanKeyframeTrack,Sd as Box2,Qr as Box3,ip as Box3Helper,gh as BoxGeometry,ep as BoxHelper,Mn as BufferAttribute,Wn as BufferGeometry,fu as BufferGeometryLoader,Ct as ByteType,Cc as Cache,Qc as Camera,Qd as CameraHelper,uh as CanvasTexture,fh as CapsuleGeometry,Eh as CatmullRomCurve3,et as CineonToneMapping,xh as CircleGeometry,yt as ClampToEdgeWrapping,xd as Clock,Pr as Color,vc as ColorKeyframeTrack,Rs as ColorManagement,Hi as Compatibility,hh as CompressedArrayTexture,lh as CompressedCubeTexture,oh as CompressedTexture,Ec as CompressedTextureLoader,vh as ConeGeometry,F as ConstantAlphaFactor,E as ConstantColorFactor,cp as Controls,Pu as CubeCamera,mh as CubeDepthTexture,lt as CubeReflectionMapping,ct as CubeRefractionMapping,ch as CubeTexture,jc as CubeTextureLoader,pt as CubeUVReflectionMapping,Dh as CubicBezierCurve,Uh as CubicBezierCurve3,mc as CubicInterpolant,r as CullFaceBack,n as CullFaceFront,a as CullFaceFrontBack,s as CullFaceNone,Ch as Curve,Zh as CurvePath,b as CustomBlending,st as CustomToneMapping,bh as CylinderGeometry,vd as Cylindrical,Gs as Data3DTexture,Hs as DataArrayTexture,Ya as DataTexture,Dc as DataTextureLoader,xn as DataUtils,di as DecrementStencilOp,mi as DecrementWrapStencilOp,kc as DefaultLoadingManager,Wt as DepthFormat,qt as DepthStencilFormat,ph as DepthTexture,ot as DetachedBindMode,lu as DirectionalLight,Zd as DirectionalLightHelper,gc as DiscreteInterpolant,Mh as DodecahedronGeometry,p as DoubleSide,O as DstAlphaFactor,R as DstColorFactor,Fi as DynamicCopyUsage,Pi as DynamicDrawUsage,Vi as DynamicReadUsage,zh as EdgesGeometry,Ih as EllipseCurve,Ti as EqualCompare,J as EqualDepth,xi as EqualStencilFunc,ut as EquirectangularReflectionMapping,dt as EquirectangularRefractionMapping,hr as Euler,ds as EventDispatcher,yh as ExternalTexture,Cl as ExtrudeGeometry,Nc as FileLoader,Bn as Float16BufferAttribute,kn as Float32BufferAttribute,Pt as FloatType,Vr as Fog,Nr as FogExp2,ah as FramebufferTexture,u as FrontSide,mo as Frustum,fo as FrustumArray,pd as GLBufferAttribute,Di as GLSL1,Ui as GLSL3,Ci as GreaterCompare,Y as GreaterDepth,Bi as GreaterEqualCompare,X as GreaterEqualDepth,Mi as GreaterEqualStencilFunc,vi as GreaterStencilFunc,qd as GridHelper,Tr as Group,dh as HTMLTexture,Rt as HalfFloatType,qc as HemisphereLight,Wd as HemisphereLightHelper,Bl as IcosahedronGeometry,_u as ImageBitmapLoader,Fc as ImageLoader,Ls as ImageUtils,ui as IncrementStencilOp,pi as IncrementWrapStencilOp,$a as InstancedBufferAttribute,gu as InstancedBufferGeometry,dd as InstancedInterleavedBuffer,no as InstancedMesh,Tn as Int16BufferAttribute,Cn as Int32BufferAttribute,Sn as Int8BufferAttribute,kt as IntType,qn as InterleavedBuffer,Xn as InterleavedBufferAttribute,pc as Interpolant,Fe as InterpolateBezier,Ve as InterpolateDiscrete,Ee as InterpolateLinear,Le as InterpolateSmooth,Yi as InterpolationSamplingMode,Xi as InterpolationSamplingType,yi as InvertStencilOp,li as KeepStencilOp,xc as KeyframeTrack,pa as LOD,kl as LatheGeometry,lr as Layers,Ai as LessCompare,W as LessDepth,zi as LessEqualCompare,q as LessEqualDepth,bi as LessEqualStencilFunc,fi as LessStencilFunc,Wc as Light,pu as LightProbe,Jo as Line,kd as Line3,Eo as LineBasicMaterial,Wh as LineCurve,qh as LineCurve3,oc as LineDashedMaterial,Go as LineLoop,Zo as LineSegments,Mt as LinearFilter,yc as LinearInterpolant,Tt as LinearMipMapLinearFilter,_t as LinearMipMapNearestFilter,At as LinearMipmapLinearFilter,St as LinearMipmapNearestFilter,ii as LinearSRGBColorSpace,K as LinearToneMapping,si as LinearTransfer,Oc as Loader,yu as LoaderUtils,Bc as LoadingManager,Pe as LoopOnce,Ne as LoopPingPong,Re as LoopRepeat,e as MOUSE,Zn as Material,v as MaterialBlending,mu as MaterialLoader,Ss as MathUtils,wd as Matrix2,Is as Matrix3,Qs as Matrix4,A as MaxEquation,Ra as Mesh,Ma as MeshBasicMaterial,rc as MeshDepthMaterial,nc as MeshDistanceMaterial,sc as MeshLambertMaterial,ac as MeshMatcapMaterial,ic as MeshNormalMaterial,tc as MeshPhongMaterial,Kl as MeshPhysicalMaterial,Ql as MeshStandardMaterial,ec as MeshToonMaterial,_ as MinEquation,gt as MirroredRepeatWrapping,G as MixOperation,x as MultiplyBlending,Z as MultiplyOperation,ft as NearestFilter,wt as NearestMipMapLinearFilter,bt as NearestMipMapNearestFilter,vt as NearestMipmapLinearFilter,xt as NearestMipmapNearestFilter,nt as NeutralToneMapping,_i as NeverCompare,D as NeverDepth,gi as NeverStencilFunc,m as NoBlending,ti as NoColorSpace,ni as NoNormalPacking,Q as NoToneMapping,We as NormalAnimationBlendMode,y as NormalBlending,oi as NormalGAPacking,ai as NormalRGPacking,Ii as NotEqualCompare,H as NotEqualDepth,wi as NotEqualStencilFunc,wc as NumberKeyframeTrack,Ar as Object3D,bu as ObjectLoader,Ke as ObjectSpaceNormalMap,Ol as OctahedronGeometry,z as OneFactor,j as OneMinusConstantAlphaFactor,L as OneMinusConstantColorFactor,P as OneMinusDstAlphaFactor,N as OneMinusDstColorFactor,k as OneMinusSrcAlphaFactor,I as OneMinusSrcColorFactor,ou as OrthographicCamera,h as PCFShadowMap,l as PCFSoftShadowMap,Gh as Path,iu as PerspectiveCamera,lo as Plane,Pl as PlaneGeometry,sp as PlaneHelper,au as PointLight,Fd as PointLightHelper,ih as Points,$o as PointsMaterial,Jd as PolarGridHelper,wh as PolyhedronGeometry,Hu as PositionalAudio,sd as PropertyBinding,Gu as PropertyMixer,Jh as QuadraticBezierCurve,Xh as QuadraticBezierCurve3,As as Quaternion,Sc as QuaternionKeyframeTrack,Mc as QuaternionLinearInterpolant,he as R11_EAC_Format,gs as RAD2DEG,ke as RED_GREEN_RGTC2_Format,Ie as RED_RGTC1_Format,t as REVISION,ce as RG11_EAC_Format,Ze as RGBADepthPacking,Ut as RGBAFormat,Gt as RGBAIntegerFormat,Se as RGBA_ASTC_10x10_Format,ve as RGBA_ASTC_10x5_Format,we as RGBA_ASTC_10x6_Format,Me as RGBA_ASTC_10x8_Format,_e as RGBA_ASTC_12x10_Format,Ae as RGBA_ASTC_12x12_Format,de as RGBA_ASTC_4x4_Format,pe as RGBA_ASTC_5x4_Format,me as RGBA_ASTC_5x5_Format,ye as RGBA_ASTC_6x5_Format,ge as RGBA_ASTC_6x6_Format,fe as RGBA_ASTC_8x5_Format,xe as RGBA_ASTC_8x6_Format,be as RGBA_ASTC_8x8_Format,Te as RGBA_BPTC_Format,oe as RGBA_ETC2_EAC_Format,re as RGBA_PVRTC_2BPPV1_Format,se as RGBA_PVRTC_4BPPV1_Format,Qt as RGBA_S3TC_DXT1_Format,Kt as RGBA_S3TC_DXT3_Format,te as RGBA_S3TC_DXT5_Format,Ge as RGBDepthPacking,Dt as RGBFormat,Zt as RGBIntegerFormat,ze as RGB_BPTC_SIGNED_Format,Ce as RGB_BPTC_UNSIGNED_Format,ne as RGB_ETC1_Format,ae as RGB_ETC2_Format,ie as RGB_PVRTC_2BPPV1_Format,ee as RGB_PVRTC_4BPPV1_Format,$t as RGB_S3TC_DXT1_Format,$e as RGDepthPacking,Yt as RGFormat,Ht as RGIntegerFormat,$l as RawShaderMaterial,wa as Ray,yd as Raycaster,uu as RectAreaLight,Jt as RedFormat,Xt as RedIntegerFormat,tt as ReinhardToneMapping,Xs as RenderTarget,hd as RenderTarget3D,mt as RepeatWrapping,ci as ReplaceStencilOp,S as ReverseSubtractEquation,us as ReversedDepthFuncs,Rl as RingGeometry,le as SIGNED_R11_EAC_Format,Oe as SIGNED_RED_GREEN_RGTC2_Format,Be as SIGNED_RED_RGTC1_Format,ue as SIGNED_RG11_EAC_Format,ei as SRGBColorSpace,ri as SRGBTransfer,Er as Scene,Gl as ShaderMaterial,ql as ShadowMaterial,$h as Shape,Nl as ShapeGeometry,lp as ShapePath,Al as ShapeUtils,It as ShortType,Ga as Skeleton,Ed as SkeletonHelper,Ja as SkinnedMesh,js as Source,Nn as Sphere,Vl as SphereGeometry,bd as Spherical,du as SphericalHarmonics3,Yh as SplineCurve,ru as SpotLight,Pd as SpotLightHelper,la as Sprite,Gn as SpriteMaterial,B as SrcAlphaFactor,V as SrcAlphaSaturateFactor,C as SrcColorFactor,Li as StaticCopyUsage,Oi as StaticDrawUsage,Ni as StaticReadUsage,ku as StereoCamera,ji as StreamCopyUsage,Ri as StreamDrawUsage,Ei as StreamReadUsage,_c as StringKeyframeTrack,M as SubtractEquation,f as SubtractiveBlending,i as TOUCH,Qe as TangentSpaceNormalMap,El as TetrahedronGeometry,qs as Texture,Uc as TextureLoader,dp as TextureUtils,Nu as Timer,Ji as TimestampQuery,Ll as TorusGeometry,Fl as TorusKnotGeometry,$r as Triangle,Ye as TriangleFanDrawMode,Xe as TriangleStripDrawMode,Je as TrianglesDrawMode,jl as TubeGeometry,ht as UVMapping,zn as Uint16BufferAttribute,In as Uint32BufferAttribute,_n as Uint8BufferAttribute,An as Uint8ClampedBufferAttribute,ld as Uniform,ud as UniformsGroup,Zl as UniformsUtils,zt as UnsignedByteType,Ft as UnsignedInt101111Type,Et as UnsignedInt248Type,Lt as UnsignedInt5999Type,Ot as UnsignedIntType,Nt as UnsignedShort4444Type,Vt as UnsignedShort5551Type,Bt as UnsignedShortType,c as VSMShadowMap,_s as Vector2,Ts as Vector3,Js as Vector4,Ac as VectorKeyframeTrack,nh as VideoFrameTexture,rh as VideoTexture,$s as WebGL3DRenderTarget,Zs as WebGLArrayRenderTarget,Wi as WebGLCoordinateSystem,Ys as WebGLRenderTarget,qi as WebGPUCoordinateSystem,Cr as WebXRController,Dl as WireframeGeometry,Ue as WrapAroundEnding,je as ZeroCurvatureEnding,T as ZeroFactor,De as ZeroSlopeEnding,hi as ZeroStencilOp,Jl as cloneUniforms,Ki as createCanvasElement,Qi as createElementNS,os as error,up as getByteLength,ss as getConsoleFunction,Hl as getUnlitUniformColorSpace,$i as isTypedArray,rs as log,Xl as mergeUniforms,cs as probeAsync,is as setConsoleFunction,as as warn,hs as warnOnce,ls as yieldToMain}; diff --git a/build/three.webgpu.js b/build/three.webgpu.js index 5a6b59d76f87fa..f17ba08ac453c7 100644 --- a/build/three.webgpu.js +++ b/build/three.webgpu.js @@ -31477,12 +31477,12 @@ class Info { */ createReadbackBuffer( readbackBuffer ) { - const size = this._getAttributeMemorySize( readbackBuffer.attribute ); - this.memoryMap.set( readbackBuffer, { size, type: 'readbackBuffers' } ); + const maxByteLength = readbackBuffer.maxByteLength; + this.memoryMap.set( readbackBuffer, { size: maxByteLength, type: 'readbackBuffers' } ); this.memory.readbackBuffers ++; - this.memory.total += size; - this.memory.readbackBuffersSize += size; + this.memory.total += maxByteLength; + this.memory.readbackBuffersSize += maxByteLength; } @@ -31493,7 +31493,12 @@ class Info { */ destroyReadbackBuffer( readbackBuffer ) { - this.destroyAttribute( readbackBuffer ); + const { size } = this.memoryMap.get( readbackBuffer ); + this.memoryMap.delete( readbackBuffer ); + + this.memory.readbackBuffers --; + this.memory.total -= size; + this.memory.readbackBuffersSize -= size; } @@ -38057,6 +38062,10 @@ class EventNode extends Node { this.updateType = NodeUpdateType.RENDER; + } else if ( eventType === EventNode.FRAME ) { + + this.updateType = NodeUpdateType.FRAME; + } else if ( eventType === EventNode.BEFORE_OBJECT ) { this.updateBeforeType = NodeUpdateType.OBJECT; @@ -38065,6 +38074,10 @@ class EventNode extends Node { this.updateBeforeType = NodeUpdateType.RENDER; + } else if ( eventType === EventNode.BEFORE_FRAME ) { + + this.updateBeforeType = NodeUpdateType.FRAME; + } } @@ -38085,8 +38098,10 @@ class EventNode extends Node { EventNode.OBJECT = 'object'; EventNode.MATERIAL = 'material'; +EventNode.FRAME = 'frame'; EventNode.BEFORE_OBJECT = 'beforeObject'; EventNode.BEFORE_MATERIAL = 'beforeMaterial'; +EventNode.BEFORE_FRAME = 'beforeFrame'; /** * Helper to create an EventNode and add it to the stack. @@ -38117,6 +38132,16 @@ const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback ) */ const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback ); +/** + * Creates an event that triggers a function every frame. + * + * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one. + * + * @param {Function} callback - The callback function. + * @returns {EventNode} + */ +const OnFrameUpdate = ( callback ) => createEvent( EventNode.FRAME, callback ); + /** * Creates an event that triggers a function before an object (Mesh|Sprite) is updated. * @@ -38137,6 +38162,16 @@ const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJEC */ const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback ); +/** + * Creates an event that triggers a function before every frame. + * + * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one. + * + * @param {Function} callback - The callback function. + * @returns {EventNode} + */ +const OnBeforeFrameUpdate = ( callback ) => createEvent( EventNode.BEFORE_FRAME, callback ); + /** * This special type of instanced buffer attribute is intended for compute shaders. * In earlier three.js versions it was only possible to update attribute data @@ -47363,8 +47398,10 @@ var TSL = /*#__PURE__*/Object.freeze({ NodeShaderStage: NodeShaderStage, NodeType: NodeType, NodeUpdateType: NodeUpdateType, + OnBeforeFrameUpdate: OnBeforeFrameUpdate, OnBeforeMaterialUpdate: OnBeforeMaterialUpdate, OnBeforeObjectUpdate: OnBeforeObjectUpdate, + OnFrameUpdate: OnFrameUpdate, OnMaterialUpdate: OnMaterialUpdate, OnObjectUpdate: OnObjectUpdate, PCFShadowFilter: PCFShadowFilter, @@ -57733,65 +57770,6 @@ class CanvasTarget extends EventDispatcher { } -/** - * A readback buffer is used to transfer data from the GPU to the CPU. - * It is primarily used to read back compute shader results. - * - * @augments EventDispatcher - */ -class ReadbackBuffer extends EventDispatcher { - - /** - * Constructs a new readback buffer. - * - * @param {BufferAttribute} attribute - The buffer attribute. - */ - constructor( attribute ) { - - super(); - - /** - * The buffer attribute. - * - * @type {BufferAttribute} - */ - this.attribute = attribute; - - /** - * This flag can be used for type testing. - * - * @type {boolean} - * @readonly - * @default true - */ - this.isReadbackBuffer = true; - - } - - /** - * Releases the mapped buffer data so the GPU buffer can be - * used by the GPU again. - * - * Note: Any `ArrayBuffer` data associated with this readback buffer - * are removed and no longer accessible after calling this method. - */ - release() { - - this.dispatchEvent( { type: 'release' } ); - - } - - /** - * Frees internal resources. - */ - dispose() { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -} - const _scene = /*@__PURE__*/ new Scene(); const _drawingBufferSize = /*@__PURE__*/ new Vector2(); const _screen = /*@__PURE__*/ new Vector4(); @@ -59666,61 +59644,42 @@ class Renderer { * from the GPU to the CPU in context of compute shaders. * * @async - * @param {StorageBufferAttribute|ReadbackBuffer} buffer - The storage buffer attribute. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @param {number} offset - The storage buffer attribute. + * @param {number} count - The offset from which to start reading the + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( buffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { - let readbackBuffer = buffer; + // tally the memory for this readback buffer + if ( target !== null && target.isReadbackBuffer ) { - if ( readbackBuffer.isReadbackBuffer !== true ) { + if ( this.info.memoryMap.has( target ) === false ) { - const attribute = buffer; - const attributeData = this.backend.get( attribute ); + this.info.createReadbackBuffer( target ); - readbackBuffer = attributeData.readbackBuffer; - - if ( readbackBuffer === undefined ) { - - readbackBuffer = new ReadbackBuffer( attribute ); - - const dispose = () => { + const disposeInfo = () => { - attribute.removeEventListener( 'dispose', dispose ); + target.removeEventListener( 'dispose', disposeInfo ); - readbackBuffer.dispose(); - - delete attributeData.readbackBuffer; + this.info.destroyReadbackBuffer( target ); }; - attribute.addEventListener( 'dispose', dispose ); - - attributeData.readbackBuffer = readbackBuffer; + target.addEventListener( 'dispose', disposeInfo ); } } - if ( this.info.memoryMap.has( readbackBuffer ) === false ) { - - this.info.createReadbackBuffer( readbackBuffer ); - - const disposeInfo = () => { - - readbackBuffer.removeEventListener( 'dispose', disposeInfo ); - - this.info.destroyReadbackBuffer( readbackBuffer ); - - }; + if ( offset % 4 !== 0 || ( count > 0 && count % 4 !== 0 ) ) { - readbackBuffer.addEventListener( 'dispose', disposeInfo ); + throw new Error( 'THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.' ); } - readbackBuffer.release(); - - return await this.backend.getArrayBufferAsync( readbackBuffer ); + return await this.backend.getArrayBufferAsync( attribute, target, offset, count ); } @@ -65385,76 +65344,81 @@ class WebGLAttributeUtils { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The readback buffer. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @param {number} offset - The storage buffer attribute. + * @param {number} count - The offset from which to start reading the + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { const backend = this.backend; const { gl } = backend; - const attribute = readbackBuffer.attribute; const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute; - const { bufferGPU } = backend.get( bufferAttribute ); + const attributeInfo = backend.get( bufferAttribute ); + const { bufferGPU } = attributeInfo; - const array = attribute.array; - const byteLength = array.byteLength; - - gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU ); + const byteLength = count === -1 ? attributeInfo.byteLength - offset : count; - const readbackBufferData = backend.get( readbackBuffer ); + // read the data back + let dstBuffer; + if ( target === null ) { - let { writeBuffer } = readbackBufferData; + dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) ); - if ( writeBuffer === undefined ) { + } else if ( target.isReadbackBuffer ) { - writeBuffer = gl.createBuffer(); + if ( target._mapped === true ) { - gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer ); - gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ ); + throw new Error( 'WebGPURenderer: ReadbackBuffer must be released before being used again.' ); - // dispose - - const dispose = () => { - - gl.deleteBuffer( writeBuffer ); + } - backend.delete( readbackBuffer ); + const releaseCallback = () => { - readbackBuffer.removeEventListener( 'dispose', dispose ); + target.buffer = null; + target._mapped = false; + target.removeEventListener( 'release', releaseCallback ); + target.removeEventListener( 'dispose', releaseCallback ); }; - readbackBuffer.addEventListener( 'dispose', dispose ); + target.addEventListener( 'release', releaseCallback ); + target.addEventListener( 'dispose', releaseCallback ); - // register - - readbackBufferData.writeBuffer = writeBuffer; + // WebGL has no concept of a "mapped" data buffer so we create a new buffer, instead. + dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) ); + target.buffer = dstBuffer.buffer; } else { - gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer ); + dstBuffer = new Uint8Array( target ); } - gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength ); + // Ensure the buffer is bound before reading + gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU ); + gl.getBufferSubData( gl.COPY_READ_BUFFER, offset, dstBuffer ); - await backend.utils._clientWaitAsync(); + gl.bindBuffer( gl.COPY_READ_BUFFER, null ); + gl.bindBuffer( gl.COPY_WRITE_BUFFER, null ); - const dstBuffer = new attribute.array.constructor( array.length ); + // return the appropriate type + if ( target && target.isReadbackBuffer ) { - // Ensure the buffer is bound before reading - gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer ); + return target; - gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer ); + } else { - gl.bindBuffer( gl.COPY_READ_BUFFER, null ); - gl.bindBuffer( gl.COPY_WRITE_BUFFER, null ); + return dstBuffer.buffer; - return dstBuffer; + } } @@ -69581,15 +69545,20 @@ class WebGLBackend extends Backend { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The readback buffer. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @param {number} offset - The storage buffer attribute. + * @param {number} count - The offset from which to start reading the + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { - return await this.attributeUtils.getArrayBufferAsync( readbackBuffer ); + return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count ); } @@ -73581,7 +73550,9 @@ class WebGPUTextureUtils { await readBuffer.mapAsync( GPUMapMode.READ ); - const buffer = readBuffer.getMappedRange(); + const buffer = readBuffer.getMappedRange().slice(); + + readBuffer.destroy(); return new typedArrayType( buffer ); @@ -77884,82 +77855,137 @@ class WebGPUAttributeUtils { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The storage buffer attribute. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {number} count - The offset from which to start reading the + * @param {number} offset - The storage buffer attribute. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { const backend = this.backend; const device = backend.device; - const attribute = readbackBuffer.attribute; const data = backend.get( this._getBufferAttribute( attribute ) ); const bufferGPU = data.buffer; - const size = bufferGPU.size; + const byteLength = count === -1 ? bufferGPU.size - offset : count; - const readbackBufferData = backend.get( readbackBuffer ); + let readBufferGPU; + if ( target !== null && target.isReadbackBuffer ) { - let { readBufferGPU } = readbackBufferData; + const readbackInfo = backend.get( target ); - if ( readBufferGPU === undefined ) { + if ( target._mapped === true ) { - readBufferGPU = device.createBuffer( { - label: `${ attribute.name }_readback`, - size, - usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ - } ); + throw new Error( 'WebGPURenderer: ReadbackBuffer must be released before being used again.' ); - // release / dispose + } - const release = () => { + target._mapped = true; - readBufferGPU.unmap(); + // initialize the GPU-side read copy buffer if it is not present + if ( readbackInfo.readBufferGPU === undefined ) { - }; + readBufferGPU = device.createBuffer( { + label: `${ target.name }_readback`, + size: target.maxByteLength, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ + } ); - const dispose = () => { + // release / dispose + const releaseCallback = () => { - readBufferGPU.destroy(); + target.buffer = null; + target._mapped = false; - backend.delete( readbackBuffer ); + readBufferGPU.unmap(); - readbackBuffer.removeEventListener( 'release', release ); - readbackBuffer.removeEventListener( 'dispose', dispose ); + }; - }; + const disposeCallback = () => { + + target.buffer = null; + target._mapped = false; + + readBufferGPU.destroy(); + + backend.delete( target ); + + target.removeEventListener( 'release', releaseCallback ); + target.removeEventListener( 'dispose', disposeCallback ); + + }; + + target.addEventListener( 'release', releaseCallback ); + target.addEventListener( 'dispose', disposeCallback ); + + // register + readbackInfo.readBufferGPU = readBufferGPU; + + } else { - readbackBuffer.addEventListener( 'release', release ); - readbackBuffer.addEventListener( 'dispose', dispose ); + readBufferGPU = readbackInfo.readBufferGPU; - // register + } - readbackBufferData.readBufferGPU = readBufferGPU; + } else { + + // create a new temp buffer for array buffers otherwise + readBufferGPU = device.createBuffer( { + label: `${ attribute.name }_readback`, + size: byteLength, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ + } ); } + // copy the data const cmdEncoder = device.createCommandEncoder( { label: `readback_encoder_${ attribute.name }` } ); cmdEncoder.copyBufferToBuffer( bufferGPU, - 0, + offset, readBufferGPU, 0, - size + byteLength, ); const gpuCommands = cmdEncoder.finish(); device.queue.submit( [ gpuCommands ] ); - await readBufferGPU.mapAsync( GPUMapMode.READ ); + // map the data to the CPU + await readBufferGPU.mapAsync( GPUMapMode.READ, 0, byteLength ); + + if ( target === null ) { + + // return a new array buffer and clean up the gpu handles + const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength ); + const result = arrayBuffer.slice(); + readBufferGPU.destroy(); + return result; + + } else if ( target.isReadbackBuffer ) { + + // assign the data to the read back handle + target.buffer = readBufferGPU.getMappedRange( 0, byteLength ); + return target; + + } else { - const arrayBuffer = readBufferGPU.getMappedRange(); + // copy the data into the target array buffer + const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength ); + new Uint8Array( target ).set( new Uint8Array( arrayBuffer ) ); + readBufferGPU.destroy(); + return target; - return arrayBuffer; + } } @@ -80155,15 +80181,20 @@ class WebGPUBackend extends Backend { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The readback buffer. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {number} count - The offset from which to start reading the + * @param {number} offset - The storage buffer attribute. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { - return await this.attributeUtils.getArrayBufferAsync( readbackBuffer ); + return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count ); } @@ -81438,20 +81469,17 @@ class WebGPUBackend extends Backend { for ( let i = 0; i < drawCount; i ++ ) { - const count = 1; - const firstInstance = i; - if ( hasIndex === true ) { - passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance ); + passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i ); } else { - passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance ); + passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i ); } - info.update( object, counts[ i ], count ); + info.update( object, counts[ i ], 1 ); } @@ -83018,6 +83046,81 @@ class PostProcessing extends RenderPipeline { } +/** + * A readback buffer is used to transfer data from the GPU to the CPU. + * It is primarily used to read back compute shader results. + * + * @augments EventDispatcher + */ +class ReadbackBuffer extends EventDispatcher { + + /** + * Constructs a new readback buffer. + * + * @param {number} maxByteLength - The maximum size of the buffer to be read back. + */ + constructor( maxByteLength ) { + + super(); + + /** + * Name used for debugging purposes. + * + * @type {string} + */ + this.name = ''; + + /** + * The mapped, read back array buffer. + * + * @type {ArrayBuffer|null} + */ + this.buffer = null; + + /** + * The maximum size of the buffer to be read back. + * + * @type {number} + */ + this.maxByteLength = maxByteLength; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isReadbackBuffer = true; + + this._mapped = false; + + } + + /** + * Releases the mapped buffer data so the GPU buffer can be + * used by the GPU again. + * + * Note: Any `ArrayBuffer` data associated with this readback buffer + * are removed and no longer accessible after calling this method. + */ + release() { + + this.dispatchEvent( { type: 'release' } ); + + } + + /** + * Frees internal resources. + */ + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + /** * This special type of texture is intended for compute shaders. * It can be used to compute the data of a texture with a compute shader. @@ -83689,6 +83792,24 @@ class NodeObjectLoader extends ObjectLoader { } + /** + * Async version of {@link NodeObjectLoader#parse}. + * + * @param {Object} json - The JSON definition + * @return {Promise} A Promise that resolves with the parsed 3D object. + */ + async parseAsync( json ) { + + this._nodesJSON = json.nodes; + + const data = await super.parseAsync( json ); + + this._nodesJSON = null; // dispose + + return data; + + } + /** * Parses the node objects from the given JSON and textures. * diff --git a/build/three.webgpu.min.js b/build/three.webgpu.min.js index 07c0799a97f8cf..2975941d505376 100644 --- a/build/three.webgpu.min.js +++ b/build/three.webgpu.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2026 Three.js Authors * SPDX-License-Identifier: MIT */ -import{Color as e,Vector2 as t,Vector3 as r,Vector4 as s,Matrix2 as i,Matrix3 as n,Matrix4 as a,error as o,EventDispatcher as u,MathUtils as l,warn as d,WebGLCoordinateSystem as c,WebGPUCoordinateSystem as h,ColorManagement as p,SRGBTransfer as g,NoToneMapping as m,StaticDrawUsage as f,InterleavedBufferAttribute as y,InterleavedBuffer as b,DynamicDrawUsage as x,NoColorSpace as T,log as _,warnOnce as v,Texture as N,UnsignedIntType as S,IntType as R,Compatibility as E,LessCompare as A,LessEqualCompare as w,GreaterCompare as C,GreaterEqualCompare as M,NearestFilter as B,Sphere as L,BackSide as F,DoubleSide as P,CubeTexture as D,CubeReflectionMapping as U,CubeRefractionMapping as I,TangentSpaceNormalMap as O,NoNormalPacking as V,NormalRGPacking as k,NormalGAPacking as G,ObjectSpaceNormalMap as z,RGFormat as $,RED_GREEN_RGTC2_Format as W,RG11_EAC_Format as H,InstancedBufferAttribute as q,InstancedInterleavedBuffer as j,DataArrayTexture as X,FloatType as K,FramebufferTexture as Q,LinearMipmapLinearFilter as Y,DepthTexture as Z,Material as J,LineBasicMaterial as ee,LineDashedMaterial as te,NoBlending as re,MeshNormalMaterial as se,SRGBColorSpace as ie,RenderTarget as ne,BoxGeometry as ae,Mesh as oe,Scene as ue,LinearFilter as le,CubeCamera as de,EquirectangularReflectionMapping as ce,EquirectangularRefractionMapping as he,AddOperation as pe,MixOperation as ge,MultiplyOperation as me,MeshBasicMaterial as fe,MeshLambertMaterial as ye,MeshPhongMaterial as be,DataTexture as xe,HalfFloatType as Te,ClampToEdgeWrapping as _e,BufferGeometry as ve,OrthographicCamera as Ne,PerspectiveCamera as Se,LinearSRGBColorSpace as Re,RGBAFormat as Ee,CubeUVReflectionMapping as Ae,BufferAttribute as we,MeshStandardMaterial as Ce,MeshPhysicalMaterial as Me,MeshToonMaterial as Be,MeshMatcapMaterial as Le,SpriteMaterial as Fe,PointsMaterial as Pe,ShadowMaterial as De,Uint32BufferAttribute as Ue,Uint16BufferAttribute as Ie,ByteType as Oe,UnsignedByteType as Ve,ShortType as ke,UnsignedShortType as Ge,AlphaFormat as ze,RedFormat as $e,RedIntegerFormat as We,DepthFormat as He,DepthStencilFormat as qe,RGIntegerFormat as je,RGBFormat as Xe,RGBIntegerFormat as Ke,UnsignedShort4444Type as Qe,UnsignedShort5551Type as Ye,UnsignedInt248Type as Ze,UnsignedInt5999Type as Je,UnsignedInt101111Type as et,NormalBlending as tt,SrcAlphaFactor as rt,OneMinusSrcAlphaFactor as st,AddEquation as it,MaterialBlending as nt,Object3D as at,LinearMipMapLinearFilter as ot,Plane as ut,Float32BufferAttribute as lt,UVMapping as dt,PCFShadowMap as ct,PCFSoftShadowMap as ht,VSMShadowMap as pt,BasicShadowMap as gt,CubeDepthTexture as mt,SphereGeometry as ft,LinearMipmapNearestFilter as yt,NearestMipmapLinearFilter as bt,Float16BufferAttribute as xt,yieldToMain as Tt,REVISION as _t,ArrayCamera as vt,PlaneGeometry as Nt,FrontSide as St,CustomBlending as Rt,ZeroFactor as Et,CylinderGeometry as At,Quaternion as wt,WebXRController as Ct,RAD2DEG as Mt,FrustumArray as Bt,Frustum as Lt,RGBAIntegerFormat as Ft,TimestampQuery as Pt,createCanvasElement as Dt,ReverseSubtractEquation as Ut,SubtractEquation as It,OneMinusDstAlphaFactor as Ot,OneMinusDstColorFactor as Vt,OneMinusSrcColorFactor as kt,DstAlphaFactor as Gt,DstColorFactor as zt,SrcAlphaSaturateFactor as $t,SrcColorFactor as Wt,OneFactor as Ht,CullFaceNone as qt,CullFaceBack as jt,CullFaceFront as Xt,MultiplyBlending as Kt,SubtractiveBlending as Qt,AdditiveBlending as Yt,NotEqualDepth as Zt,GreaterDepth as Jt,GreaterEqualDepth as er,EqualDepth as tr,LessEqualDepth as rr,LessDepth as sr,AlwaysDepth as ir,NeverDepth as nr,ReversedDepthFuncs as ar,RGB_S3TC_DXT1_Format as or,RGBA_S3TC_DXT1_Format as ur,RGBA_S3TC_DXT3_Format as lr,RGBA_S3TC_DXT5_Format as dr,RGB_PVRTC_4BPPV1_Format as cr,RGB_PVRTC_2BPPV1_Format as hr,RGBA_PVRTC_4BPPV1_Format as pr,RGBA_PVRTC_2BPPV1_Format as gr,RGB_ETC1_Format as mr,RGB_ETC2_Format as fr,RGBA_ETC2_EAC_Format as yr,R11_EAC_Format as br,SIGNED_R11_EAC_Format as xr,SIGNED_RG11_EAC_Format as Tr,RGBA_ASTC_4x4_Format as _r,RGBA_ASTC_5x4_Format as vr,RGBA_ASTC_5x5_Format as Nr,RGBA_ASTC_6x5_Format as Sr,RGBA_ASTC_6x6_Format as Rr,RGBA_ASTC_8x5_Format as Er,RGBA_ASTC_8x6_Format as Ar,RGBA_ASTC_8x8_Format as wr,RGBA_ASTC_10x5_Format as Cr,RGBA_ASTC_10x6_Format as Mr,RGBA_ASTC_10x8_Format as Br,RGBA_ASTC_10x10_Format as Lr,RGBA_ASTC_12x10_Format as Fr,RGBA_ASTC_12x12_Format as Pr,RGBA_BPTC_Format as Dr,RED_RGTC1_Format as Ur,SIGNED_RED_RGTC1_Format as Ir,SIGNED_RED_GREEN_RGTC2_Format as Or,MirroredRepeatWrapping as Vr,RepeatWrapping as kr,NearestMipmapNearestFilter as Gr,NotEqualCompare as zr,EqualCompare as $r,AlwaysCompare as Wr,NeverCompare as Hr,LinearTransfer as qr,getByteLength as jr,isTypedArray as Xr,NotEqualStencilFunc as Kr,GreaterStencilFunc as Qr,GreaterEqualStencilFunc as Yr,EqualStencilFunc as Zr,LessEqualStencilFunc as Jr,LessStencilFunc as es,AlwaysStencilFunc as ts,NeverStencilFunc as rs,DecrementWrapStencilOp as ss,IncrementWrapStencilOp as is,DecrementStencilOp as ns,IncrementStencilOp as as,InvertStencilOp as os,ReplaceStencilOp as us,ZeroStencilOp as ls,KeepStencilOp as ds,MaxEquation as cs,MinEquation as hs,SpotLight as ps,PointLight as gs,DirectionalLight as ms,RectAreaLight as fs,AmbientLight as ys,HemisphereLight as bs,LightProbe as xs,LinearToneMapping as Ts,ReinhardToneMapping as _s,CineonToneMapping as vs,ACESFilmicToneMapping as Ns,AgXToneMapping as Ss,NeutralToneMapping as Rs,Group as Es,Loader as As,FileLoader as ws,MaterialLoader as Cs,ObjectLoader as Ms}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,BezierInterpolant,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,ConstantAlphaFactor,ConstantColorFactor,Controls,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CustomToneMapping,Cylindrical,Data3DTexture,DataTextureLoader,DataUtils,DefaultLoadingManager,DetachedBindMode,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,Euler,ExternalTexture,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HTMLTexture,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,InterpolateBezier,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,KeyframeTrack,LOD,LatheGeometry,Layers,Light,Line,Line3,LineCurve,LineCurve3,LineLoop,LineSegments,LinearInterpolant,LinearMipMapNearestFilter,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,MeshDepthMaterial,MeshDistanceMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NormalAnimationBlendMode,NumberKeyframeTrack,OctahedronGeometry,OneMinusConstantAlphaFactor,OneMinusConstantColorFactor,Path,PlaneHelper,PointLightHelper,Points,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBADepthPacking,RGBDepthPacking,RGB_BPTC_SIGNED_Format,RGB_BPTC_UNSIGNED_Format,RGDepthPacking,RawShaderMaterial,Ray,Raycaster,RenderTarget3D,RingGeometry,ShaderMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Spherical,SphericalHarmonics3,SplineCurve,SpotLightHelper,Sprite,StaticCopyUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,Timer,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding,getConsoleFunction,setConsoleFunction}from"./three.core.min.js";const Bs=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],Ls=new WeakMap,Fs=new WeakMap,Ps=new WeakMap;class Ds{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Bs,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:r,object:s}=e;if(t={geometryId:r.id,worldMatrix:s.matrixWorld.clone()},s.center&&(t.center=s.center.clone()),s.morphTargetInfluences&&(t.morphTargetInfluences=s.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),e.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={id:s.id,version:s.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=Ps.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Ps.set(e,t)),t}getMaterialData(e){let t=Fs.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:s.version}:t[r]=s.clone():t[r]=s)}Fs.set(e,t)}return t}equals(e,t,r){const{object:s,material:i,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(s.matrixWorld))return a.worldMatrix.copy(s.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==r){o._renderId=r;for(const e in o){const t=o[e],r=i[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),o._equal=!1,!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,o._equal=!1,!1}else if(t!==r)return o[e]=r,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:r}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==r)return a.bufferWidth=t,a.bufferHeight=r,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==r){u._renderId=r;const e=n.attributes,t=u.attributes;let s=0,i=0;for(const t in e)s++;for(const r in t){i++;const s=t[r],n=e[r];if(void 0===n)return delete t[r],u._equal=!1,!1;if(s.id!==n.id||s.version!==n.version)return s.id=n.id,s.version=n.version,u._equal=!1,!1}if(i!==s)return u.attributes=this.getAttributesData(e),u._equal=!1,!1;const a=n.index,o=u.indexId,l=u.indexVersion,d=a?a.id:null,c=a?a.version:null;if(o!==d||l!==c)return u.indexId=d,u.indexVersion=c,u._equal=!1,!1;if(u.drawRange.start!==n.drawRange.start||u.drawRange.count!==n.drawRange.count)return u.drawRange.start=n.drawRange.start,u.drawRange.count=n.drawRange.count,u._equal=!1,!1;u._equal=!0}else if(!1===u._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t{const r=e.match(t);if(!r)return null;const s=r[1]||r[2]||"",i=r[3].split("?")[0],n=parseInt(r[4],10),a=parseInt(r[5],10);return{fn:s,file:i.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Us.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Os(e,t=0){let r=3735928559^t,s=1103547991^t;if(Array.isArray(e))for(let t,i=0;i>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const Vs=e=>Os(e),ks=e=>Os(e),Gs=(...e)=>Os(e),zs=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),$s=new WeakMap;function Ws(e){return zs.get(e)}function Hs(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function qs(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function js(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Xs(e){return/float|int|uint/.test(e)?4:/vec2/.test(e)?8:/vec3/.test(e)||/vec4/.test(e)?16:/mat2/.test(e)?8:/mat3/.test(e)||/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Ks(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 Qs(o,...u){const l=o?o.slice(-4):void 0;return 1===u.length&&("vec2"===l?u=[u[0],u[0]]:"vec3"===l?u=[u[0],u[0],u[0]]:"vec4"===l&&(u=[u[0],u[0],u[0],u[0]])),"color"===o?new e(...u):"vec2"===l?new t(...u):"vec3"===l?new r(...u):"vec4"===l?new s(...u):"mat2"===l?new i(...u):"mat3"===l?new n(...u):"mat4"===l?new a(...u):"bool"===o?u[0]||!1:"float"===o||"int"===o||"uint"===o?u[0]||0:"string"===o?u[0]||"":"ArrayBuffer"===o?Js(u[0]):null}function Ys(e){let t=$s.get(e);return void 0===t&&(t={},$s.set(e,t)),t}function Zs(e){let t="";const r=new Uint8Array(e);for(let e=0;ee.charCodeAt(0)).buffer}var ei=Object.freeze({__proto__:null,arrayBufferToBase64:Zs,base64ToArrayBuffer:Js,getAlignmentFromType:Xs,getDataFromObject:Ys,getLengthFromType:qs,getMemoryLengthFromType:js,getTypeFromLength:Ws,getTypedArrayFromType:Hs,getValueFromType:Qs,getValueType:Ks,hash:Gs,hashArray:ks,hashString:Vs});const ti={VERTEX:"vertex",FRAGMENT:"fragment"},ri={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},si={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},ii={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ni=["fragment","vertex"],ai=["setup","analyze","generate"],oi=[...ni,"compute"],ui=["x","y","z","w"],li={analyze:"setup",generate:"analyze"};let di=0;class ci extends u{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ri.NONE,this.updateBeforeType=ri.NONE,this.updateAfterType=ri.NONE,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=di++,this.stackTrace=null,!0===ci.captureStackTrace&&(this.stackTrace=new Is)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=l.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,ri.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ri.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ri.OBJECT)}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 r of Object.getOwnPropertyNames(this)){const s=this[r];if(!0!==r.startsWith("_")&&!e.has(s))if(!0===Array.isArray(s))for(let e=0;e0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}ci.captureStackTrace=!1;class hi extends ci{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 pi extends ci{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class gi extends ci{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 r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class mi extends gi{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,r)=>t+e.getTypeLength(r.getNodeType(e)),0))}generate(e,t){const r=this.getNodeType(e),s=e.getTypeLength(r),i=this.nodes,n=e.getComponentType(r),a=[];let u=0;for(const t of i){if(u>=s){o(`TSL: Length of parameters exceeds maximum length of function '${r}()' type.`,this.stackTrace);break}let i,l=t.getNodeType(e),d=e.getTypeLength(l);u+d>s&&(o(`TSL: Length of '${r}()' data exceeds maximum length of output type.`,this.stackTrace),d=s-u,l=e.getTypeFromLength(d)),u+=d,i=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(d,n);i=e.format(i,l,t)}a.push(i)}const l=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(l,r,t)}}const fi=ui.join("");class yi extends ci{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(ui.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 r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===fi.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class bi extends gi{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");ci.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Si?Si.assign(this,...e):o("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Is),this;{const t=Ri.get("assign");return this.addToStack(t(...e))}},ci.prototype.toVarIntent=function(){return this},ci.prototype.get=function(e){return new Ni(this,e)};const wi={};function Ci(e,t,r){wi[e]=wi[t]=wi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new yi(this,e),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();ci.prototype["set"+s]=ci.prototype["set"+i]=ci.prototype["set"+n]=function(t){const r=Ai(e);return new bi(this,r,tn(t))},ci.prototype["flip"+s]=ci.prototype["flip"+i]=ci.prototype["flip"+n]=function(){const t=Ai(e);return new xi(this,t)}}const Mi=["x","y","z","w"],Bi=["r","g","b","a"],Li=["s","t","p","q"];for(let e=0;e<4;e++){let t=Mi[e],r=Bi[e],s=Li[e];Ci(t,r,s);for(let i=0;i<4;i++){t=Mi[e]+Mi[i],r=Bi[e]+Bi[i],s=Li[e]+Li[i],Ci(t,r,s);for(let n=0;n<4;n++){t=Mi[e]+Mi[i]+Mi[n],r=Bi[e]+Bi[i]+Bi[n],s=Li[e]+Li[i]+Li[n],Ci(t,r,s);for(let a=0;a<4;a++)t=Mi[e]+Mi[i]+Mi[n]+Mi[a],r=Bi[e]+Bi[i]+Bi[n]+Bi[a],s=Li[e]+Li[i]+Li[n]+Li[a],Ci(t,r,s)}}}for(let e=0;e<32;e++)wi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new hi(this,new vi(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};Object.defineProperties(ci.prototype,wi);const Fi=new WeakMap,Pi=function(e,t=null){for(const r in e)e[r]=tn(e[r],t);return e},Di=function(e,t=null){const r=e.length;for(let s=0;su?(o(`TSL: "${r}" parameter length exceeds limit.`,new Is),t.slice(0,u)):t}return null===t?n=(...t)=>i(new e(...nn(d(t)))):null!==r?(r=tn(r),n=(...s)=>i(new e(t,...nn(d(s)),r))):n=(...r)=>i(new e(t,...nn(d(r)))),n.setParameterLength=(...e)=>(1===e.length?a=u=e[0]:2===e.length&&([a,u]=e),n),n.setName=e=>(l=e,n),n},Ii=function(e,...t){return new e(...nn(t))};class Oi extends ci{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:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let u=null;if(t.layout){let s=Fi.get(e.constructor);void 0===s&&(s=new WeakMap,Fi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=tn(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i);const n=r?function(e){let t;sn(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(r):null;u=tn(i.call(n))}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return sn(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield tn(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof ci&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=tn(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,o=n||a.length>1?a(i,s):a(s);u=tn(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(s[n]=u),u}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return e.fnCall=o,r}}class Vi extends ci{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 Oi(this,e)}setup(){return this.call()}}const ki=[!1,!0],Gi=[0,1,2,3],zi=[-1,-2],$i=[.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],Wi=new Map;for(const e of ki)Wi.set(e,new vi(e));const Hi=new Map;for(const e of Gi)Hi.set(e,new vi(e,"uint"));const qi=new Map([...Hi].map(e=>new vi(e.value,"int")));for(const e of zi)qi.set(e,new vi(e,"int"));const ji=new Map([...qi].map(e=>new vi(e.value)));for(const e of $i)ji.set(e,new vi(e));for(const e of $i)ji.set(-e,new vi(-e));const Xi={bool:Wi,uint:Hi,ints:qi,float:ji},Ki=new Map([...Wi,...ji]),Qi=(e,t)=>Ki.has(e)?Ki.get(e):!0===e.isNode?e:new vi(e,t),Yi=function(e,t=null){return(...r)=>{for(const t of r)if(void 0===t)return o(`TSL: Invalid parameter for the type "${e}".`,new Is),new vi(0,e);if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(r=[Qs(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return rn(t.get(r[0]));if(1===r.length){const t=Qi(r[0],e);return t.nodeType===e?rn(t):rn(new pi(t,e))}const s=r.map(e=>Qi(e));return rn(new mi(s,e))}};function Zi(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}const Ji=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function en(e,t){return new Vi(e,t)}const tn=(e,t=null)=>function(e,t=null){const r=Ks(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?tn(Qi(e,t)):"shader"===r?e.isFn?e:cn(e):e}(e,t),rn=(e,t=null)=>tn(e,t).toVarIntent(),sn=(e,t=null)=>new Pi(e,t),nn=(e,t=null)=>new Di(e,t),an=(e,t=null,r=null,s=null)=>new Ui(e,t,r,s),on=(e,...t)=>new Ii(e,...t),un=(e,t=null,r=null,s={})=>new Ui(e,t,r,{...s,intent:!0});let ln=0;class dn extends ci{constructor(e,t=null){super();let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:o("TSL: Invalid layout type.",new Is),t=null)),this.shaderNode=new en(e,r),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+ln++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}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 o('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function cn(e,t=null){const r=new dn(e,t);return new Proxy(()=>{},{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const hn=e=>{Si=e},pn=()=>Si,gn=(...e)=>Si.If(...e);function mn(e){return Si&&Si.addToStack(e),e}Ei("toStack",mn);const fn=new Yi("color"),yn=new Yi("float",Xi.float),bn=new Yi("int",Xi.ints),xn=new Yi("uint",Xi.uint),Tn=new Yi("bool",Xi.bool),_n=new Yi("vec2"),vn=new Yi("ivec2"),Nn=new Yi("uvec2"),Sn=new Yi("bvec2"),Rn=new Yi("vec3"),En=new Yi("ivec3"),An=new Yi("uvec3"),wn=new Yi("bvec3"),Cn=new Yi("vec4"),Mn=new Yi("ivec4"),Bn=new Yi("uvec4"),Ln=new Yi("bvec4"),Fn=new Yi("mat2"),Pn=new Yi("mat3"),Dn=new Yi("mat4");Ei("toColor",fn),Ei("toFloat",yn),Ei("toInt",bn),Ei("toUint",xn),Ei("toBool",Tn),Ei("toVec2",_n),Ei("toIVec2",vn),Ei("toUVec2",Nn),Ei("toBVec2",Sn),Ei("toVec3",Rn),Ei("toIVec3",En),Ei("toUVec3",An),Ei("toBVec3",wn),Ei("toVec4",Cn),Ei("toIVec4",Mn),Ei("toUVec4",Bn),Ei("toBVec4",Ln),Ei("toMat2",Fn),Ei("toMat3",Pn),Ei("toMat4",Dn);const Un=an(hi).setParameterLength(2),In=(e,t)=>new pi(tn(e),t);Ei("element",Un),Ei("convert",In);Ei("append",e=>(d("TSL: .append() has been renamed to .toStack().",new Is),mn(e)));class On extends ci{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1){super(e),this.name=t,this.varying=r,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Vs(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Vn=(e,t)=>new On(e,t),kn=(e,t)=>new On(e,t,!0),Gn=on(On,"vec4","DiffuseColor"),zn=on(On,"vec3","DiffuseContribution"),$n=on(On,"vec3","EmissiveColor"),Wn=on(On,"float","Roughness"),Hn=on(On,"float","Metalness"),qn=on(On,"float","Clearcoat"),jn=on(On,"float","ClearcoatRoughness"),Xn=on(On,"vec3","Sheen"),Kn=on(On,"float","SheenRoughness"),Qn=on(On,"float","Iridescence"),Yn=on(On,"float","IridescenceIOR"),Zn=on(On,"float","IridescenceThickness"),Jn=on(On,"float","AlphaT"),ea=on(On,"float","Anisotropy"),ta=on(On,"vec3","AnisotropyT"),ra=on(On,"vec3","AnisotropyB"),sa=on(On,"color","SpecularColor"),ia=on(On,"color","SpecularColorBlended"),na=on(On,"float","SpecularF90"),aa=on(On,"float","Shininess"),oa=on(On,"vec4","Output"),ua=on(On,"float","dashSize"),la=on(On,"float","gapSize"),da=on(On,"float","pointWidth"),ca=on(On,"float","IOR"),ha=on(On,"float","Transmission"),pa=on(On,"float","Thickness"),ga=on(On,"float","AttenuationDistance"),ma=on(On,"color","AttenuationColor"),fa=on(On,"float","Dispersion");class ya extends ci{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1,s=null){super("string"),this.name=e,this.shared=t,this.order=r,this.updateType=s,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 ba=(e,t=1,r=null)=>new ya(e,!1,t,r),xa=(e,t=0,r=null)=>new ya(e,!0,t,r),Ta=xa("frame",0,ri.FRAME),_a=xa("render",0,ri.RENDER),va=ba("object",1,ri.OBJECT);class Na extends Ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=va}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const r=e(t,this);void 0!==r&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const Sa=(e,t)=>{const r=Ji(t||e);if(r===e&&(e=Qs(r)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new Na(e,r)};class Ra extends gi{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,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 Ea=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Ra(null,r.length,r)}else{const r=e[0],s=e[1];t=new Ra(r,s)}return tn(t)};Ei("toArray",(e,t)=>Ea(Array(t).fill(e)));class Aa extends gi{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 r=e.getTypeLength(t.node.getNodeType(e));return ui.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getDataFromNode(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t{const s=r.type;let i;return i="pointer"===s?"&"+t.build(e):t.build(e,s),i};if(Array.isArray(i)){if(i.length>s.length)o("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=s.length;else if(i.length(t=t.length>1||t[0]&&!0===t[0].isNode?nn(t):sn(t[0]),new Ca(tn(e),t));Ei("call",Ma);const Ba={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class La extends gi{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new La(e,t,r);for(let t=0;t>"===r||"<<"===r)return e.getIntegerType(n);if("!"===r||"&&"===r||"||"===r||"^^"===r)return"bool";if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),l=i?i.build(e,o):null,d=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===c;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${r} ${l} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${l} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(d)return e.format(`${d}( ${u}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${l}`,n,t);{let i=`( ${u} ${r} ${l} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return d?e.format(`${d}( ${u}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${r} ${u}`,n,t):e.format(`${u} ${r} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Fa=un(La,"+").setParameterLength(2,1/0).setName("add"),Pa=un(La,"-").setParameterLength(2,1/0).setName("sub"),Da=un(La,"*").setParameterLength(2,1/0).setName("mul"),Ua=un(La,"/").setParameterLength(2,1/0).setName("div"),Ia=un(La,"%").setParameterLength(2).setName("mod"),Oa=un(La,"==").setParameterLength(2).setName("equal"),Va=un(La,"!=").setParameterLength(2).setName("notEqual"),ka=un(La,"<").setParameterLength(2).setName("lessThan"),Ga=un(La,">").setParameterLength(2).setName("greaterThan"),za=un(La,"<=").setParameterLength(2).setName("lessThanEqual"),$a=un(La,">=").setParameterLength(2).setName("greaterThanEqual"),Wa=un(La,"&&").setParameterLength(2,1/0).setName("and"),Ha=un(La,"||").setParameterLength(2,1/0).setName("or"),qa=un(La,"!").setParameterLength(1).setName("not"),ja=un(La,"^^").setParameterLength(2).setName("xor"),Xa=un(La,"&").setParameterLength(2).setName("bitAnd"),Ka=un(La,"~").setParameterLength(1).setName("bitNot"),Qa=un(La,"|").setParameterLength(2).setName("bitOr"),Ya=un(La,"^").setParameterLength(2).setName("bitXor"),Za=un(La,"<<").setParameterLength(2).setName("shiftLeft"),Ja=un(La,">>").setParameterLength(2).setName("shiftRight"),eo=cn(([e])=>(e.addAssign(1),e)),to=cn(([e])=>(e.subAssign(1),e)),ro=cn(([e])=>{const t=bn(e).toConst();return e.addAssign(1),t}),so=cn(([e])=>{const t=bn(e).toConst();return e.subAssign(1),t});Ei("add",Fa),Ei("sub",Pa),Ei("mul",Da),Ei("div",Ua),Ei("mod",Ia),Ei("equal",Oa),Ei("notEqual",Va),Ei("lessThan",ka),Ei("greaterThan",Ga),Ei("lessThanEqual",za),Ei("greaterThanEqual",$a),Ei("and",Wa),Ei("or",Ha),Ei("not",qa),Ei("xor",ja),Ei("bitAnd",Xa),Ei("bitNot",Ka),Ei("bitOr",Qa),Ei("bitXor",Ya),Ei("shiftLeft",Za),Ei("shiftRight",Ja),Ei("incrementBefore",eo),Ei("decrementBefore",to),Ei("increment",ro),Ei("decrement",so);const io=(e,t)=>(d('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Is),Ia(bn(e),bn(t)));Ei("modInt",io);class no extends gi{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===no.MAX||e===no.MIN)&&arguments.length>3){let i=new no(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}generateNodeType(e){const t=this.method;return t===no.LENGTH||t===no.DISTANCE||t===no.DOT?"float":t===no.CROSS?"vec3":t===no.ALL||t===no.ANY?"bool":t===no.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===no.ONE_MINUS)i=Pa(1,t);else if(s===no.RECIPROCAL)i=Ua(1,t);else if(s===no.DIFFERENCE)i=Vo(Pa(t,r));else if(s===no.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=Cn(Rn(n),0):s=Cn(Rn(s),0);const a=Da(s,n).xyz;i=Ro(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===no.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const l=[];return r===no.CROSS?l.push(n.build(e,s),a.build(e,s)):u===c&&r===no.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==c||r!==no.MIN&&r!==no.MAX?r===no.REFRACT?l.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===no.MIX?l.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===h&&r===no.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==no.DFDX&&r!==no.DFDY||(d(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),r="/*"+r+"*/"),l.push(n.build(e,i)),null!==a&&l.push(a.build(e,i)),null!==o&&l.push(o.build(e,i))):l.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${l.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}no.ALL="all",no.ANY="any",no.RADIANS="radians",no.DEGREES="degrees",no.EXP="exp",no.EXP2="exp2",no.LOG="log",no.LOG2="log2",no.SQRT="sqrt",no.INVERSE_SQRT="inversesqrt",no.FLOOR="floor",no.CEIL="ceil",no.NORMALIZE="normalize",no.FRACT="fract",no.SIN="sin",no.SINH="sinh",no.COS="cos",no.COSH="cosh",no.TAN="tan",no.TANH="tanh",no.ASIN="asin",no.ASINH="asinh",no.ACOS="acos",no.ACOSH="acosh",no.ATAN="atan",no.ATANH="atanh",no.ABS="abs",no.SIGN="sign",no.LENGTH="length",no.NEGATE="negate",no.ONE_MINUS="oneMinus",no.DFDX="dFdx",no.DFDY="dFdy",no.ROUND="round",no.RECIPROCAL="reciprocal",no.TRUNC="trunc",no.FWIDTH="fwidth",no.TRANSPOSE="transpose",no.DETERMINANT="determinant",no.INVERSE="inverse",no.EQUALS="equals",no.MIN="min",no.MAX="max",no.STEP="step",no.REFLECT="reflect",no.DISTANCE="distance",no.DIFFERENCE="difference",no.DOT="dot",no.CROSS="cross",no.POW="pow",no.TRANSFORM_DIRECTION="transformDirection",no.MIX="mix",no.CLAMP="clamp",no.REFRACT="refract",no.SMOOTHSTEP="smoothstep",no.FACEFORWARD="faceforward";const ao=yn(1e-6),oo=yn(1e6),uo=yn(Math.PI),lo=yn(2*Math.PI),co=yn(2*Math.PI),ho=yn(.5*Math.PI),po=un(no,no.ALL).setParameterLength(1),go=un(no,no.ANY).setParameterLength(1),mo=un(no,no.RADIANS).setParameterLength(1),fo=un(no,no.DEGREES).setParameterLength(1),yo=un(no,no.EXP).setParameterLength(1),bo=un(no,no.EXP2).setParameterLength(1),xo=un(no,no.LOG).setParameterLength(1),To=un(no,no.LOG2).setParameterLength(1),_o=un(no,no.SQRT).setParameterLength(1),vo=un(no,no.INVERSE_SQRT).setParameterLength(1),No=un(no,no.FLOOR).setParameterLength(1),So=un(no,no.CEIL).setParameterLength(1),Ro=un(no,no.NORMALIZE).setParameterLength(1),Eo=un(no,no.FRACT).setParameterLength(1),Ao=un(no,no.SIN).setParameterLength(1),wo=un(no,no.SINH).setParameterLength(1),Co=un(no,no.COS).setParameterLength(1),Mo=un(no,no.COSH).setParameterLength(1),Bo=un(no,no.TAN).setParameterLength(1),Lo=un(no,no.TANH).setParameterLength(1),Fo=un(no,no.ASIN).setParameterLength(1),Po=un(no,no.ASINH).setParameterLength(1),Do=un(no,no.ACOS).setParameterLength(1),Uo=un(no,no.ACOSH).setParameterLength(1),Io=un(no,no.ATAN).setParameterLength(1,2),Oo=un(no,no.ATANH).setParameterLength(1),Vo=un(no,no.ABS).setParameterLength(1),ko=un(no,no.SIGN).setParameterLength(1),Go=un(no,no.LENGTH).setParameterLength(1),zo=un(no,no.NEGATE).setParameterLength(1),$o=un(no,no.ONE_MINUS).setParameterLength(1),Wo=un(no,no.DFDX).setParameterLength(1),Ho=un(no,no.DFDY).setParameterLength(1),qo=un(no,no.ROUND).setParameterLength(1),jo=un(no,no.RECIPROCAL).setParameterLength(1),Xo=un(no,no.TRUNC).setParameterLength(1),Ko=un(no,no.FWIDTH).setParameterLength(1),Qo=un(no,no.TRANSPOSE).setParameterLength(1),Yo=un(no,no.DETERMINANT).setParameterLength(1),Zo=un(no,no.INVERSE).setParameterLength(1),Jo=un(no,no.MIN).setParameterLength(2,1/0),eu=un(no,no.MAX).setParameterLength(2,1/0),tu=un(no,no.STEP).setParameterLength(2),ru=un(no,no.REFLECT).setParameterLength(2),su=un(no,no.DISTANCE).setParameterLength(2),iu=un(no,no.DIFFERENCE).setParameterLength(2),nu=un(no,no.DOT).setParameterLength(2),au=un(no,no.CROSS).setParameterLength(2),ou=un(no,no.POW).setParameterLength(2),uu=e=>Da(e,e),lu=e=>Da(e,e,e),du=e=>Da(e,e,e,e),cu=un(no,no.TRANSFORM_DIRECTION).setParameterLength(2),hu=e=>Da(ko(e),ou(Vo(e),1/3)),pu=e=>nu(e,e),gu=un(no,no.MIX).setParameterLength(3),mu=(e,t=0,r=1)=>new no(no.CLAMP,tn(e),tn(t),tn(r)),fu=e=>mu(e),yu=un(no,no.REFRACT).setParameterLength(3),bu=un(no,no.SMOOTHSTEP).setParameterLength(3),xu=un(no,no.FACEFORWARD).setParameterLength(3),Tu=cn(([e])=>{const t=nu(e.xy,_n(12.9898,78.233)),r=Ia(t,uo);return Eo(Ao(r).mul(43758.5453))}),_u=(e,t,r)=>gu(t,r,e),vu=(e,t,r)=>bu(t,r,e),Nu=(e,t)=>tu(t,e),Su=xu,Ru=vo;Ei("all",po),Ei("any",go),Ei("radians",mo),Ei("degrees",fo),Ei("exp",yo),Ei("exp2",bo),Ei("log",xo),Ei("log2",To),Ei("sqrt",_o),Ei("inverseSqrt",vo),Ei("floor",No),Ei("ceil",So),Ei("normalize",Ro),Ei("fract",Eo),Ei("sin",Ao),Ei("sinh",wo),Ei("cos",Co),Ei("cosh",Mo),Ei("tan",Bo),Ei("tanh",Lo),Ei("asin",Fo),Ei("asinh",Po),Ei("acos",Do),Ei("acosh",Uo),Ei("atan",Io),Ei("atanh",Oo),Ei("abs",Vo),Ei("sign",ko),Ei("length",Go),Ei("lengthSq",pu),Ei("negate",zo),Ei("oneMinus",$o),Ei("dFdx",Wo),Ei("dFdy",Ho),Ei("round",qo),Ei("reciprocal",jo),Ei("trunc",Xo),Ei("fwidth",Ko),Ei("min",Jo),Ei("max",eu),Ei("step",Nu),Ei("reflect",ru),Ei("distance",su),Ei("dot",nu),Ei("cross",au),Ei("pow",ou),Ei("pow2",uu),Ei("pow3",lu),Ei("pow4",du),Ei("transformDirection",cu),Ei("mix",_u),Ei("clamp",mu),Ei("refract",yu),Ei("smoothstep",vu),Ei("faceForward",xu),Ei("difference",iu),Ei("saturate",fu),Ei("cbrt",hu),Ei("transpose",Qo),Ei("determinant",Yo),Ei("inverse",Zo),Ei("rand",Tu);class Eu extends ci{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}generateNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode,r=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?Vn(r).build(e):"";s.nodeProperty=l;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(c,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=n.build(e,r);if(h&&(u?h=l+" = "+h+";":(h="return "+h+";",null===o&&(d("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,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Au=an(Eu).setParameterLength(2,3);Ei("select",Au);class wu extends ci{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const r=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(r),s}}const Cu=(e=null,t={})=>{let r=e;return null!==r&&!0===r.isNode||(t=r||t,r=null),new wu(r,t)},Mu=e=>Cu(e,{uniformFlow:!0}),Bu=(e,t)=>Cu(e,{nodeName:t});function Lu(e,t,r=null){return Cu(r,{getShadow:({light:r,shadowColorNode:s})=>t===r?s.mul(e):s})}function Fu(e,t=null){return Cu(t,{getAO:(t,{material:r})=>!0===r.transparent?t:null!==t?t.mul(e):e})}function Pu(e,t){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),Bu(e,t)}Ei("context",Cu),Ei("label",Pu),Ei("uniformFlow",Mu),Ei("setName",Bu),Ei("builtinShadowContext",(e,t,r)=>Lu(t,r,e)),Ei("builtinAOContext",(e,t)=>Fu(t,e));class Du extends ci{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const r=t.getBaseStack();e?r.addToStackBefore(this):r.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,u=!1;s&&(a=e.isDeterministic(t),u=n?s:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&o('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const d=e.getVectorType(l),c=t.build(e,d),h=e.getVarFromNode(this,r,d,void 0,u),p=e.getPropertyName(h);let g=p;if(u)if(n)g=a?`const ${p}`:`let ${p}`;else{const r=t.getArrayCount(e);g=`const ${e.getVar(h.type,p,r)}`}return e.addLineFlowCode(`${g} = ${c}`,this),p}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Uu=an(Du),Iu=(e,t=null)=>Uu(e,t).toStack(),Ou=(e,t=null)=>Uu(e,t,!0).toStack(),Vu=e=>Uu(e).setIntent(!0).toStack();Ei("toVar",Iu),Ei("toConst",Ou),Ei("toVarIntent",Vu);class ku extends ci{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),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 r=this.node.build(e,...t);return e.removeSubBuild(),r}}const Gu=(e,t,r=null)=>new ku(tn(e),t,r);class zu extends ci{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Gu(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 r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=Gu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,ti.VERTEX);e.flowNodeFromShaderStage(ti.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const $u=an(zu).setParameterLength(1,2),Wu=e=>$u(e);Ei("toVarying",$u),Ei("toVertexStage",Wu);const Hu=cn(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return gu(t,r,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),qu=cn(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return gu(t,r,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ju="WorkingColorSpace";class Xu extends gi{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===ju?p.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==p.enabled&&r!==s&&r&&s?(p.getTransfer(r)===g&&(i=Cn(Hu(i.rgb),i.a)),p.getPrimaries(r)!==p.getPrimaries(s)&&(i=Cn(Pn(p._getMatrix(new n,r,s)).mul(i.rgb),i.a)),p.getTransfer(s)===g&&(i=Cn(qu(i.rgb),i.a)),i):i}}const Ku=(e,t)=>new Xu(tn(e),ju,t),Qu=(e,t)=>new Xu(tn(e),t,ju);Ei("workingToColorSpace",Ku),Ei("colorSpaceToWorking",Qu);let Yu=class extends hi{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),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class Zu extends ci{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=ri.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Yu(this,tn(e))}setNodeType(e){const t=Sa(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 r=e[t[0]];for(let e=1;enew Ju(e,t,r);class tl extends gi{static get type(){return"ToneMappingNode"}constructor(e,t=sl,r=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Gs(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,r=this._toneMapping;if(r===m)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=Cn(i(t.rgb,this.exposureNode),t.a):(o("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const rl=(e,t,r)=>new tl(e,tn(t),tn(r)),sl=el("toneMappingExposure","float");Ei("toneMapping",(e,t,r)=>rl(t,r,e));const il=new WeakMap;function nl(e,t){let r=il.get(e);return void 0===r&&(r=new b(e,t),il.set(e,r)),r}class al extends Ti{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=f,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.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),r=e.getTypeLength(t),s=this.value,i=this.bufferStride||r,n=this.bufferOffset;let a;a=!0===s.isInterleavedBuffer?s:!0===s.isBufferAttribute?nl(s.array,i):nl(s,i);const o=new y(a,r,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(r);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=s,i=s;else{i=$u(this).build(e,t)}return i}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 ol(e,t=null,r=0,s=0,i=f,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Pn(new al(e,"vec3",9,0).setUsage(i).setInstanced(n),new al(e,"vec3",9,3).setUsage(i).setInstanced(n),new al(e,"vec3",9,6).setUsage(i).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Dn(new al(e,"vec4",16,0).setUsage(i).setInstanced(n),new al(e,"vec4",16,4).setUsage(i).setInstanced(n),new al(e,"vec4",16,8).setUsage(i).setInstanced(n),new al(e,"vec4",16,12).setUsage(i).setInstanced(n)):new al(e,t,r,s).setUsage(i)}const ul=(e,t=null,r=0,s=0)=>ol(e,t,r,s),ll=(e,t=null,r=0,s=0)=>ol(e,t,r,s,f,!0),dl=(e,t=null,r=0,s=0)=>ol(e,t,r,s,x,!0);Ei("toAttribute",e=>ul(e.value));class cl extends ci{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===cl.VERTEX)s=e.getVertexIndex();else if(r===cl.INSTANCE)s=e.getInstanceIndex();else if(r===cl.DRAW)s=e.getDrawIndex();else if(r===cl.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===cl.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==cl.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=$u(this).build(e,t)}return i}}cl.VERTEX="vertex",cl.INSTANCE="instance",cl.SUBGROUP="subgroup",cl.INVOCATION_LOCAL="invocationLocal",cl.INVOCATION_SUBGROUP="invocationSubgroup",cl.DRAW="draw";const hl=on(cl,cl.VERTEX),pl=on(cl,cl.INSTANCE),gl=on(cl,cl.SUBGROUP),ml=on(cl,cl.INVOCATION_SUBGROUP),fl=on(cl,cl.INVOCATION_LOCAL),yl=on(cl,cl.DRAW);class bl extends ci{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=ri.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=Sa(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:r}=e;if("compute"===r){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"),r=pl.build(e,"uint");e.flow.code=`${e.tab}if ( ${r} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const xl=(e,t=[64])=>{(0===t.length||t.length>3)&&o("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Is);for(let e=0;e{const s=xl(e,r);return"number"==typeof t?s.count=t:s.dispatchSize=t,s};Ei("compute",Tl),Ei("computeKernel",xl);class _l extends ci{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(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vl=e=>new _l(tn(e));function Nl(e,t=!0){return d('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vl(e).setParent(t)}Ei("cache",Nl),Ei("isolate",vl);class Sl extends ci{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)}}const Rl=an(Sl).setParameterLength(2);Ei("bypass",Rl);const El=cn(([e,t,r,s=yn(0),i=yn(1),n=Tn(!1)])=>{let a=e.sub(t).div(r.sub(t));return Zi(n)&&(a=a.clamp()),a.mul(i.sub(s)).add(s)});function Al(e,t,r,s=yn(0),i=yn(1)){return El(e,t,r,s,i,!0)}Ei("remap",El),Ei("remapClamp",Al);class wl extends ci{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Cl=an(wl).setParameterLength(1,2),Ml=e=>(e?Au(e,Cl("discard")):Cl("discard")).toStack();Ei("discard",Ml);class Bl extends gi{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||m,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||T;return r!==m&&(t=t.toneMapping(r)),s!==T&&s!==p.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Ll=(e,t=null,r=null)=>new Bl(tn(e),t,r);Ei("renderOutput",Ll);class Fl extends gi{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,r=this.node.build(e);if(null!==t)t(e,r);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(t.length);let i="";i+="// #"+t+"#\n",i+=e.flow.code.replace(/^\t/gm,"")+"\n",i+="/* ... */ "+r+" /* ... */\n",i+="// #"+s+"#\n",_(i)}return r}}const Pl=(e,t=null)=>new Fl(tn(e),t).toStack();Ei("debug",Pl);class Dl extends u{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Ul extends ci{static get type(){return"InspectorNode"}constructor(e,t="",r=null){super(),this.node=e,this.name=t,this.callback=r,this.updateType=ri.FRAME,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!==Dl&&v('TSL: ".toInspector()" is only available with WebGPU.'),t}}function Il(e,t="",r=null){return(e=tn(e)).before(new Ul(e,t,r))}Ei("toInspector",Il);class Ol extends ci{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 r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return $u(this).build(e,r)}return d(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Vl=(e,t=null)=>new Ol(e,t),kl=(e=0)=>Vl("uv"+(e>0?e:""),"vec2");class Gl extends ci{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const zl=an(Gl).setParameterLength(1,2);class $l extends Na{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ri.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const Wl=an($l).setParameterLength(1);class Hl extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const ql=new N;class jl extends Na{static get type(){return"TextureNode"}constructor(e=ql,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ri.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===S?"uvec4":this.value.type===R?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return kl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Sa(this.value.matrix)),this._matrixUniform.mul(Rn(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Sa(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(bn(zl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Hl("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const s=cn(()=>{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?ri.OBJECT:ri.NONE,t})();let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(E.TEXTURE_COMPARE))n=this.compareNode;else{const e=r.compareFunction;null===e||e===A||e===w||e===C||e===M?a=this.compareNode:(n=this.compareNode,v('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;let d;return d=i?e.generateTextureBias(l,t,r,i,n,u):o?e.generateTextureGrad(l,t,r,o,n,u):a?e.generateTextureCompare(l,t,r,a,n,u):!1===this.sampler?e.generateTextureLoad(l,t,r,s,n,u):s?e.generateTextureLevel(l,t,r,s,n,u):e.generateTexture(l,t,r,n,u),d}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:u,biasNode:l,compareNode:d,compareStepNode:c,depthNode:h,gradNode:p,offsetNode:g}=s,m=this.generateUV(e,t),f=u?u.build(e,"float"):null,y=l?l.build(e,"float"):null,b=h?h.build(e,"int"):null,x=d?d.build(e,"float"):null,T=c?c.build(e,"float"):null,_=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,v=g?this.generateOffset(e,g):null;let N=b;null===N&&r.isArrayTexture&&!0!==this.isTexture3DNode&&(N="0");const S=e.getVarFromNode(this);o=e.getPropertyName(S);let R=this.generateSnippet(e,i,m,f,y,N,x,_,v);if(null!==T){const t=r.compareFunction;R=t===C||t===M?tu(Cl(R,a),Cl(T,"float")).build(e,a):tu(Cl(T,"float"),Cl(R,a)).build(e,a)}e.addLineFlowCode(`${o} = ${R}`,this),n.snippet=R,n.propertyName=o}let u=o;return e.needsToWorkingColorSpace(r)&&(u=Qu(Cl(u,a),r.colorSpace).setup(e).build(e,a)),e.format(u,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=tn(e),t.referenceNode=this.getBase(),tn(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=tn(e).mul(Wl(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===B||r.magFilter===B)&&(d("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),tn(t)}level(e){const t=this.clone();return t.levelNode=tn(e),t.referenceNode=this.getBase(),tn(t)}size(e){return zl(this,e)}bias(e){const t=this.clone();return t.biasNode=tn(e),t.referenceNode=this.getBase(),tn(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=tn(e),t.referenceNode=this.getBase(),tn(t)}grad(e,t){const r=this.clone();return r.gradNode=[tn(e),tn(t)],r.referenceNode=this.getBase(),tn(r)}depth(e){const t=this.clone();return t.depthNode=tn(e),t.referenceNode=this.getBase(),tn(t)}offset(e){const t=this.clone();return t.offsetNode=tn(e),t.referenceNode=this.getBase(),tn(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 r=this._flipYUniform;null!==r&&(r.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const Xl=an(jl).setParameterLength(1,4).setName("texture"),Kl=(e=ql,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=tn(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=Xl(e,t,r,s),i},Ql=(...e)=>Kl(...e).setSampler(!1);class Yl extends Na{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r,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 Zl=(e,t,r)=>new Yl(e,t,r);class Jl extends hi{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(e),s=this.node.getPaddedType();return e.format(t,s,r)}}class ed extends Yl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ks(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ri.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rnew ed(e,t);class rd extends ci{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const sd=an(rd).setParameterLength(1);let id,nd;class ad extends ci{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===ad.DPR?"float":this.scope===ad.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ri.NONE;return this.scope!==ad.SIZE&&this.scope!==ad.VIEWPORT&&this.scope!==ad.DPR||(e=ri.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===ad.VIEWPORT?null!==t?nd.copy(t.viewport):(e.getViewport(nd),nd.multiplyScalar(e.getPixelRatio())):this.scope===ad.DPR?this._output.value=e.getPixelRatio():null!==t?(id.width=t.width,id.height=t.height):e.getDrawingBufferSize(id)}setup(){const e=this.scope;let r=null;return r=e===ad.SIZE?Sa(id||(id=new t)):e===ad.VIEWPORT?Sa(nd||(nd=new s)):e===ad.DPR?Sa(1):_n(dd.div(ld)),this._output=r,r}generate(e){if(this.scope===ad.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(ld).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}ad.COORDINATE="coordinate",ad.VIEWPORT="viewport",ad.SIZE="size",ad.UV="uv",ad.DPR="dpr";const od=on(ad,ad.DPR),ud=on(ad,ad.UV),ld=on(ad,ad.SIZE),dd=on(ad,ad.COORDINATE),cd=on(ad,ad.VIEWPORT),hd=cd.zw,pd=dd.sub(cd.xy),gd=pd.div(hd),md=cn(()=>(d('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new Is),ld),"vec2").once()();let fd=null,yd=null,bd=null,xd=null,Td=null,_d=null,vd=null,Nd=null,Sd=null,Rd=null,Ed=null,Ad=null,wd=null,Cd=null;const Md=Sa(0,"uint").setName("u_cameraIndex").setGroup(xa("cameraIndex")).toVarying("v_cameraIndex"),Bd=Sa("float").setName("cameraNear").setGroup(_a).onRenderUpdate(({camera:e})=>e.near),Ld=Sa("float").setName("cameraFar").setGroup(_a).onRenderUpdate(({camera:e})=>e.far),Fd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);null===yd?yd=td(r).setGroup(_a).setName("cameraProjectionMatrices"):yd.array=r,t=yd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrix")}else null===fd&&(fd=Sa(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=fd;return t}).once()(),Pd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);null===xd?xd=td(r).setGroup(_a).setName("cameraProjectionMatricesInverse"):xd.array=r,t=xd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrixInverse")}else null===bd&&(bd=Sa(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=bd;return t}).once()(),Dd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);null===_d?_d=td(r).setGroup(_a).setName("cameraViewMatrices"):_d.array=r,t=_d.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraViewMatrix")}else null===Td&&(Td=Sa(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=Td;return t}).once()(),Ud=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);null===Nd?Nd=td(r).setGroup(_a).setName("cameraWorldMatrices"):Nd.array=r,t=Nd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraWorldMatrix")}else null===vd&&(vd=Sa(e.matrixWorld).setName("cameraWorldMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=vd;return t}).once()(),Id=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);null===Rd?Rd=td(r).setGroup(_a).setName("cameraNormalMatrices"):Rd.array=r,t=Rd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraNormalMatrix")}else null===Sd&&(Sd=Sa(e.normalMatrix).setName("cameraNormalMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.normalMatrix)),t=Sd;return t}).once()(),Od=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t{const r=e.cameras,s=t.array;for(let e=0,t=r.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=Ed;return t}).once()(),Vd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);null===Cd?Cd=td(r,"vec4").setGroup(_a).setName("cameraViewports"):Cd.array=r,t=Cd.element(Md).toConst("cameraViewport")}else null===wd&&(wd=Cn(0,0,ld.x,ld.y).toConst("cameraViewport")),t=wd;return t}).once()(),kd=new L;class Gd extends ci{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ri.OBJECT,this.uniformNode=new Na(null)}generateNodeType(){const e=this.scope;return e===Gd.WORLD_MATRIX?"mat4":e===Gd.POSITION||e===Gd.VIEW_POSITION||e===Gd.DIRECTION||e===Gd.SCALE?"vec3":e===Gd.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Gd.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gd.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gd.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gd.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===Gd.VIEW_POSITION){const i=e.camera;s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Gd.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),kd.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=kd.radius}}generate(e){const t=this.scope;return t===Gd.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Gd.POSITION||t===Gd.VIEW_POSITION||t===Gd.DIRECTION||t===Gd.SCALE?this.uniformNode.nodeType="vec3":t===Gd.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}}Gd.WORLD_MATRIX="worldMatrix",Gd.POSITION="position",Gd.SCALE="scale",Gd.VIEW_POSITION="viewPosition",Gd.DIRECTION="direction",Gd.RADIUS="radius";const zd=an(Gd,Gd.DIRECTION).setParameterLength(1),$d=an(Gd,Gd.WORLD_MATRIX).setParameterLength(1),Wd=an(Gd,Gd.POSITION).setParameterLength(1),Hd=an(Gd,Gd.SCALE).setParameterLength(1),qd=an(Gd,Gd.VIEW_POSITION).setParameterLength(1),jd=an(Gd,Gd.RADIUS).setParameterLength(1);class Xd extends Gd{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Kd=on(Xd,Xd.DIRECTION),Qd=on(Xd,Xd.WORLD_MATRIX),Yd=on(Xd,Xd.POSITION),Zd=on(Xd,Xd.SCALE),Jd=on(Xd,Xd.VIEW_POSITION),ec=on(Xd,Xd.RADIUS),tc=Sa(new n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),rc=Sa(new a).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),sc=cn(e=>e.context.modelViewMatrix||ic).once()().toVar("modelViewMatrix"),ic=Dd.mul(Qd),nc=cn(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Sa("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),ac=cn(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Sa("mat3").onObjectUpdate(({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),oc=cn(e=>"fragment"!==e.shaderStage?(v("TSL: `clipSpace` is only available in fragment stage."),Cn()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),uc=Vl("position","vec3"),lc=uc.toVarying("positionLocal"),dc=uc.toVarying("positionPrevious"),cc=cn(e=>Qd.mul(lc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),hc=cn(()=>lc.transformDirection(Qd).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),pc=cn(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Pd.mul(oc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),gc=cn(e=>{let t;return t=e.camera.isOrthographicCamera?Rn(0,0,1):pc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class mc extends ci{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===F?"false":e.getFrontFacing()}}const fc=on(mc),yc=yn(fc).mul(2).sub(1),bc=cn(([e],{material:t})=>{const r=t.side;return r===F?e=e.mul(-1):r===P&&(e=e.mul(yc)),e}),xc=Vl("normal","vec3"),Tc=cn(e=>!1===e.geometry.hasAttribute("normal")?(d('TSL: Vertex attribute "normal" not found on geometry.'),Rn(0,1,0)):xc,"vec3").once()().toVar("normalLocal"),_c=pc.dFdx().cross(pc.dFdy()).normalize().toVar("normalFlat"),vc=cn(e=>{let t;return t=e.isFlatShading()?_c:wc(Tc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Nc=cn(e=>{let t=vc.transformDirection(Dd);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Sc=cn(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=vc,!0!==e.isFlatShading()&&(t=bc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Rc=Sc.transformDirection(Dd).toVar("normalWorld"),Ec=cn(({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Sc:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Ac=cn(([e,t=Qd])=>{const r=Pn(t),s=e.div(Rn(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz}),wc=cn(([e],t)=>{const r=t.context.modelNormalViewMatrix;if(r)return r.transformDirection(e);const s=tc.mul(e);return Dd.transformDirection(s)}),Cc=cn(()=>(d('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Sc)).once(["NORMAL","VERTEX"])(),Mc=cn(()=>(d('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Rc)).once(["NORMAL","VERTEX"])(),Bc=cn(()=>(d('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ec)).once(["NORMAL","VERTEX"])(),Lc=new a,Fc=Sa(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Pc=Sa(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Dc=Sa(new a).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const r=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?Lc.makeRotationFromEuler(r).transpose():Lc.identity(),Lc}),Uc=gc.negate().reflect(Sc),Ic=gc.negate().refract(Sc,Fc),Oc=Uc.transformDirection(Dd).toVar("reflectVector"),Vc=Ic.transformDirection(Dd).toVar("reflectVector"),kc=new D;class Gc extends jl{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===U?Oc:e.mapping===I?Vc:(o('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Rn(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!0===r.isDepthTexture?e.renderer.coordinateSystem===h?Rn(t.x,t.y.negate(),t.z):t:(t=Dc.mul(t),e.renderer.coordinateSystem!==h&&r.isRenderTargetTexture||(t=Rn(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const zc=an(Gc).setParameterLength(1,4).setName("cubeTexture"),$c=(e=kc,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=tn(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=zc(e,t,r,s),i};class Wc extends hi{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),r=this.referenceNode.getNodeType(e),s=this.getNodeType(e);return e.format(t,r,s)}}class Hc extends ci{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=ri.OBJECT}element(e){return new Wc(this,tn(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Zl(null,e,this.count):Array.isArray(this.getValueFromReference())?td(null,e):"texture"===e?Kl(null):"cubeTexture"===e?$c(null):Sa(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 r=e[t[0]];for(let e=1;enew Hc(e,t,r),jc=(e,t,r,s)=>new Hc(e,t,s,r);class Xc extends Hc{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Kc=(e,t,r=null)=>new Xc(e,t,r),Qc=kl(),Yc=pc.dFdx(),Zc=pc.dFdy(),Jc=Qc.dFdx(),eh=Qc.dFdy(),th=Sc,rh=Zc.cross(th),sh=th.cross(Yc),ih=rh.mul(Jc.x).add(sh.mul(eh.x)),nh=rh.mul(Jc.y).add(sh.mul(eh.y)),ah=ih.dot(ih).max(nh.dot(nh)),oh=ah.equal(0).select(0,ah.inverseSqrt()),uh=ih.mul(oh).toVar("tangentViewFrame"),lh=nh.mul(oh).toVar("bitangentViewFrame"),dh=Vl("tangent","vec4"),ch=dh.xyz.toVar("tangentLocal"),hh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?sc.mul(Cn(ch,0)).xyz.toVarying("v_tangentView").normalize():uh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ph=hh.transformDirection(Dd).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),gh=cn(([e,t],r)=>{let s=e.mul(dh.w).xyz;return"NORMAL"===r.subBuildFn&&!0!==r.isFlatShading()&&(s=s.toVarying(t)),s}).once(["NORMAL"]),mh=gh(xc.cross(dh),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),fh=gh(Tc.cross(ch),"v_bitangentLocal").normalize().toVar("bitangentLocal"),yh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?gh(Sc.cross(hh),"v_bitangentView").normalize():lh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),bh=gh(Rc.cross(ph),"v_bitangentWorld").normalize().toVar("bitangentWorld"),xh=Pn(hh,yh,Sc).toVar("TBNViewMatrix"),Th=gc.mul(xh),_h=cn(()=>{let e=ra.cross(gc);return e=e.cross(ra).normalize(),e=gu(e,Sc,ea.mul(Wn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),vh=e=>tn(e).mul(.5).add(.5),Nh=e=>Rn(e,_o(fu(yn(1).sub(nu(e,e)))));class Sh extends gi{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=O,this.unpackNormalMode=V}setup(e){const{normalMapType:t,scaleNode:r,unpackNormalMode:s}=this;let i=this.node.mul(2).sub(1);if(t===O?s===k?i=Nh(i.xy):s===G?i=Nh(i.yw):s!==V&&o(`THREE.NodeMaterial: Unexpected unpack normal mode: ${s}`):s!==V&&o(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${s}'`),null!==r){let t=r;!0===e.isFlatShading()&&(t=bc(t)),i=Rn(i.xy.mul(t),i.z)}let n=null;return t===z?n=wc(i):t===O?n=xh.mul(i).normalize():(o(`NodeMaterial: Unsupported normal map type: ${t}`),n=Sc),n}}const Rh=an(Sh).setParameterLength(1,2),Eh=cn(({textureNode:e,bumpScale:t})=>{const r=t=>e.isolate().context({getUV:e=>t(e.uvNode||kl()),forceUVContext:!0}),s=yn(r(e=>e));return _n(yn(r(e=>e.add(e.dFdx()))).sub(s),yn(r(e=>e.add(e.dFdy()))).sub(s)).mul(t)}),Ah=cn(e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(yc),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()});class wh extends gi{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Eh({textureNode:this.textureNode,bumpScale:e});return Ah({surf_pos:pc,surf_norm:Sc,dHdxy:t})}}const Ch=an(wh).setParameterLength(1,2),Mh=new Map;class Bh extends ci{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Mh.get(e);return void 0===r&&(r=Kc(e,t),Mh.set(e,r)),r}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,r=this.scope;let s=null;if(r===Bh.COLOR){const e=void 0!==t.color?this.getColor(r):Rn();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Bh.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Bh.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:yn(1);else if(r===Bh.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Bh.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Bh.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Bh.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Bh.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Bh.NORMAL)t.normalMap?(s=Rh(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType,t.normalMap.format!=$&&t.normalMap.format!=W&&t.normalMap.format!=H||(s.unpackNormalMode=k)):s=t.bumpMap?Ch(this.getTexture("bump").r,this.getFloat("bumpScale")):Sc;else if(r===Bh.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Rh(this.getTexture(r),this.getCache(r+"Scale","vec2")):Sc;else if(r===Bh.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Bh.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(1e-4,1)}else if(r===Bh.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=Fn(mp.x,mp.y,mp.y.negate(),mp.x).mul(e.rg.mul(2).sub(_n(1)).normalize().mul(e.b))}else s=mp;else if(r===Bh.IRIDESCENCE_THICKNESS){const e=qc("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=qc("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Bh.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Bh.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Bh.IOR)s=this.getFloat(r);else if(r===Bh.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Bh.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Bh.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):yn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Bh.ALPHA_TEST="alphaTest",Bh.COLOR="color",Bh.OPACITY="opacity",Bh.SHININESS="shininess",Bh.SPECULAR="specular",Bh.SPECULAR_STRENGTH="specularStrength",Bh.SPECULAR_INTENSITY="specularIntensity",Bh.SPECULAR_COLOR="specularColor",Bh.REFLECTIVITY="reflectivity",Bh.ROUGHNESS="roughness",Bh.METALNESS="metalness",Bh.NORMAL="normal",Bh.CLEARCOAT="clearcoat",Bh.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Bh.CLEARCOAT_NORMAL="clearcoatNormal",Bh.EMISSIVE="emissive",Bh.ROTATION="rotation",Bh.SHEEN="sheen",Bh.SHEEN_ROUGHNESS="sheenRoughness",Bh.ANISOTROPY="anisotropy",Bh.IRIDESCENCE="iridescence",Bh.IRIDESCENCE_IOR="iridescenceIOR",Bh.IRIDESCENCE_THICKNESS="iridescenceThickness",Bh.IOR="ior",Bh.TRANSMISSION="transmission",Bh.THICKNESS="thickness",Bh.ATTENUATION_DISTANCE="attenuationDistance",Bh.ATTENUATION_COLOR="attenuationColor",Bh.LINE_SCALE="scale",Bh.LINE_DASH_SIZE="dashSize",Bh.LINE_GAP_SIZE="gapSize",Bh.LINE_WIDTH="linewidth",Bh.LINE_DASH_OFFSET="dashOffset",Bh.POINT_SIZE="size",Bh.DISPERSION="dispersion",Bh.LIGHT_MAP="light",Bh.AO="ao";const Lh=on(Bh,Bh.ALPHA_TEST),Fh=on(Bh,Bh.COLOR),Ph=on(Bh,Bh.SHININESS),Dh=on(Bh,Bh.EMISSIVE),Uh=on(Bh,Bh.OPACITY),Ih=on(Bh,Bh.SPECULAR),Oh=on(Bh,Bh.SPECULAR_INTENSITY),Vh=on(Bh,Bh.SPECULAR_COLOR),kh=on(Bh,Bh.SPECULAR_STRENGTH),Gh=on(Bh,Bh.REFLECTIVITY),zh=on(Bh,Bh.ROUGHNESS),$h=on(Bh,Bh.METALNESS),Wh=on(Bh,Bh.NORMAL),Hh=on(Bh,Bh.CLEARCOAT),qh=on(Bh,Bh.CLEARCOAT_ROUGHNESS),jh=on(Bh,Bh.CLEARCOAT_NORMAL),Xh=on(Bh,Bh.ROTATION),Kh=on(Bh,Bh.SHEEN),Qh=on(Bh,Bh.SHEEN_ROUGHNESS),Yh=on(Bh,Bh.ANISOTROPY),Zh=on(Bh,Bh.IRIDESCENCE),Jh=on(Bh,Bh.IRIDESCENCE_IOR),ep=on(Bh,Bh.IRIDESCENCE_THICKNESS),tp=on(Bh,Bh.TRANSMISSION),rp=on(Bh,Bh.THICKNESS),sp=on(Bh,Bh.IOR),ip=on(Bh,Bh.ATTENUATION_DISTANCE),np=on(Bh,Bh.ATTENUATION_COLOR),ap=on(Bh,Bh.LINE_SCALE),op=on(Bh,Bh.LINE_DASH_SIZE),up=on(Bh,Bh.LINE_GAP_SIZE),lp=on(Bh,Bh.LINE_WIDTH),dp=on(Bh,Bh.LINE_DASH_OFFSET),cp=on(Bh,Bh.POINT_SIZE),hp=on(Bh,Bh.DISPERSION),pp=on(Bh,Bh.LIGHT_MAP),gp=on(Bh,Bh.AO),mp=Sa(new t).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))}),fp=cn(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class yp extends hi{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 r=this.storageBufferNode.structTypeNode;return r?r.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 r;const s=e.context.assign;if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const bp=an(yp).setParameterLength(2);class xp extends Yl{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStruct?(s="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Ws(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=ii.READ_WRITE,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return bp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ii.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=ul(this.value),this._varying=$u(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:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Tp=(e,t=null,r=0)=>new xp(e,t,r);class _p extends ci{static get type(){return"InstanceNode"}constructor(e,t,r=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=r,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=ri.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:r}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:s,isStorageColor:i}=this;if(s&&null===r){if(i)r=Tp(s,"vec3",Math.max(s.count,1)).element(pl);else{const e=new q(s.array,3),t=s.usage===x?dl:ll;this.bufferColor=e,r=Rn(t(e,"vec3",3,0))}this.instanceColorNode=r}const n=t.mul(lc).xyz;if(lc.assign(n),e.needsPreviousData()&&dc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=Ac(Tc,t);Tc.assign(e)}null!==this.instanceColorNode&&kn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(dc).xyz}_createInstanceMatrixNode(e,t){let r;const{instanceMatrix:s}=this,{count:i}=s;if(this.isStorageMatrix)r=Tp(s,"mat4",Math.max(i,1)).element(pl);else{if(16*i*4<=t.getUniformBufferLimit())r=Zl(s.array,"mat4",Math.max(i,1)).element(pl);else{const t=new j(s.array,16,1);!0===e&&(this.buffer=t);const i=s.usage===x?dl:ll,n=[i(t,"vec4",16,0),i(t,"vec4",16,4),i(t,"vec4",16,8),i(t,"vec4",16,12)];r=Dn(...n)}}return r}}const vp=an(_p).setParameterLength(2,3);class Np extends _p{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Sp=an(Np).setParameterLength(1);class Rp extends ci{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=pl:this.batchingIdNode=yl);const t=cn(([e])=>{const t=bn(zl(Ql(this.batchMesh._indirectTexture),0).x).toConst(),r=bn(e).mod(t).toConst(),s=bn(e).div(t).toConst();return Ql(this.batchMesh._indirectTexture,vn(r,s)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(bn(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=bn(zl(Ql(s),0).x).toConst(),n=yn(r).mul(4).toInt().toConst(),a=n.mod(i).toConst(),o=n.div(i).toConst(),u=Dn(Ql(s,vn(a,o)),Ql(s,vn(a.add(1),o)),Ql(s,vn(a.add(2),o)),Ql(s,vn(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=cn(([e])=>{const t=bn(zl(Ql(l),0).x).toConst(),r=e,s=r.mod(t).toConst(),i=r.div(t).toConst();return Ql(l,vn(s,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);kn("vec3","vBatchColor").assign(t)}const d=Pn(u);lc.assign(u.mul(lc));const c=Tc.div(Rn(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Tc.assign(h),e.hasGeometryAttribute("tangent")&&ch.mulAssign(d)}}const Ep=an(Rp).setParameterLength(1),Ap=new WeakMap;class wp extends ci{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=ri.OBJECT,this.skinIndexNode=Vl("skinIndex","uvec4"),this.skinWeightNode=Vl("skinWeight","vec4"),this.bindMatrixNode=qc("bindMatrix","mat4"),this.bindMatrixInverseNode=qc("bindMatrixInverse","mat4"),this.boneMatricesNode=jc("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=lc,this.toPositionNode=lc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w),d=i.mul(t),c=Fa(a.mul(s.x).mul(d),o.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=Tc,r=ch){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(s.x),u=e.element(s.y),l=e.element(s.z),d=e.element(s.w);let c=Fa(i.x.mul(o),i.y.mul(u),i.z.mul(l),i.w.mul(d));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(r).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=jc("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,dc)}setup(e){e.needsPreviousData()&&dc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:r}=this.getSkinnedNormalAndTangent();Tc.assign(t),e.hasGeometryAttribute("tangent")&&ch.assign(r)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Ap.get(t)!==e.frameId&&(Ap.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Cp=e=>new wp(e);class Mp extends ci{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 r={};for(let e=0,t=this.params.length-1;eNumber(l)?">=":"<")),a)n=`while ( ${l} )`;else{const r={start:u,end:l},s=r.start,i=r.end;let a;const g=()=>h.includes("<")?"+=":"-=";if(null!=p)switch(typeof p){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=d+" "+g()+" "+e.generateConst(c,p);break;case"string":a=d+" "+p;break;default:p.isNode?a=d+" "+g()+" "+p.build(e):(o("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else p="int"===c||"uint"===c?h.includes("<")?"++":"--":g()+" 1.",a=d+" "+p;n=`for ( ${e.getVar(c,d)+" = "+s}; ${d+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tnew Mp(nn(e,"int")).toStack(),Lp=()=>Cl("break").toStack(),Fp=new WeakMap,Pp=new s,Dp=cn(({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=bn(hl).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ql(e,vn(u,o)).depth(i).xyz.mul(t)});class Up extends ci{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Sa(1),this.updateType=ri.OBJECT}setup(e){const{geometry:r}=e,s=void 0!==r.morphAttributes.position,i=r.hasAttribute("normal")&&void 0!==r.morphAttributes.normal,n=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,a=void 0!==n?n.length:0,{texture:o,stride:u,size:l}=function(e){const r=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=Fp.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===r&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new X(m,h,p,a);f.type=K,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=yn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ql(this.mesh.morphTexture,vn(bn(e).add(1),bn(pl))).r):t.assign(qc("morphTargetInfluences","float").element(e).toVar()),gn(t.notEqual(0),()=>{!0===s&&lc.addAssign(Dp({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(0)})),!0===i&&Tc.addAssign(Dp({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const Ip=an(Up).setParameterLength(1);class Op extends ci{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vp extends Op{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class kp extends wu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=null,s=null){super(e),this.lightingModel=t,this.backdropNode=r,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,r={directDiffuse:Rn().toVar("directDiffuse"),directSpecular:Rn().toVar("directSpecular"),indirectDiffuse:Rn().toVar("indirectDiffuse"),indirectSpecular:Rn().toVar("indirectSpecular")};return{radiance:Rn().toVar("radiance"),irradiance:Rn().toVar("irradiance"),iblIrradiance:Rn().toVar("iblIrradiance"),ambientOcclusion:yn(1).toVar("ambientOcclusion"),reflectedLight:r,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Gp=an(kp);class zp extends Op{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const $p=new t;class Wp extends jl{static get type(){return"ViewportTextureNode"}constructor(e=ud,t=null,r=null){let s=null;null===r?(s=new Q,s.minFilter=Y,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=ri.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;null===i?t.getDrawingBufferSize($p):i.getDrawingBufferSize?i.getDrawingBufferSize($p):$p.set(i.width,i.height);const n=this.getTextureForReference(i);n.image.width===$p.width&&n.image.height===$p.height||(n.image.width=$p.width,n.image.height=$p.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Hp=an(Wp).setParameterLength(0,3),qp=an(Wp,null,null,{generateMipmaps:!0}).setParameterLength(0,3),jp=qp(),Xp=(e=ud,t=null)=>jp.sample(e,t);let Kp=null;class Qp extends Wp{static get type(){return"ViewportDepthTextureNode"}constructor(e=ud,t=null,r=null){null===r&&(null===Kp&&(Kp=new Z),r=Kp),super(e,t,r)}}const Yp=an(Qp).setParameterLength(0,3);class Zp extends ci{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===Zp.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Zp.DEPTH_BASE)null!==r&&(s=ng().assign(r));else if(t===Zp.DEPTH)s=e.isPerspectiveCamera?tg(pc.z,Bd,Ld):Jp(pc.z,Bd,Ld);else if(t===Zp.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=sg(r,Bd,Ld);s=Jp(e,Bd,Ld)}else s=r;else s=Jp(pc.z,Bd,Ld);return s}}Zp.DEPTH_BASE="depthBase",Zp.DEPTH="depth",Zp.LINEAR_DEPTH="linearDepth";const Jp=(e,t,r)=>e.add(t).div(t.sub(r)),eg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?r.sub(t).mul(e).sub(r):t.sub(r).mul(e).sub(t)),tg=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),rg=(e,t,r)=>t.mul(e.add(r)).div(e.mul(t.sub(r))),sg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?t.mul(r).div(t.sub(r).mul(e).sub(t)):t.mul(r).div(r.sub(t).mul(e).sub(r))),ig=(e,t,r)=>{t=t.max(1e-6).toVar();const s=To(e.negate().div(t)),i=To(r.div(t));return s.div(i)},ng=an(Zp,Zp.DEPTH_BASE),ag=on(Zp,Zp.DEPTH),og=an(Zp,Zp.LINEAR_DEPTH).setParameterLength(0,1),ug=og(Yp());ag.assign=e=>ng(e);class lg extends ci{static get type(){return"ClippingNode"}constructor(e=lg.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===lg.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===lg.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return cn(()=>{const r=yn().toVar("distanceToPlane"),s=yn().toVar("distanceToGradient"),i=yn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=td(t).setGroup(_a);Bp(n,({i:t})=>{const n=e.element(t);r.assign(pc.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(bu(s.negate(),s,r))})}const a=e.length;if(a>0){const t=td(e).setGroup(_a),n=yn(1).toVar("intersectionClipOpacity");Bp(a,({i:e})=>{const i=t.element(e);r.assign(pc.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(bu(s.negate(),s,r).oneMinus())}),i.mulAssign(n.oneMinus())}Gn.a.mulAssign(i),Gn.a.equal(0).discard()})()}setupDefault(e,t){return cn(()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=td(t).setGroup(_a);Bp(r,({i:t})=>{const r=e.element(t);pc.dot(r.xyz).greaterThan(r.w).discard()})}const s=e.length;if(s>0){const t=td(e).setGroup(_a),r=Tn(!0).toVar("clipped");Bp(s,({i:e})=>{const s=t.element(e);r.assign(pc.dot(s.xyz).greaterThan(s.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),cn(()=>{const s=td(e).setGroup(_a),i=sd(t.getClipDistance());Bp(r,({i:e})=>{const t=s.element(e),r=pc.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)})})()}}lg.ALPHA_TO_COVERAGE="alphaToCoverage",lg.DEFAULT="default",lg.HARDWARE="hardware";const dg=cn(([e])=>Eo(Da(1e4,Ao(Da(17,e.x).add(Da(.1,e.y)))).mul(Fa(.1,Vo(Ao(Da(13,e.y).add(e.x))))))),cg=cn(([e])=>dg(_n(dg(e.xy),e.z))),hg=cn(([e])=>{const t=eu(Go(Wo(e.xyz)),Go(Ho(e.xyz))),r=yn(1).div(yn(.05).mul(t)).toVar("pixScale"),s=_n(bo(No(To(r))),bo(So(To(r)))),i=_n(cg(No(s.x.mul(e.xyz))),cg(No(s.y.mul(e.xyz)))),n=Eo(To(r)),a=Fa(Da(n.oneMinus(),i.x),Da(n,i.y)),o=Jo(n,n.oneMinus()),u=Rn(a.mul(a).div(Da(2,o).mul(Pa(1,o))),a.sub(Da(.5,o)).div(Pa(1,o)),Pa(1,Pa(1,a).mul(Pa(1,a)).div(Da(2,o).mul(Pa(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return mu(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class pg extends Ol{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 r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new s(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const gg=(e=0)=>new pg(e),mg=cn(([e,t])=>Jo(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),fg=cn(([e,t])=>Jo(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yg=cn(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bg=cn(([e,t])=>gu(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),tu(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xg=cn(([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return Cn(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),Tg=cn(([e])=>Cn(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),_g=cn(([e])=>(gn(e.a.equal(0),()=>Cn(0)),Cn(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class vg extends J{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const r=this[t];r&&!0===r.isNode&&e.push({property:t,childNode:r})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:r}of this._getNodeChildren())e.push(Vs(t.slice(0,-4)),r.getCacheKey());return this.type+ks(e)}build(e){this.setup(e)}setupObserver(e){return new Ds(e)}setup(e){e.context.setupNormal=()=>Gu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=this.setupVertex(e),i=Gu(this.vertexNode||s,"VERTEX");let n;e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const i=Cn(s,Gn.a).max(0);n=this.setupOutput(e,i),oa.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&oa.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Cn(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?s=new lg(lg.ALPHA_TO_COVERAGE):e.stack.addToStack(new lg)}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new lg(lg.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?ig(pc.z,Bd,Ld):Jp(pc.z,Bd,Ld))}null!==s&&ag.assign(s).toStack()}setupPositionView(){return sc.mul(lc).xyz}setupModelViewProjection(){return Fd.mul(pc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),fp}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&Ip(t).toStack(),!0===t.isSkinnedMesh&&Cp(t).toStack(),this.displacementMap){const e=Kc("displacementMap","texture"),t=Kc("displacementScale","float"),r=Kc("displacementBias","float");lc.addAssign(Tc.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Ep(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Sp(t).toStack(),null!==this.positionNode&&lc.assign(Gu(this.positionNode,"POSITION","vec3")),lc}setupDiffuseColor(e){const{object:t,geometry:r}=e;null!==this.maskNode&&Tn(this.maskNode).not().discard();let s=this.colorNode?Cn(this.colorNode):Fh;if(!0===this.vertexColors&&r.hasAttribute("color")&&(s=s.mul(gg())),t.instanceColor){s=kn("vec3","vInstanceColor").mul(s)}if(t.isBatchedMesh&&t._colorsTexture){s=kn("vec3","vBatchColor").mul(s)}Gn.assign(s);const i=this.opacityNode?yn(this.opacityNode):Uh;Gn.a.assign(Gn.a.mul(i));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?yn(this.alphaTestNode):Lh,!0===this.alphaToCoverage?(Gn.a=bu(n,n.add(Ko(Gn.a)),Gn.a),Gn.a.lessThanEqual(0).discard()):Gn.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Gn.a.lessThan(hg(lc)).discard(),e.isOpaque()&&Gn.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Rn(0):Gn.rgb}setupNormal(){return this.normalNode?Rn(this.normalNode):Wh}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Kc("envMap","cubeTexture"):Kc("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zp(pp)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);s&&s.isLightingNode&&t.push(s);let i=this.aoNode;null===i&&e.material.aoMap&&(i=gp),e.context.getAO&&(i=e.context.getAO(i,e)),i&&t.push(new Vp(i));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Gp(n,t,r,s)}else null!==r&&(a=Rn(null!==s?gu(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&($n.assign(Rn(i||Dh)),a=a.add($n)),a}setupFog(e,t){const r=e.fogNode;return r&&(oa.assign(t),t=Cn(r.toVar())),t}setupPremultipliedAlpha(e,t){return Tg(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 r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.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 r=J.prototype.toJSON.call(this,e);r.inputNodes={};for(const{property:t,childNode:s}of this._getNodeChildren())r.inputNodes[t]=s.toJSON(e).uuid;function s(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const Ng=new ee;class Sg extends vg{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Ng),this.setValues(e)}}const Rg=new te;class Eg extends vg{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Rg),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?yn(this.offsetNode):dp,t=this.dashScaleNode?yn(this.dashScaleNode):ap,r=this.dashSizeNode?yn(this.dashSizeNode):op,s=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(r),la.assign(s);const i=$u(Vl("lineDistance").mul(t));(e?i.add(e):i).mod(ua.add(la)).greaterThan(ua).discard()}}const Ag=new te;class wg extends vg{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Ag),this.vertexColors=e.vertexColors,this.dashOffset=0,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=re,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.vertexColors,i=this._useDash,n=this._useWorldUnits,a=cn(({start:e,end:t})=>{const r=Fd.element(2).element(2),s=Fd.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return Cn(gu(e.xyz,t.xyz,s),t.w)}).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=cn(()=>{const e=Vl("instanceStart"),t=Vl("instanceEnd"),r=Cn(sc.mul(Cn(e,1))).toVar("start"),s=Cn(sc.mul(Cn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?yn(this.dashScaleNode):ap,t=this.offsetNode?yn(this.offsetNode):dp,r=Vl("instanceDistanceStart"),s=Vl("instanceDistanceEnd");let i=uc.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),kn("float","lineDistance").assign(i)}n&&(kn("vec3","worldStart").assign(r.xyz),kn("vec3","worldEnd").assign(s.xyz));const o=cd.z.div(cd.w),u=Fd.element(2).element(3).equal(-1);gn(u,()=>{gn(r.z.lessThan(0).and(s.z.greaterThan(0)),()=>{s.assign(a({start:r,end:s}))}).ElseIf(s.z.lessThan(0).and(r.z.greaterThanEqual(0)),()=>{r.assign(a({start:s,end:r}))})});const l=Fd.mul(r),d=Fd.mul(s),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const g=Cn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=gu(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=kn("vec4","worldPos");o.assign(uc.y.lessThan(.5).select(r,s));const u=lp.mul(.5);o.addAssign(Cn(uc.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(Cn(uc.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(Cn(a.mul(u),0)),gn(uc.y.greaterThan(1).or(uc.y.lessThan(0)),()=>{o.subAssign(Cn(a.mul(2).mul(u),0))})),g.assign(Fd.mul(o));const l=Rn().toVar();l.assign(uc.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=_n(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(uc.x.lessThan(0).select(e.negate(),e)),gn(uc.y.lessThan(0),()=>{e.assign(e.sub(p))}).ElseIf(uc.y.greaterThan(1),()=>{e.assign(e.add(p))}),e.assign(e.mul(lp)),e.assign(e.div(cd.w.div(od))),g.assign(uc.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(Cn(e,0,0)))}return g})();const o=cn(({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return _n(h,p)});if(this.colorNode=cn(()=>{const e=kl();if(i){const t=this.dashSizeNode?yn(this.dashSizeNode):op,r=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(t),la.assign(r);const s=kn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(ua.add(la)).greaterThan(ua).discard()}const a=yn(1).toVar("alpha");if(n){const e=kn("vec3","worldStart"),s=kn("vec3","worldEnd"),n=kn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:Rn(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(lp);if(!i)if(r&&t.currentSamples>0){const e=h.fwidth();a.assign(bu(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.currentSamples>0){const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1)),s=t.mul(t).add(r.mul(r)),i=yn(s.fwidth()).toVar("dlen");gn(e.y.abs().greaterThan(1),()=>{a.assign(bu(i.oneMinus(),i.add(1),s).oneMinus())})}else gn(e.y.abs().greaterThan(1),()=>{const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1));t.mul(t).add(r.mul(r)).greaterThan(1).discard()});let u;if(this.lineColorNode)u=this.lineColorNode;else if(s){const e=Vl("instanceColorStart"),t=Vl("instanceColorEnd");u=uc.y.lessThan(.5).select(e,t).mul(Fh)}else u=Fh;return Cn(u,a)})(),this.transparent){const e=this.opacityNode?yn(this.opacityNode):Uh;this.outputNode=Cn(this.colorNode.rgb.mul(e).add(Xp().rgb.mul(e.oneMinus())),this.colorNode.a)}super.setup(e)}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}copy(e){return super.copy(e),this.vertexColors=e.vertexColors,this.dashOffset=e.dashOffset,this.lineColorNode=e.lineColorNode,this.offsetNode=e.offsetNode,this.dashScaleNode=e.dashScaleNode,this.dashSizeNode=e.dashSizeNode,this.gapSizeNode=e.gapSizeNode,this._useDash=e._useDash,this._useAlphaToCoverage=e._useAlphaToCoverage,this._useWorldUnits=e._useWorldUnits,this}}const Cg=new se;class Mg extends vg{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Cg),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?yn(this.opacityNode):Uh;Gn.assign(Qu(Cn(vh(Sc),e),ie))}}const Bg=cn(([e=hc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return _n(t,r)});class Lg extends ne{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const r={width:e,height:e,depth:1},s=[r,r,r,r,r,r];this.texture=new D(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=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 i=new ae(5,5,5),n=Bg(hc),a=new vg;a.colorNode=Kl(t,n,0),a.side=F,a.blending=re;const o=new oe(i,a),u=new ue;u.add(o),t.minFilter===Y&&(t.minFilter=le);const l=new de(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.generateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,r=!0,s=!0){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,r,s);e.setRenderTarget(i)}}const Fg=new WeakMap;class Pg extends gi{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=$c(null);const t=new D;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ri.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===ce||r===he){if(Fg.has(e)){const t=Fg.get(e);Ug(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Lg(r.height);s.fromEquirectangularTexture(t,e),Ug(s.texture,e.mapping),this._cubeTexture=s.texture,Fg.set(e,s.texture),e.addEventListener("dispose",Dg)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Dg(e){const t=e.target;t.removeEventListener("dispose",Dg);const r=Fg.get(t);void 0!==r&&(Fg.delete(t),r.dispose())}function Ug(e,t){t===ce?e.mapping=U:t===he&&(e.mapping=I)}const Ig=an(Pg).setParameterLength(1);class Og extends Op{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Ig(this.envNode)}}class Vg extends Op{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=yn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class kg{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Gg extends kg{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(Cn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(Cn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(Gn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case me:s.rgb.assign(gu(s.rgb,s.rgb.mul(i.rgb),kh.mul(Gh)));break;case ge:s.rgb.assign(gu(s.rgb,i.rgb,kh.mul(Gh)));break;case pe:s.rgb.addAssign(i.rgb.mul(kh.mul(Gh)));break;default:d("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const zg=new fe;class $g extends vg{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(zg),this.setValues(e)}setupNormal(){return bc(vc)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Vg(pp)),t}setupOutgoingLight(){return Gn.rgb}setupLightingModel(){return new Gg}}const Wg=cn(({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))}),Hg=cn(e=>e.diffuseColor.mul(1/Math.PI)),qg=cn(({dotNH:e})=>aa.mul(yn(.5)).add(1).mul(yn(1/Math.PI)).mul(e.pow(aa))),jg=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(t).clamp(),s=gc.dot(t).clamp(),i=Wg({f0:sa,f90:1,dotVH:s}),n=yn(.25),a=qg({dotNH:r});return i.mul(n).mul(a)});class Xg extends Gg{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:Gn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(jg({lightDirection:e})).mul(kh))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Kg=new ye;class Qg extends vg{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Kg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg(!1)}}const Yg=new be;class Zg extends vg{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Yg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg}setupVariants(){const e=(this.shininessNode?yn(this.shininessNode):Ph).max(1e-4);aa.assign(e);const t=this.specularNode||Ih;sa.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Jg=cn(e=>{if(!1===e.geometry.hasAttribute("normal"))return yn(0);const t=vc.dFdx().abs().max(vc.dFdy().abs());return t.x.max(t.y).max(t.z)}),em=cn(e=>{const{roughness:t}=e,r=Jg();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s}),tm=cn(({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return Ua(.5,i.add(n).max(ao))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),rm=cn(({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(Rn(e.mul(r),t.mul(s),a).length()),l=a.mul(Rn(e.mul(i),t.mul(n),o).length());return Ua(.5,u.add(l).max(ao))}).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"}]}),sm=cn(({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),im=yn(1/Math.PI),nm=cn(({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=Rn(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return im.mul(n.mul(u.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"}]}),am=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Sc,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(gc).normalize(),d=n.dot(e).clamp(),c=n.dot(gc).clamp(),h=n.dot(l).clamp(),p=gc.dot(l).clamp();let g,m,f=Wg({f0:t,f90:r,dotVH:p});if(Zi(a)&&(f=Qn.mix(f,i)),Zi(o)){const t=ta.dot(e),r=ta.dot(gc),s=ta.dot(l),i=ra.dot(e),n=ra.dot(gc),a=ra.dot(l);g=rm({alphaT:Jn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=nm({alphaT:Jn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=tm({alpha:u,dotNL:d,dotNV:c}),m=sm({alpha:u,dotNH:h});return f.mul(g).mul(m)}),om=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 um=null;const lm=cn(({roughness:e,dotNV:t})=>{null===um&&(um=new xe(om,16,16,$,Te),um.name="DFG_LUT",um.minFilter=le,um.magFilter=le,um.wrapS=_e,um.wrapT=_e,um.generateMipmaps=!1,um.needsUpdate=!0);const r=_n(e,t);return Kl(um,r).rg}),dm=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=am({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),u=Sc.dot(e).clamp(),l=Sc.dot(gc).clamp(),d=lm({roughness:s,dotNV:l}),c=lm({roughness:s,dotNV:u}),h=t.mul(d.x).add(r.mul(d.y)),p=t.mul(c.x).add(r.mul(c.y)),g=d.x.add(d.y),m=c.x.add(c.y),f=yn(1).sub(g),y=yn(1).sub(m),b=t.add(t.oneMinus().mul(.047619)),x=h.mul(p).mul(b).div(yn(1).sub(f.mul(y).mul(b).mul(b)).add(ao)),T=f.mul(y),_=x.mul(T);return o.add(_)}),cm=cn(e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=lm({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))}),hm=cn(({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(Rn(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),pm=cn(({roughness:e,dotNH:t})=>{const r=e.pow2(),s=yn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return yn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),gm=cn(({dotNV:e,dotNL:t})=>yn(1).div(yn(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),mm=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(e).clamp(),s=Sc.dot(gc).clamp(),i=Sc.dot(t).clamp(),n=pm({roughness:Kn,dotNH:i}),a=gm({dotNV:s,dotNL:r});return Xn.mul(n).mul(a)}),fm=cn(({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=_n(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),ym=cn(({f:e})=>{const t=e.length();return eu(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),bm=cn(({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,eu(r.mul(r).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"}]}),xm=cn(({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=Rn().toVar();return gn(d.dot(r.sub(i)).greaterThanEqual(0),()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(Pn(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=Rn(0).toVar();f.addAssign(bm({v1:h,v2:p})),f.addAssign(bm({v1:p,v2:g})),f.addAssign(bm({v1:g,v2:m})),f.addAssign(bm({v1:m,v2:h})),c.assign(Rn(ym({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Tm=cn(({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=Rn().toVar();return gn(o.dot(e.sub(t)).greaterThanEqual(0),()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=Rn(0).toVar();d.addAssign(bm({v1:n,v2:a})),d.addAssign(bm({v1:a,v2:o})),d.addAssign(bm({v1:o,v2:l})),d.addAssign(bm({v1:l,v2:n})),u.assign(Rn(ym({f:d.abs()})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),_m=1/6,vm=e=>Da(_m,Da(e,Da(e,e.negate().add(3)).sub(3)).add(1)),Nm=e=>Da(_m,Da(e,Da(e,Da(3,e).sub(6))).add(4)),Sm=e=>Da(_m,Da(e,Da(e,Da(-3,e).add(3)).add(3)).add(1)),Rm=e=>Da(_m,ou(e,3)),Em=e=>vm(e).add(Nm(e)),Am=e=>Sm(e).add(Rm(e)),wm=e=>Fa(-1,Nm(e).div(vm(e).add(Nm(e)))),Cm=e=>Fa(1,Rm(e).div(Sm(e).add(Rm(e)))),Mm=(e,t,r)=>{const s=e.uvNode,i=Da(s,t.zw).add(.5),n=No(i),a=Eo(i),o=Em(a.x),u=Am(a.x),l=wm(a.x),d=Cm(a.x),c=wm(a.y),h=Cm(a.y),p=_n(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=_n(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=_n(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=_n(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Em(a.y).mul(Fa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Am(a.y).mul(Fa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},Bm=cn(([e,t])=>{const r=_n(e.size(bn(t))),s=_n(e.size(bn(t.add(1)))),i=Ua(1,r),n=Ua(1,s),a=Mm(e,Cn(i,r),No(t)),o=Mm(e,Cn(n,s),So(t));return Eo(t).mix(a,o)}),Lm=cn(([e,t])=>{const r=t.mul(Wl(e));return Bm(e,r)}),Fm=cn(([e,t,r,s,i])=>{const n=Rn(yu(t.negate(),Ro(e),Ua(1,s))),a=Rn(Go(i[0].xyz),Go(i[1].xyz),Go(i[2].xyz));return Ro(n).mul(r.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"}]}),Pm=cn(([e,t])=>e.mul(mu(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Dm=qp(),Um=Xp(),Im=cn(([e,t,r],{material:s})=>{const i=(s.side===F?Dm:Um).sample(e),n=To(ld.x).mul(Pm(t,r));return Bm(i,n)}),Om=cn(([e,t,r])=>(gn(r.notEqual(0),()=>{const s=xo(t).negate().div(r);return yo(s.negate().mul(e))}),Rn(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Vm=cn(([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=Cn().toVar(),f=Rn().toVar();const i=d.sub(1).mul(g.mul(.025)),n=Rn(d.sub(i),d,d.add(i));Bp({start:0,end:3},({i:i})=>{const d=n.element(i),g=Fm(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(Cn(y,1))),x=_n(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(_n(x.x,x.y.oneMinus()));const T=Im(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(Om(Go(g),h,p).element(i)))}),m.a.divAssign(3)}else{const i=Fm(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(Cn(n,1))),y=_n(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(_n(y.x,y.y.oneMinus())),m=Im(y,r,d),f=s.mul(Om(Go(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=Rn(cm({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return Cn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())}),km=Pn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Gm=(e,t)=>e.sub(t).div(e.add(t)).pow2(),zm=cn(({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=gu(e,t,bu(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();gn(a.lessThan(0),()=>Rn(1));const o=a.sqrt(),u=Gm(n,e),l=Wg({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=yn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Rn(1).add(t).div(Rn(1).sub(t))})(i.clamp(0,.9999)),g=Gm(p,n.toVec3()),m=Wg({f0:g,f90:1,dotVH:o}),f=Rn(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=Rn(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(Rn(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Bp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=Rn(54856e-17,44201e-17,52481e-17),i=Rn(1681e3,1795300,2208400),n=Rn(43278e5,93046e5,66121e5),a=yn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=Rn(o.x.add(a),o.y,o.z).div(1.0685e-7),km.mul(o)})(yn(e).mul(y),yn(e).mul(b)).mul(2);v.addAssign(N.mul(t))}),v.max(Rn(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"}]}),$m=cn(({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.mul(r),n=r.add(.1).reciprocal(),a=yn(-1.9362).add(r.mul(1.0678)).add(i.mul(.4573)).sub(n.mul(.8469)),o=yn(-.6014).add(r.mul(.5538)).sub(i.mul(.467)).sub(n.mul(.1255));return a.mul(s).add(o).exp().saturate()}),Wm=Rn(.04),Hm=yn(1);class qm extends kg{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Rn().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Rn().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Rn().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Rn().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Rn().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Sc.dot(gc).clamp(),t=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:sa}),r=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:Gn.rgb});this.iridescenceFresnel=gu(t,r,Hn),this.iridescenceF0Dielectric=hm({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=hm({f:r,f90:1,dotVH:e}),this.iridescenceF0=gu(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Hn)}if(!0===this.transmission){const t=cc,r=Od.sub(cc).normalize(),s=Rc,i=e.context;i.backdrop=Vm(s,r,Wn,zn,ia,na,t,Qd,Dd,Fd,ca,pa,ma,ga,this.dispersion?fa:null),i.backdropAlpha=ha,Gn.a.mulAssign(gu(1,i.backdrop.a,ha))}super.start(e)}computeMultiscattering(e,t,r,s,i=null){const n=Sc.dot(gc).clamp(),a=lm({roughness:Wn,dotNV:n}),o=i?Qn.mix(s,i):s,u=o.mul(a.x).add(r.mul(a.y)),l=a.x.add(a.y).oneMinus(),d=o.add(o.oneMinus().mul(.047619)),c=u.mul(d).div(l.mul(d).oneMinus());e.addAssign(u),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(s.mul(mm({lightDirection:e})));const t=$m({normal:Sc,viewDir:gc,roughness:Kn}),r=$m({normal:Sc,viewDir:e,roughness:Kn}),i=Xn.r.max(Xn.g).max(Xn.b).mul(t.max(r)).oneMinus();s.mulAssign(i)}if(!0===this.clearcoat){const r=Ec.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(am({lightDirection:e,f0:Wm,f90:Hm,roughness:jn,normalView:Ec})))}r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:zn}))),r.directSpecular.addAssign(s.mul(dm({lightDirection:e,f0:ia,f90:1,roughness:Wn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Sc,h=gc,p=pc.toVar(),g=fm({N:c,V:h,roughness:Wn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=Pn(Rn(m.x,0,m.y),Rn(0,1,0),Rn(m.z,0,m.w)).toVar(),b=ia.mul(f.x).add(na.sub(ia).mul(f.y)).toVar();if(i.directSpecular.addAssign(e.mul(b).mul(xm({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(zn).mul(xm({N:c,V:h,P:p,mInv:Pn(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d}))),!0===this.clearcoat){const t=Ec,r=fm({N:t,V:h,roughness:jn}),s=n.sample(r),i=a.sample(r),c=Pn(Rn(s.x,0,s.y),Rn(0,1,0),Rn(s.z,0,s.w)),g=Wm.mul(i.x).add(Hm.sub(Wm).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(g).mul(xm({N:t,V:h,P:p,mInv:c,p0:o,p1:u,p2:l,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context,s=t.mul(Hg({diffuseColor:zn})).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();s.mulAssign(t)}r.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Xn,$m({normal:Sc,viewDir:gc,roughness:Kn}))),!0===this.clearcoat){const e=Ec.dot(gc).clamp(),t=cm({dotNV:e,specularColor:Wm,specularF90:Hm,roughness:jn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Rn().toVar("singleScatteringDielectric"),n=Rn().toVar("multiScatteringDielectric"),a=Rn().toVar("singleScatteringMetallic"),o=Rn().toVar("multiScatteringMetallic");this.computeMultiscattering(i,n,na,sa,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,na,Gn.rgb,this.iridescenceF0Metallic);const u=gu(i,a,Hn),l=gu(n,o,Hn),d=i.add(n),c=zn.mul(d.oneMinus()),h=r.mul(1/Math.PI),p=t.mul(u).add(l.mul(h)).toVar(),g=c.mul(h).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();p.mulAssign(t),g.mulAssign(t)}s.indirectSpecular.addAssign(p),s.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Sc.dot(gc).clamp().add(t),i=Wn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ec.dot(gc).clamp(),r=Wg({dotVH:e,f0:Wm,f90:Hm}),s=t.mul(qn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(qn));t.assign(s)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const jm=yn(1),Xm=yn(-2),Km=yn(.8),Qm=yn(-1),Ym=yn(.4),Zm=yn(2),Jm=yn(.305),ef=yn(3),tf=yn(.21),rf=yn(4),sf=yn(4),nf=yn(16),af=cn(([e])=>{const t=Rn(Vo(e)).toVar(),r=yn(-1).toVar();return gn(t.x.greaterThan(t.z),()=>{gn(t.x.greaterThan(t.y),()=>{r.assign(Au(e.x.greaterThan(0),0,3))}).Else(()=>{r.assign(Au(e.y.greaterThan(0),1,4))})}).Else(()=>{gn(t.z.greaterThan(t.y),()=>{r.assign(Au(e.z.greaterThan(0),2,5))}).Else(()=>{r.assign(Au(e.y.greaterThan(0),1,4))})}),r}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),of=cn(([e,t])=>{const r=_n().toVar();return gn(t.equal(0),()=>{r.assign(_n(e.z,e.y).div(Vo(e.x)))}).ElseIf(t.equal(1),()=>{r.assign(_n(e.x.negate(),e.z.negate()).div(Vo(e.y)))}).ElseIf(t.equal(2),()=>{r.assign(_n(e.x.negate(),e.y).div(Vo(e.z)))}).ElseIf(t.equal(3),()=>{r.assign(_n(e.z.negate(),e.y).div(Vo(e.x)))}).ElseIf(t.equal(4),()=>{r.assign(_n(e.x.negate(),e.z).div(Vo(e.y)))}).Else(()=>{r.assign(_n(e.x,e.y).div(Vo(e.z)))}),Da(.5,r.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),uf=cn(([e])=>{const t=yn(0).toVar();return gn(e.greaterThanEqual(Km),()=>{t.assign(jm.sub(e).mul(Qm.sub(Xm)).div(jm.sub(Km)).add(Xm))}).ElseIf(e.greaterThanEqual(Ym),()=>{t.assign(Km.sub(e).mul(Zm.sub(Qm)).div(Km.sub(Ym)).add(Qm))}).ElseIf(e.greaterThanEqual(Jm),()=>{t.assign(Ym.sub(e).mul(ef.sub(Zm)).div(Ym.sub(Jm)).add(Zm))}).ElseIf(e.greaterThanEqual(tf),()=>{t.assign(Jm.sub(e).mul(rf.sub(ef)).div(Jm.sub(tf)).add(ef))}).Else(()=>{t.assign(yn(-2).mul(To(Da(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),lf=cn(([e,t])=>{const r=e.toVar();r.assign(Da(2,r).sub(1));const s=Rn(r,1).toVar();return gn(t.equal(0),()=>{s.assign(s.zyx)}).ElseIf(t.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),df=cn(([e,t,r,s,i,n])=>{const a=yn(r),o=Rn(t),u=mu(uf(a),Xm,n),l=Eo(u),d=No(u),c=Rn(cf(e,o,d,s,i,n)).toVar();return gn(l.notEqual(0),()=>{const t=Rn(cf(e,o,d.add(1),s,i,n)).toVar();c.assign(gu(c,t,l))}),c}),cf=cn(([e,t,r,s,i,n])=>{const a=yn(r).toVar(),o=Rn(t),u=yn(af(o)).toVar(),l=yn(eu(sf.sub(a),0)).toVar();a.assign(eu(a,sf));const d=yn(bo(a)).toVar(),c=_n(of(o,u).mul(d.sub(2)).add(1)).toVar();return gn(u.greaterThan(2),()=>{c.y.addAssign(d),u.subAssign(3)}),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(Da(3,nf))),c.y.addAssign(Da(4,bo(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(_n(),_n())}),hf=cn(({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Co(s),l=r.mul(u).add(i.cross(r).mul(Ao(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return cf(e,l,t,n,a,o)}),pf=cn(({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=Rn(Au(t,r,au(r,s))).toVar();gn(h.equal(Rn(0)),()=>{h.assign(Rn(s.z,0,s.x.negate()))}),h.assign(Ro(h));const p=Rn().toVar();return p.addAssign(i.element(0).mul(hf({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Bp({start:bn(1),end:e},({i:e})=>{gn(e.greaterThanEqual(n),()=>{Lp()});const t=yn(a.mul(yn(e))).toVar();p.addAssign(i.element(e).mul(hf({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(hf({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))}),Cn(p,1)}),gf=cn(([e])=>{const t=xn(e).toVar();return t.assign(t.shiftLeft(xn(16)).bitOr(t.shiftRight(xn(16)))),t.assign(t.bitAnd(xn(1431655765)).shiftLeft(xn(1)).bitOr(t.bitAnd(xn(2863311530)).shiftRight(xn(1)))),t.assign(t.bitAnd(xn(858993459)).shiftLeft(xn(2)).bitOr(t.bitAnd(xn(3435973836)).shiftRight(xn(2)))),t.assign(t.bitAnd(xn(252645135)).shiftLeft(xn(4)).bitOr(t.bitAnd(xn(4042322160)).shiftRight(xn(4)))),t.assign(t.bitAnd(xn(16711935)).shiftLeft(xn(8)).bitOr(t.bitAnd(xn(4278255360)).shiftRight(xn(8)))),yn(t).mul(2.3283064365386963e-10)}),mf=cn(([e,t])=>_n(yn(e).div(yn(t)),gf(e))),ff=cn(([e,t,r])=>{const s=r.mul(r).toConst(),i=Rn(1,0,0).toConst(),n=au(t,i).toConst(),a=_o(e.x).toConst(),o=Da(2,3.14159265359).mul(e.y).toConst(),u=a.mul(Co(o)).toConst(),l=a.mul(Ao(o)).toVar(),d=Da(.5,t.z.add(1)).toConst();l.assign(d.oneMinus().mul(_o(u.mul(u).oneMinus())).add(d.mul(l)));const c=i.mul(u).add(n.mul(l)).add(t.mul(_o(eu(0,u.mul(u).add(l.mul(l)).oneMinus()))));return Ro(Rn(s.mul(c.x),s.mul(c.y),eu(0,c.z)))}),yf=cn(({roughness:e,mipInt:t,envMap:r,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Rn(s).toVar(),l=Rn(0).toVar(),d=yn(0).toVar();return gn(e.lessThan(.001),()=>{l.assign(cf(r,u,t,n,a,o))}).Else(()=>{const s=Au(Vo(u.z).lessThan(.999),Rn(0,0,1),Rn(1,0,0)),c=Ro(au(s,u)).toVar(),h=au(u,c).toVar();Bp({start:xn(0),end:i},({i:s})=>{const p=mf(s,i),g=ff(p,Rn(0,0,1),e),m=Ro(c.mul(g.x).add(h.mul(g.y)).add(u.mul(g.z))),f=Ro(m.mul(nu(u,m).mul(2)).sub(u)),y=eu(nu(u,f),0);gn(y.greaterThan(0),()=>{const e=cf(r,f,t,n,a,o);l.addAssign(e.mul(y)),d.addAssign(y)})}),gn(d.greaterThan(0),()=>{l.assign(l.div(d))})}),Cn(l,1)}),bf=[.125,.215,.35,.446,.526,.582],xf=20,Tf=new Ne(-1,1,1,-1,0,1),_f=new Se(90,1),vf=new e;let Nf=null,Sf=0,Rf=0;const Ef=new r,Af=new WeakMap,wf=[3,1,5,0,4,2],Cf=lf(kl(),Vl("faceIndex")).normalize(),Mf=Rn(Cf.x,Cf.y,Cf.z);class Bf{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Ef,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){d('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}Nf=this._renderer.getRenderTarget(),Sf=this._renderer.getActiveCubeFace(),Rf=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget();return u.depthBuffer=!0,this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return v('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){d('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return v('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){d("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return v('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Df(),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===U||e.mapping===I?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;ee-4?o=bf[a-e+4-1]:0===a&&(o=0),r.push(o);const u=1/(n-2),l=-u,d=1+u,c=[l,l,d,l,d,d,l,l,d,d,l,d],h=6,p=6,g=3,m=2,f=1,y=new Float32Array(g*p*h),b=new Float32Array(m*p*h),x=new Float32Array(f*p*h);for(let e=0;e2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=wf[e];y.set(s,g*p*i),b.set(c,m*p*i);const n=[i,i,i,i,i,i];x.set(n,f*p*i)}const T=new ve;T.setAttribute("position",new we(y,g)),T.setAttribute("uv",new we(b,m)),T.setAttribute("faceIndex",new we(x,f)),s.push(new oe(T,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t,sigmas:r}}(t)),this._blurMaterial=function(e,t,s){const i=td(new Array(xf).fill(0)),n=Sa(new r(0,1,0)),a=Sa(0),o=yn(xf),u=Sa(0),l=Sa(1),d=Kl(),c=Sa(0),h=yn(1/t),p=yn(1/s),g=yn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:Mf,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Ff("blur");return f.fragmentNode=pf({...m,latitudinal:u.equal(1)}),Af.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,r){const s=Kl(),i=Sa(0),n=Sa(0),a=yn(1/t),o=yn(1/r),u=yn(e),l={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:u},d=Ff("ggx");return d.fragmentNode=yf({...l,N_immutable:Mf,GGX_SAMPLES:xn(512)}),Af.set(d,l),d}(t,e.width,e.height)}}async _compileMaterial(e){const t=new oe(new ve,e);await this._renderer.compile(t,Tf)}_sceneToCubeUV(e,t,r,s,i){const n=_f;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(vf),u.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new oe(new ae,new fe({name:"PMREM.Background",side:F,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,c=d.material;let h=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,h=!0):(c.color.copy(vf),h=!0),u.setRenderTarget(s),u.clear(),h&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;this._setViewport(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=p}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===U||e.mapping===I;s?null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(e)):null===this._equirectMaterial&&(this._equirectMaterial=Df(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,Tf)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let t=1;tc-4?r-c+4:0),g=4*(this._cubeSize-h);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=d,o.mipInt.value=c-t,this._setViewport(i,p,g,3*h,2*h),s.setRenderTarget(i),s.render(a,Tf),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=c-r,this._setViewport(e,p,g,3*h,2*h),s.setRenderTarget(e),s.render(a,Tf)}_blur(e,t,r,s,i){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,r,s,"latitudinal",i),this._halfBlur(n,e,r,r,s,"longitudinal",i)}_halfBlur(e,t,r,s,i,n,a){const u=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&o("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[s];c.material=l;const h=Af.get(l),p=this._sizeLods[r]-1,g=isFinite(i)?Math.PI/(2*p):2*Math.PI/39,m=i/g,f=isFinite(i)?1+Math.floor(3*m):xf;f>xf&&d(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const y=[];let b=0;for(let e=0;ex-4?s-x+4:0),v=4*(this._cubeSize-T);this._setViewport(t,_,v,3*T,2*T),u.setRenderTarget(t),u.render(c,Tf)}_setViewport(e,t,r,s,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-r,s,i),e.scissor.set(t,e.height-i-r,s,i)):(e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i))}}function Lf(e,t){const r=new ne(e,t,{magFilter:le,minFilter:le,generateMipmaps:!1,type:Te,format:Ee,colorSpace:Re});return r.texture.mapping=Ae,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Ff(e){const t=new vg;return t.depthTest=!1,t.depthWrite=!1,t.blending=re,t.name=`PMREM_${e}`,t}function Pf(e){const t=Ff("cubemap");return t.fragmentNode=$c(e,Mf),t}function Df(e){const t=Ff("equirect");return t.fragmentNode=Kl(e,Bg(Mf),0),t}const Uf=new WeakMap;function If(e,t,r){const s=function(e){let t=Uf.get(e);void 0===t&&(t=new WeakMap,Uf.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s0}(t))return null;i=r.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,s.set(e,i)}return i.texture}class Of extends gi{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new N;s.isRenderTargetTexture=!0,this._texture=Kl(s),this._width=Sa(0),this._height=Sa(0),this._maxMip=Sa(0),this.updateBeforeType=ri.RENDER}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,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,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 r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture?s:If(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Bf(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Dc.mul(Rn(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),df(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Vf=an(Of).setParameterLength(1,3),kf=new WeakMap;class Gf extends Op{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const s=r.isTextureNode?r.value:t[r.property],i=this._getPMREMNodeCache(e.renderer);let n=i.get(s);void 0===n&&(n=Vf(s),i.set(s,n)),r=n}const s=!0===t.useAnisotropy||t.anisotropy>0?_h:Sc,i=r.context(zf(Wn,s)).mul(Pc),n=r.context($f(Rc)).mul(Math.PI).mul(Pc),a=vl(i),o=vl(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(zf(jn,Ec)).mul(Pc),t=vl(e);u.addAssign(t)}}_getPMREMNodeCache(e){let t=kf.get(e);return void 0===t&&(t=new WeakMap,kf.set(e,t)),t}}const zf=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=gc.negate().reflect(t),r=du(e).mix(r,t).normalize(),r=r.transformDirection(Dd)),r),getTextureLevel:()=>e}},$f=e=>({getUV:()=>e,getTextureLevel:()=>yn(1)}),Wf=new Ce;class Hf extends vg{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(Wf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Gf(t):null}setupLightingModel(){return new qm}setupSpecular(){const e=gu(Rn(.04),Gn.rgb,Hn);sa.assign(Rn(.04)),ia.assign(e),na.assign(1)}setupVariants(){const e=this.metalnessNode?yn(this.metalnessNode):$h;Hn.assign(e);let t=this.roughnessNode?yn(this.roughnessNode):zh;t=em({roughness:t}),Wn.assign(t),this.setupSpecular(),zn.assign(Gn.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const qf=new Me;class jf extends Hf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(qf),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?yn(this.iorNode):sp;ca.assign(e),sa.assign(Jo(uu(ca.sub(1).div(ca.add(1))).mul(Vh),Rn(1)).mul(Oh)),ia.assign(gu(sa,Gn.rgb,Hn)),na.assign(gu(Oh,1,Hn))}setupLightingModel(){return new qm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?yn(this.clearcoatNode):Hh,t=this.clearcoatRoughnessNode?yn(this.clearcoatRoughnessNode):qh;qn.assign(e),jn.assign(em({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Rn(this.sheenNode):Kh,t=this.sheenRoughnessNode?yn(this.sheenRoughnessNode):Qh;Xn.assign(e),Kn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?yn(this.iridescenceNode):Zh,t=this.iridescenceIORNode?yn(this.iridescenceIORNode):Jh,r=this.iridescenceThicknessNode?yn(this.iridescenceThicknessNode):ep;Qn.assign(e),Yn.assign(t),Zn.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?_n(this.anisotropyNode):Yh).toVar();ea.assign(e.length()),gn(ea.equal(0),()=>{e.assign(_n(1,0))}).Else(()=>{e.divAssign(_n(ea)),ea.assign(ea.saturate())}),Jn.assign(ea.pow2().mix(Wn.pow2(),1)),ta.assign(xh[0].mul(e.x).add(xh[1].mul(e.y))),ra.assign(xh[1].mul(e.x).sub(xh[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?yn(this.transmissionNode):tp,t=this.thicknessNode?yn(this.thicknessNode):rp,r=this.attenuationDistanceNode?yn(this.attenuationDistanceNode):ip,s=this.attenuationColorNode?Rn(this.attenuationColorNode):np;if(ha.assign(e),pa.assign(t),ga.assign(r),ma.assign(s),this.useDispersion){const e=this.dispersionNode?yn(this.dispersionNode):hp;fa.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Rn(this.clearcoatNormalNode):jh}setup(e){e.context.setupClearcoatNormal=()=>Gu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}class Xf extends qm{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Sc.mul(a)).normalize(),h=yn(gc.dot(c.negate()).saturate().pow(l).mul(d)),p=Rn(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Kf extends jf{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=yn(.1),this.thicknessAmbientNode=yn(0),this.thicknessAttenuationNode=yn(.1),this.thicknessPowerNode=yn(2),this.thicknessScaleNode=yn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Xf(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}copy(e){return this.thicknessColorNode=e.thicknessColorNode,this.thicknessDistortionNode=e.thicknessDistortionNode,this.thicknessAmbientNode=e.thicknessAmbientNode,this.thicknessAttenuationNode=e.thicknessAttenuationNode,this.thicknessPowerNode=e.thicknessPowerNode,this.thicknessScaleNode=e.thicknessScaleNode,super.copy(e)}}const Qf=cn(({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=_n(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Kc("gradientMap","texture").context({getUV:()=>i});return Rn(e.r)}{const e=i.fwidth().mul(.5);return gu(Rn(.7),Rn(1),bu(yn(.7).sub(e.x),yn(.7).add(e.x),i.x))}});class Yf extends kg{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Qf({normal:xc,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Hg({diffuseColor:Gn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Zf=new Be;class Jf extends vg{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Zf),this.setValues(e)}setupLightingModel(){return new Yf}}const ey=cn(()=>{const e=Rn(gc.z,0,gc.x.negate()).normalize(),t=gc.cross(e);return _n(e.dot(Sc),t.dot(Sc)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),ty=new Le;class ry extends vg{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupVariants(e){const t=ey;let r;r=e.material.matcap?Kc("matcap","texture").context({getUV:()=>t}):Rn(gu(.2,.8,t.y)),Gn.rgb.mulAssign(r.rgb)}}class sy extends gi{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return Fn(e,s,s.negate(),e).mul(r)}{const e=t,s=Dn(Cn(1,0,0,0),Cn(0,Co(e.x),Ao(e.x).negate(),0),Cn(0,Ao(e.x),Co(e.x),0),Cn(0,0,0,1)),i=Dn(Cn(Co(e.y),0,Ao(e.y),0),Cn(0,1,0,0),Cn(Ao(e.y).negate(),0,Co(e.y),0),Cn(0,0,0,1)),n=Dn(Cn(Co(e.z),Ao(e.z).negate(),0,0),Cn(Ao(e.z),Co(e.z),0,0),Cn(0,0,1,0),Cn(0,0,0,1));return s.mul(i).mul(n).mul(Cn(r,1)).xyz}}}const iy=an(sy).setParameterLength(2),ny=new Fe;class ay extends vg{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ny),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=sc.mul(Rn(s||0));let u=_n(Qd[0].xyz.length(),Qd[1].xyz.length());null!==n&&(u=u.mul(_n(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=uc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>new Zu(e,t,r))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=yn(i||Xh),c=iy(l,d);return Cn(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const oy=new Pe,uy=new t;class ly extends ay{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(oy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return sc.mul(Rn(e||lc)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?_n(n):cp;u=u.mul(od),r.isPerspectiveCamera&&!0===a&&(u=u.mul(dy.div(pc.z.negate()))),i&&i.isNode&&(u=u.mul(_n(i)));let l=uc.xy;if(s&&s.isNode){const e=yn(s);l=iy(l,e)}return l=l.mul(u),l=l.div(hd.div(2)),l=l.mul(o.w),o=o.add(Cn(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const dy=Sa(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(uy);this.value=.5*t.y});class cy extends kg{constructor(){super(),this.shadowNode=yn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Gn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Gn.rgb)}}const hy=new De;class py extends vg{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(hy),this.setValues(e)}setupLightingModel(){return new cy}}const gy=Vn("vec3"),my=Vn("vec3"),fy=Vn("vec3");class yy extends kg{constructor(){super()}start(e){const{material:t}=e,r=Vn("vec3"),s=Vn("vec3");gn(Od.sub(cc).length().greaterThan(ec.mul(2)),()=>{r.assign(Od),s.assign(cc)}).Else(()=>{r.assign(cc),s.assign(Od)});const i=s.sub(r),n=Sa("int").onRenderUpdate(({material:e})=>e.steps),a=i.length().div(n).toVar(),o=i.normalize().toVar(),u=yn(0).toVar(),l=Rn(1).toVar();t.offsetNode&&u.addAssign(t.offsetNode.mul(a)),Bp(n,()=>{const s=r.add(o.mul(u)),i=Dd.mul(Cn(s,1)).xyz;let n;null!==t.depthNode&&(my.assign(og(tg(i.z,Bd,Ld))),e.context.sceneDepthNode=og(t.depthNode).toVar()),e.context.positionWorld=s,e.context.shadowPositionWorld=s,e.context.positionView=i,gy.assign(0),t.scatteringNode&&(n=t.scatteringNode({positionRay:s})),super.start(e),n&&gy.mulAssign(n);const d=gy.mul(.01).negate().mul(a).exp();l.mulAssign(d),u.addAssign(a)}),fy.addAssign(l.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?gn(r.greaterThanEqual(my),()=>{gy.addAssign(e)}):gy.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(void 0===e.light.distance)return;const s=t.xyz.toVar();s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul(Tm({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(fy)}}class by extends vg{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=F,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new yy}}class xy{constructor(e,t,r){this.renderer=e,this.nodes=t,this.info=r,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,r),this.renderer._inspector.finish()};e()}stop(){null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Ty{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let r=this.weakMaps[t];return void 0===r&&(r=new WeakMap,this.weakMaps[t]=r),r}get(e){let t=this._getWeakMap(e);for(let r=0;r{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),i[n.name]=e.id),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e1||Array.isArray(e.morphTargetInfluences))&&(s+=e.uuid+","),s+=this.context.id+",",s+=e.receiveShadow+",",Vs(s)}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 r=this.geometry.getAttribute(t);if(void 0===r||e[t]!==r.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Gs(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Gs(e,1)),e=Gs(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Ny=[];class Sy{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);Ny[0]=e,Ny[1]=t,Ny[2]=n,Ny[3]=i;let l=u.get(Ny);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Ny,l)):(l.camera=s,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Ny[0]=null,Ny[1]=null,Ny[2]=null,Ny[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Ty)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new vy(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.deleteForRender(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Ry{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 Ey=1,Ay=2,wy=3,Cy=4,My=16;class By extends Ry{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 r=this.get(e);if(void 0===r.version)t===Ey?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ay?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===wy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Cy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version=65535?Ue:Ie)(t,1);return i.version=Ly(e),i.__id=Fy(e),i}class Dy extends Ry{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 r=()=>{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,wy):this.updateAttribute(e,Ey);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,Ay);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,Cy)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=Py(t),e.set(t,r)):r.version===Ly(t)&&r.__id===Fy(t)||(this.attributes.delete(r),r=Py(t),e.set(t,r)),s=r}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Uy{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,r){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=r*(t/3):e.isPoints?this.render.points+=r*t:e.isLineSegments?this.render.lines+=r*(t/2):e.isLine?this.render.lines+=r*(t-1):o("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const r=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:r,type:t}),this.memory[t]++,this.memory.total+=r,this.memory[t+"Size"]+=r}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=this._getAttributeMemorySize(e.attribute);this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){this.destroyAttribute(e)}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===Oe||e.type===Ve?t=1:e.type===ke||e.type===Ge||e.type===Te?t=2:e.type!==R&&e.type!==S&&e.type!==K||(t=4);let r=4;e.format===ze||e.format===$e||e.format===We||e.format===He||e.format===qe?r=1:e.format===$||e.format===je?r=2:e.format!==Xe&&e.format!==Ke||(r=3);let s=t*r;e.type===Qe||e.type===Ye?s=2:e.type!==Ze&&e.type!==Je&&e.type!==et||(s=4);const i=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=i*n*a*s;const u=e.mipmaps;if(u&&u.length>0){let e=0;for(let t=0;t>t))*(r.height||Math.max(1,n>>t))*a*s}}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 Iy{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Oy extends Iy{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Vy extends Iy{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let ky=0;class Gy{constructor(e,t,r,s=null,i=null){this.id=ky++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class zy extends Ry{constructor(e,t,r){super(),this.backend=e,this.nodes=t,this.info=r,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new Gy(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new Gy(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o),this.info.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new Gy(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u),this.info.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const r=this.backend.get(t);return void 0!==r.pipeline&&null!==r.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,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new Vy(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new Oy(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].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 $y extends Ry{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?Cy:wy;this.attributes.update(e,r)}}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,i=e.isIndirectStorageBufferAttribute?Cy:wy,n=r.get(t);this.attributes.update(e,i),n.attribute!==e&&(n.attribute=e,s=!0)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),u=t.texture,l=this.textures.get(u);o&&(this.textures.updateTexture(u),t.generation!==l.generation&&(t.generation=l.generation,s=!0),l.bindGroups.add(e));if(void 0!==r.get(u).externalTexture||l.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===u.isStorageTexture&&!0===u.mipmapsAutoUpdate){const e=this.get(u);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(u)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(u),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,s=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function Wy(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 Hy(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 qy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===P&&!1===e.forceSinglePass}class jy{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,r),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&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||Wy),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Hy),this.transparent.length>1&&this.transparent.sort(t||Hy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&d&&(l=new Z,l.format=e.stencilBuffer?qe:He,l.type=e.stencilBuffer?Ze:S,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=l),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=l.isArrayTexture?l.image.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const h={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener("dispose",r.onDispose))}updateTexture(e,t={}){const r=this.get(e);if(!0===r.initialized&&r.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(s&&!0===r.initialized&&i.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:Ve}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;"requestPaint"in t&&(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image))}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),r.generation=e.version;else if(e.version>0){const s=e.image;if(void 0===s)d("Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)d("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version;!0!==r.initialized&&(r.initialized=!0,r.generation=e.version,r.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===p.enabled&&p.getTransfer(e.colorSpace)!==g&&d("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),r.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",r.onDispose)),r.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=eb){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),e.isHTMLTexture?(t.width=r.offsetWidth||1,t.height=r.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),r=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e=2)for(let r=0;r{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===s)t.build(e);else if("analyze"===s)t.build(e,this);else if("generate"===s){const r=e.getDataFromNode(t,"any").stages,s=r&&r[e.shaderStage];if(t.isVarNode&&s&&1===s.length&&s[0]&&s[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)i(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)i(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),hn(r),e.removeActiveStack(this),o}}const nb=an(ib).setParameterLength(0,1);class ab extends ci{static get type(){return"StructTypeNode"}constructor(e,t=null){var r;super("struct"),this.membersLayout=(r=e,Object.entries(r).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,r=0;for(const s of this.membersLayout){const i=s.type,n=js(i),a=Xs(i)/e;t=Math.max(t,a);const o=r%t%a;0!==o&&(r+=a-o),r+=n}return Math.ceil(r/t)*t}getMemberType(e,t){const r=this.membersLayout.find(e=>e.name===t);return r?r.type:"void"}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class ob extends ci{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){const e=super._getChildren(),t=e.find(e=>e.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class ub extends ci{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}generateNodeType(){return"OutputType"}generate(e){const t=e.getDataFromNode(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;tnew fb(e,"uint","float"),xb={};class Tb extends no{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,r){"int"===r?t.assign(yb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return xn;case"int":return bn;case"uvec2":return Nn;case"uvec3":return An;case"uvec4":return Bn;case"ivec2":return vn;case"ivec3":return En;case"ivec4":return Mn}}_createTrailingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t);const i=yn(s.bitAnd(zo(s))),n=bb(i).shiftRight(23).sub(127);return r(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{gn(e.equal(xn(0)),()=>xn(32));const s=xn(0),i=xn(0);return this._resolveElementType(e,s,t),gn(s.shiftRight(16).equal(0),()=>{i.addAssign(16),s.shiftLeftAssign(16)}),gn(s.shiftRight(24).equal(0),()=>{i.addAssign(8),s.shiftLeftAssign(8)}),gn(s.shiftRight(28).equal(0),()=>{i.addAssign(4),s.shiftLeftAssign(4)}),gn(s.shiftRight(30).equal(0),()=>{i.addAssign(2),s.shiftLeftAssign(2)}),gn(s.shiftRight(31).equal(0),()=>{i.addAssign(1)}),r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t),s.assign(s.sub(s.shiftRight(xn(1)).bitAnd(xn(1431655765)))),s.assign(s.bitAnd(xn(858993459)).add(s.shiftRight(xn(2)).bitAnd(xn(858993459))));const i=s.add(s.shiftRight(xn(4))).bitAnd(xn(252645135)).mul(xn(16843009)).shiftRight(xn(24));return r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,r,s){const i=this._returnDataNode(t);return cn(([e])=>{if(1===r)return i(s(e));{const t=i(0),n=["x","y","z","w"];for(let i=0;id(r))()}}Tb.COUNT_TRAILING_ZEROS="countTrailingZeros",Tb.COUNT_LEADING_ZEROS="countLeadingZeros",Tb.COUNT_ONE_BITS="countOneBits";const _b=un(Tb,Tb.COUNT_TRAILING_ZEROS).setParameterLength(1),vb=un(Tb,Tb.COUNT_LEADING_ZEROS).setParameterLength(1),Nb=un(Tb,Tb.COUNT_ONE_BITS).setParameterLength(1),Sb=cn(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)}),Rb=(e,t)=>ou(Da(4,e.mul(Pa(1,e))),t);class Eb extends gi{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}generateNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const Ab=un(Eb,"snorm").setParameterLength(1),wb=un(Eb,"unorm").setParameterLength(1),Cb=un(Eb,"float16").setParameterLength(1);class Mb extends gi{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}generateNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const Bb=un(Mb,"snorm").setParameterLength(1),Lb=un(Mb,"unorm").setParameterLength(1),Fb=un(Mb,"float16").setParameterLength(1),Pb=cn(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Db=cn(([e])=>Rn(Pb(e.z.add(Pb(e.y.mul(1)))),Pb(e.z.add(Pb(e.x.mul(1)))),Pb(e.y.add(Pb(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Ub=cn(([e,t,r])=>{const s=Rn(e).toVar(),i=yn(1.4).toVar(),n=yn(0).toVar(),a=Rn(s).toVar();return Bp({start:yn(0),end:yn(3),type:"float",condition:"<="},()=>{const e=Rn(Db(a.mul(2))).toVar();s.addAssign(e.add(r.mul(yn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=yn(Pb(s.z.add(Pb(s.x.add(Pb(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class Ib extends ci{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let r=this._candidateFn;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;ri&&(s=r,i=n)}}this._candidateFn=r=s}return r}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const Ob=an(Ib),Vb=e=>(...t)=>Ob(e,...t),kb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.time),Gb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.deltaTime),zb=Sa(0,"uint").setGroup(_a).onRenderUpdate(e=>e.frameId);const $b=cn(([e,t,r=_n(.5)])=>iy(e.sub(r),t).add(r)),Wb=cn(([e,t,r=_n(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))}),Hb=cn(({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=Qd.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=Qd;const i=Dd.mul(s);return Zi(t)&&(i[0][0]=Qd[0].length(),i[0][1]=0,i[0][2]=0),Zi(r)&&(i[1][0]=0,i[1][1]=Qd[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,Fd.mul(i).mul(lc)}),qb=cn(([e=null])=>{const t=og();return og(Yp(e)).sub(t).lessThan(0).select(ud,e)}),jb=cn(([e,t=kl(),r=yn(0)])=>{const s=e.x,i=e.y,n=r.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=e.reciprocal(),l=_n(a,o);return t.add(l).mul(u)}),Xb=cn(([e,t=null,r=null,s=yn(1),i=lc,n=Tc])=>{let a=n.abs().normalize();a=a.div(a.dot(Rn(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=Kl(d,o).mul(a.x),g=Kl(c,u).mul(a.y),m=Kl(h,l).mul(a.z);return Fa(p,g,m)}),Kb=new ut,Qb=new r,Yb=new r,Zb=new r,Jb=new a,ex=new r(0,0,-1),tx=new s,rx=new r,sx=new r,ix=new s,nx=new t,ax=new ne,ox=ud.flipX();ax.depthTexture=new Z(1,1);let ux=!1;class lx extends jl{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||ax.texture,ox),this._reflectorBaseNode=e.reflector||new dx(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new lx({defaultTexture:ax.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class dx extends ci{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new at,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(v('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?ri.RENDER:ri.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(nx),e.setSize(Math.round(nx.width*r),Math.round(nx.height*r))}setup(e){return this._updateResolution(ax,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new ne(0,0,{type:Te,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=ot,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Z),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&ux)return!1;ux=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(nx),this._updateResolution(o,s),Yb.setFromMatrixPosition(n.matrixWorld),Zb.setFromMatrixPosition(r.matrixWorld),Jb.extractRotation(n.matrixWorld),Qb.set(0,0,1),Qb.applyMatrix4(Jb),rx.subVectors(Yb,Zb);let u=!1;if(!0===rx.dot(Qb)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(ux=!1);u=!0}rx.reflect(Qb).negate(),rx.add(Yb),Jb.extractRotation(r.matrixWorld),ex.set(0,0,-1),ex.applyMatrix4(Jb),ex.add(Zb),sx.subVectors(Yb,ex),sx.reflect(Qb).negate(),sx.add(Yb),a.coordinateSystem=r.coordinateSystem,a.position.copy(rx),a.up.set(0,1,0),a.up.applyMatrix4(Jb),a.up.reflect(Qb),a.lookAt(sx),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Kb.setFromNormalAndCoplanarPoint(Qb,Yb),Kb.applyMatrix4(a.matrixWorldInverse),tx.set(Kb.normal.x,Kb.normal.y,Kb.normal.z,Kb.constant);const l=a.projectionMatrix;ix.x=(Math.sign(tx.x)+l.elements[8])/l.elements[0],ix.y=(Math.sign(tx.y)+l.elements[9])/l.elements[5],ix.z=-1,ix.w=(1+l.elements[10])/l.elements[14],tx.multiplyScalar(1/tx.dot(ix));l.elements[2]=tx.x,l.elements[6]=tx.y,l.elements[10]=s.coordinateSystem===h?tx.z-0:tx.z+1-0,l.elements[14]=tx.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const d=s.getRenderTarget(),c=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0;const g=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),t.name=g,s.setMRT(c),s.setRenderTarget(d),s.autoClear=p,i.visible=!0,ux=!1,this.forceUpdate=!1}get resolution(){return v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const cx=new Ne(-1,1,1,-1,0,1);class hx extends ve{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lt(t,2))}}const px=new hx;class gx extends oe{constructor(e=null){super(px,e),this.camera=cx,this.isQuadMesh=!0}async renderAsync(e){v('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,cx)}render(e){e.render(this,cx)}}const mx=new t;class fx extends jl{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:Te}){const i=new ne(t,r,s);super(i.texture,kl()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.pixelRatio=1,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new gx(new vg),this.updateBeforeType=ri.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const r=e*this.pixelRatio,s=t*this.pixelRatio;this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),r=e.getSize(mx),s=Math.floor(r.width*t),i=Math.floor(r.height*t);s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const r=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(r)}clone(){const e=new jl(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const yx=(e,...t)=>new fx(tn(e),...t),bx=cn(([e,t,r],s)=>{let i;s.renderer.coordinateSystem===h?(e=_n(e.x,e.y.oneMinus()).mul(2).sub(1),i=Cn(Rn(e,t),1)):i=Cn(Rn(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Cn(r.mul(i));return n.xyz.div(n.w)}),xx=cn(([e,t])=>{const r=t.mul(Cn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return _n(s.x,s.y.oneMinus())}),Tx=cn(([e,t,r])=>{const s=zl(Ql(t)),i=vn(e.mul(s)).toVar(),n=Ql(t,i).toVar(),a=Ql(t,i.sub(vn(2,0))).toVar(),o=Ql(t,i.sub(vn(1,0))).toVar(),u=Ql(t,i.add(vn(1,0))).toVar(),l=Ql(t,i.add(vn(2,0))).toVar(),d=Ql(t,i.add(vn(0,2))).toVar(),c=Ql(t,i.add(vn(0,1))).toVar(),h=Ql(t,i.sub(vn(0,1))).toVar(),p=Ql(t,i.sub(vn(0,2))).toVar(),g=Vo(Pa(yn(2).mul(o).sub(a),n)).toVar(),m=Vo(Pa(yn(2).mul(u).sub(l),n)).toVar(),f=Vo(Pa(yn(2).mul(c).sub(d),n)).toVar(),y=Vo(Pa(yn(2).mul(h).sub(p),n)).toVar(),b=bx(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(bx(e.sub(_n(yn(1).div(s.x),0)),o,r)),b.negate().add(bx(e.add(_n(yn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(bx(e.add(_n(0,yn(1).div(s.y))),c,r)),b.negate().add(bx(e.sub(_n(0,yn(1).div(s.y))),h,r)));return Ro(au(x,T))}),_x=cn(([e])=>Eo(yn(52.9829189).mul(Eo(nu(e,_n(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),vx=cn(([e,t,r])=>{const s=yn(2.399963229728653),i=_o(yn(e).add(.5).div(yn(t))),n=yn(e).mul(s).add(r);return _n(Co(n),Ao(n)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class Nx extends ci{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(kl())}sample(e){return this.callback(e)}}class Sx extends ci{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Sx.OBJECT?this.updateType=ri.OBJECT:e===Sx.MATERIAL?this.updateType=ri.RENDER:e===Sx.BEFORE_OBJECT?this.updateBeforeType=ri.OBJECT:e===Sx.BEFORE_MATERIAL&&(this.updateBeforeType=ri.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}Sx.OBJECT="object",Sx.MATERIAL="material",Sx.BEFORE_OBJECT="beforeObject",Sx.BEFORE_MATERIAL="beforeMaterial";const Rx=(e,t)=>new Sx(e,t).toStack();class Ex extends q{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Ax extends we{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class wx extends ci{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Cx=on(wx),Mx=new a,Bx=Sa(0).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Lx=Sa(1).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundIntensity),Fx=Sa(new a).setGroup(_a).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&t.mapping!==dt?Mx.makeRotationFromEuler(e.backgroundRotation).transpose():Mx.identity(),Mx});class Px extends jl{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=ii.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return null!==this.storeNode?(this.generateStore(e),""):super.generate(e,t)}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;return e.generateStorageTextureLoad(l,t,r,s,n,u)}toReadWrite(){return this.setAccess(ii.READ_WRITE)}toReadOnly(){return this.setAccess(ii.READ_ONLY)}toWriteOnly(){return this.setAccess(ii.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(this.value,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}}const Dx=an(Px).setParameterLength(1,3),Ux=cn(({texture:e,uv:t})=>{const r=1e-4,s=Rn().toVar();return gn(t.x.lessThan(r),()=>{s.assign(Rn(1,0,0))}).ElseIf(t.y.lessThan(r),()=>{s.assign(Rn(0,1,0))}).ElseIf(t.z.lessThan(r),()=>{s.assign(Rn(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{s.assign(Rn(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{s.assign(Rn(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{s.assign(Rn(0,0,-1))}).Else(()=>{const r=.01,i=e.sample(t.add(Rn(-.01,0,0))).r.sub(e.sample(t.add(Rn(r,0,0))).r),n=e.sample(t.add(Rn(0,-.01,0))).r.sub(e.sample(t.add(Rn(0,r,0))).r),a=e.sample(t.add(Rn(0,0,-.01))).r.sub(e.sample(t.add(Rn(0,0,r))).r);s.assign(Rn(i,n,a))}),s.normalize()});class Ix extends jl{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Rn(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return Ux({texture:this,uv:e})}}const Ox=an(Ix).setParameterLength(1,3);class Vx extends Hc{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const kx=new WeakMap;class Gx extends gi{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=ri.OBJECT,this.updateAfterType=ri.OBJECT,this.previousModelWorldMatrix=Sa(new a),this.previousProjectionMatrix=Sa(new a).setGroup(_a),this.previousCameraViewMatrix=Sa(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=$x(r);this.previousModelWorldMatrix.value.copy(s);const i=zx(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new a,i.previousCameraViewMatrix=new a,i.currentProjectionMatrix=new a,i.currentCameraViewMatrix=new a,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){$x(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Fd:Sa(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(sc).mul(lc),s=this.previousProjectionMatrix.mul(t).mul(dc),i=r.xy.div(r.w),n=s.xy.div(s.w);return Pa(i,n)}}function zx(e){let t=kx.get(e);return void 0===t&&(t={},kx.set(e,t)),t}function $x(e,t=0){const r=zx(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const Wx=on(Gx),Hx=cn(([e])=>Kx(e.rgb)),qx=cn(([e,t=yn(1)])=>t.mix(Kx(e.rgb),e.rgb)),jx=cn(([e,t=yn(1)])=>{const r=Fa(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return gu(e.rgb,s,i)}),Xx=cn(([e,t=yn(1)])=>{const r=Rn(.57735,.57735,.57735),s=t.cos();return Rn(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(nu(r,e.rgb).mul(s.oneMinus())))))}),Kx=(e,t=Rn(p.getLuminanceCoefficients(new r)))=>nu(e,t),Qx=cn(([e,t=Rn(1),s=Rn(0),i=Rn(1),n=yn(1),a=Rn(p.getLuminanceCoefficients(new r,Re))])=>{const o=e.rgb.dot(Rn(a)),u=eu(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return gn(u.r.greaterThan(0),()=>{u.r.assign(l.r)}),gn(u.g.greaterThan(0),()=>{u.g.assign(l.g)}),gn(u.b.greaterThan(0),()=>{u.b.assign(l.b)}),u.assign(o.add(u.sub(o).mul(n))),Cn(u.rgb,e.a)}),Yx=cn(([e,t])=>e.mul(t).floor().div(t));let Zx=null;class Jx extends Wp{static get type(){return"ViewportSharedTextureNode"}constructor(e=ud,t=null){null===Zx&&(Zx=new Q),super(e,t,Zx)}getTextureForReference(){return Zx}updateReference(){return this}}const eT=an(Jx).setParameterLength(0,2),tT=new t;class rT extends jl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class sT extends rT{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class iT extends gi{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const i=new Z;i.isRenderTargetTexture=!0,i.name="depth";const n=new ne(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Te,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Sa(0),this._cameraFar=Sa(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=ri.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return d("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return d("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new sT(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new sT(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=sg(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=Jp(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),!0===e.reversedDepthBuffer&&(this.renderTarget.depthTexture.type=K),this.scope===iT.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s,i;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(i=1,s=t.xr.getCamera(),t.xr.updateCamera(s),tT.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(tT)),this._pixelRatio=i,this.setSize(tT.width,tT.height);const a=t.getRenderTarget(),o=t.getMRT(),u=t.autoClear,l=t.transparent,d=t.opaque,c=s.layers.mask,h=t.contextNode,p=r.overrideMaterial;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(r.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Cu({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const g=r.name;r.name=this.name?this.name:r.name,t.render(r,s),r.name=g,r.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=u,t.transparent=l,t.opaque=d,t.contextNode=h,s.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const r=Math.floor(this._width*this._pixelRatio*this._resolutionScale),s=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(r,s),null!==this._scissor?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,r,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new s),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,i))}setViewport(e,t,r,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new s),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}iT.COLOR="color",iT.DEPTH="depth";class nT extends iT{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(iT.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)}),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new vg;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=F;const t=Tc.negate(),r=Fd.mul(sc),s=yn(1),i=r.mul(Cn(lc,1)),n=r.mul(Cn(lc.add(t),1)),a=Ro(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=Cn(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const aT=cn(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),oT=cn(([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"}]}),uT=cn(([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lT=cn(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)}),dT=cn(([e,t])=>{const r=Pn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Pn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=lT(e),(e=s.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),cT=Pn(Rn(1.6605,-.1246,-.0182),Rn(-.5876,1.1329,-.1006),Rn(-.0728,-.0083,1.1187)),hT=Pn(Rn(.6274,.0691,.0164),Rn(.3293,.9195,.088),Rn(.0433,.0113,.8956)),pT=cn(([e])=>{const t=Rn(e).toVar(),r=Rn(t.mul(t)).toVar(),s=Rn(r.mul(r)).toVar();return yn(15.5).mul(s.mul(r)).sub(Da(40.14,s.mul(t))).add(Da(31.96,s).sub(Da(6.868,r.mul(t))).add(Da(.4298,r).add(Da(.1191,t).sub(.00232))))}),gT=cn(([e,t])=>{const r=Rn(e).toVar(),s=Pn(Rn(.856627153315983,.137318972929847,.11189821299995),Rn(.0951212405381588,.761241990602591,.0767994186031903),Rn(.0482516061458583,.101439036467562,.811302368396859)),i=Pn(Rn(1.1271005818144368,-.1413297634984383,-.14132976349843826),Rn(-.11060664309660323,1.157823702216272,-.11060664309660294),Rn(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=yn(-12.47393),a=yn(4.026069);return r.mulAssign(t),r.assign(hT.mul(r)),r.assign(s.mul(r)),r.assign(eu(r,1e-10)),r.assign(To(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(mu(r,0,1)),r.assign(pT(r)),r.assign(i.mul(r)),r.assign(ou(eu(Rn(0),r),Rn(2.2))),r.assign(cT.mul(r)),r.assign(mu(r,0,1)),r}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),mT=cn(([e,t])=>{const r=yn(.76),s=yn(.15);e=e.mul(t);const i=Jo(e.r,Jo(e.g,e.b)),n=Au(i.lessThan(.08),i.sub(Da(6.25,i.mul(i))),.04);e.subAssign(n);const a=eu(e.r,eu(e.g,e.b));gn(a.lessThan(r),()=>e);const o=Pa(1,r),u=Pa(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=Pa(1,Ua(1,s.mul(a.sub(u)).add(1)));return gu(e,Rn(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class fT extends ci{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.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}}const yT=an(fT).setParameterLength(1,3);class bT extends fT{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const xT=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};function TT(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||pc.z).negate()}const _T=cn(([e,t],r)=>{const s=TT(r);return bu(e,t,s)}),vT=cn(([e],t)=>{const r=TT(t);return e.mul(e,r,r).negate().exp().oneMinus()}),NT=cn(([e,t],r)=>{const s=TT(r),i=t.sub(cc.y).max(0).toConst().mul(s).toConst();return e.mul(e,i,i).negate().exp().oneMinus()}),ST=cn(([e,t])=>Cn(t.toFloat().mix(oa.rgb,e.toVec3()),oa.a));let RT=null,ET=null;class AT extends ci{static get type(){return"RangeNode"}constructor(e=yn(),t=yn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),s=e.getTypeLength(Ks(t.value)),i=e.getTypeLength(Ks(r.value));return s>i?s:i}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Hl('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=i.value,o=n.value,u=e.getTypeLength(Ks(a)),d=e.getTypeLength(Ks(o));RT=RT||new s,ET=ET||new s,RT.setScalar(0),ET.setScalar(0),1===u?RT.setScalar(a):a.isColor?RT.set(a.r,a.g,a.b,1):RT.set(a.x,a.y,a.z||0,a.w||0),1===d?ET.setScalar(o):o.isColor?ET.set(o.r,o.g,o.b,1):ET.set(o.x,o.y,o.z||0,o.w||0);const c=4,h=c*t.count,p=new Float32Array(h);for(let e=0;enew CT(e,t),BT=MT("numWorkgroups","uvec3"),LT=MT("workgroupId","uvec3"),FT=MT("globalId","uvec3"),PT=MT("localId","uvec3"),DT=MT("subgroupSize","uint");class UT extends ci{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}const IT=an(UT);class OT extends hi{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.context.assign;if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class VT extends ci{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new OT(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class kT extends ci{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Cl(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}kT.ATOMIC_LOAD="atomicLoad",kT.ATOMIC_STORE="atomicStore",kT.ATOMIC_ADD="atomicAdd",kT.ATOMIC_SUB="atomicSub",kT.ATOMIC_MAX="atomicMax",kT.ATOMIC_MIN="atomicMin",kT.ATOMIC_AND="atomicAnd",kT.ATOMIC_OR="atomicOr",kT.ATOMIC_XOR="atomicXor";const GT=an(kT),zT=(e,t,r)=>GT(e,t,r).toStack();class $T extends gi{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}generateNodeType(e){const t=this.method;return t===$T.SUBGROUP_ELECT?"bool":t===$T.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===$T.SUBGROUP_BROADCAST||r===$T.SUBGROUP_SHUFFLE||r===$T.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===$T.SUBGROUP_SHUFFLE_XOR||r===$T.SUBGROUP_SHUFFLE_DOWN||r===$T.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}$T.SUBGROUP_ELECT="subgroupElect",$T.SUBGROUP_BALLOT="subgroupBallot",$T.SUBGROUP_ADD="subgroupAdd",$T.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",$T.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",$T.SUBGROUP_MUL="subgroupMul",$T.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",$T.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",$T.SUBGROUP_AND="subgroupAnd",$T.SUBGROUP_OR="subgroupOr",$T.SUBGROUP_XOR="subgroupXor",$T.SUBGROUP_MIN="subgroupMin",$T.SUBGROUP_MAX="subgroupMax",$T.SUBGROUP_ALL="subgroupAll",$T.SUBGROUP_ANY="subgroupAny",$T.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",$T.QUAD_SWAP_X="quadSwapX",$T.QUAD_SWAP_Y="quadSwapY",$T.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",$T.SUBGROUP_BROADCAST="subgroupBroadcast",$T.SUBGROUP_SHUFFLE="subgroupShuffle",$T.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",$T.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",$T.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",$T.QUAD_BROADCAST="quadBroadcast";const WT=un($T,$T.SUBGROUP_ELECT).setParameterLength(0),HT=un($T,$T.SUBGROUP_BALLOT).setParameterLength(1),qT=un($T,$T.SUBGROUP_ADD).setParameterLength(1),jT=un($T,$T.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),XT=un($T,$T.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),KT=un($T,$T.SUBGROUP_MUL).setParameterLength(1),QT=un($T,$T.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),YT=un($T,$T.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),ZT=un($T,$T.SUBGROUP_AND).setParameterLength(1),JT=un($T,$T.SUBGROUP_OR).setParameterLength(1),e_=un($T,$T.SUBGROUP_XOR).setParameterLength(1),t_=un($T,$T.SUBGROUP_MIN).setParameterLength(1),r_=un($T,$T.SUBGROUP_MAX).setParameterLength(1),s_=un($T,$T.SUBGROUP_ALL).setParameterLength(0),i_=un($T,$T.SUBGROUP_ANY).setParameterLength(0),n_=un($T,$T.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),a_=un($T,$T.QUAD_SWAP_X).setParameterLength(1),o_=un($T,$T.QUAD_SWAP_Y).setParameterLength(1),u_=un($T,$T.QUAD_SWAP_DIAGONAL).setParameterLength(1),l_=un($T,$T.SUBGROUP_BROADCAST).setParameterLength(2),d_=un($T,$T.SUBGROUP_SHUFFLE).setParameterLength(2),c_=un($T,$T.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),h_=un($T,$T.SUBGROUP_SHUFFLE_UP).setParameterLength(2),p_=un($T,$T.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),g_=un($T,$T.QUAD_BROADCAST).setParameterLength(1);let m_;function f_(e){m_=m_||new WeakMap;let t=m_.get(e);return void 0===t&&m_.set(e,t={}),t}function y_(e){const t=f_(e);return t.shadowMatrix||(t.shadowMatrix=Sa("mat4").setGroup(_a).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 b_(e,t=cc){const r=y_(e).mul(t);return r.xyz.div(r.w)}function x_(e){const t=f_(e);return t.position||(t.position=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld)))}function T_(e){const t=f_(e);return t.targetPosition||(t.targetPosition=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld)))}function __(e){const t=f_(e);return t.viewPosition||(t.viewPosition=Sa(new r).setGroup(_a).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const v_=e=>Dd.transformDirection(x_(e).sub(T_(e))),N_=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},S_=new WeakMap,R_=[];class E_ extends ci{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Vn("vec3","totalDiffuse"),this.totalSpecularNode=Vn("vec3","totalSpecular"),this.outgoingLightNode=Vn("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(tn(e));else{let s=null;if(null!==r&&(s=N_(e.id,r)),null===s){const t=i.getLightNodeClass(e.constructor);if(null===t){d(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===S_.has(e)&&S_.set(e,new t(e)),s=S_.get(e)}t.push(s)}this._lightNodes=t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=Rn(null!==l?l.mix(g,u):u)),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class A_ extends ci{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ri.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){w_.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||cc)}}const w_=Vn("vec3","shadowPositionWorld");function C_(t,r={}){return r.toneMapping=t.toneMapping,r.toneMappingExposure=t.toneMappingExposure,r.outputColorSpace=t.outputColorSpace,r.renderTarget=t.getRenderTarget(),r.activeCubeFace=t.getActiveCubeFace(),r.activeMipmapLevel=t.getActiveMipmapLevel(),r.renderObjectFunction=t.getRenderObjectFunction(),r.pixelRatio=t.getPixelRatio(),r.mrt=t.getMRT(),r.clearColor=t.getClearColor(r.clearColor||new e),r.clearAlpha=t.getClearAlpha(),r.autoClear=t.autoClear,r.scissorTest=t.getScissorTest(),r}function M_(e,t){return t=C_(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function B_(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)}function L_(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function F_(e,t){return t=L_(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function P_(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function D_(e,t,r){return r=F_(t,r=M_(e,r))}function U_(e,t,r){B_(e,r),P_(t,r)}var I_=Object.freeze({__proto__:null,resetRendererAndSceneState:D_,resetRendererState:M_,resetSceneState:F_,restoreRendererAndSceneState:U_,restoreRendererState:B_,restoreSceneState:P_,saveRendererAndSceneState:function(e,t,r={}){return r=L_(t,r=C_(e,r))},saveRendererState:C_,saveSceneState:L_});const O_=new WeakMap,V_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Kl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)}),k_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=qc("radius","float",r).setGroup(_a),o=_n(1).div(n),u=a.mul(o.x),l=_x(dd.xy).mul(6.28318530718);return Fa(i(t.xy.add(vx(0,5,l).mul(u)),t.z),i(t.xy.add(vx(1,5,l).mul(u)),t.z),i(t.xy.add(vx(2,5,l).mul(u)),t.z),i(t.xy.add(vx(3,5,l).mul(u)),t.z),i(t.xy.add(vx(4,5,l).mul(u)),t.z)).mul(.2)}),G_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=_n(1).div(n),o=a.x,u=a.y,l=t.xy,d=Eo(l.mul(n).add(.5));return l.subAssign(d.mul(a)),Fa(i(l,t.z),i(l.add(_n(o,0)),t.z),i(l.add(_n(0,u)),t.z),i(l.add(a),t.z),gu(i(l.add(_n(o.negate(),0)),t.z),i(l.add(_n(o.mul(2),0)),t.z),d.x),gu(i(l.add(_n(o.negate(),u)),t.z),i(l.add(_n(o.mul(2),u)),t.z),d.x),gu(i(l.add(_n(0,u.negate())),t.z),i(l.add(_n(0,u.mul(2))),t.z),d.y),gu(i(l.add(_n(o,u.negate())),t.z),i(l.add(_n(o,u.mul(2))),t.z),d.y),gu(gu(i(l.add(_n(o.negate(),u.negate())),t.z),i(l.add(_n(o.mul(2),u.negate())),t.z),d.x),gu(i(l.add(_n(o.negate(),u.mul(2))),t.z),i(l.add(_n(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)}),z_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r},s)=>{let i=Kl(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=i.x,a=eu(1e-7,i.y.mul(i.y)),o=s.renderer.reversedDepthBuffer?tu(n,t.z):tu(t.z,n),u=yn(1).toVar();return gn(o.notEqual(1),()=>{const e=t.z.sub(n);let r=a.div(a.add(e.mul(e)));r=mu(Pa(r,.3).div(.65)),u.assign(eu(o,r))}),u}),$_=e=>{let t=O_.get(e);return void 0===t&&(t=new vg,t.colorNode=Cn(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=re,t.fog=!1,O_.set(e,t)),t},W_=e=>{const t=O_.get(e);void 0!==t&&(t.dispose(),O_.delete(e))},H_=new Ty,q_=[],j_=(e,t,r,s)=>{q_[0]=e,q_[1]=t;let i=H_.get(q_);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===pt)&&(s&&(Ys(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,...d),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,H_.set(q_,i)),q_[0]=null,q_[1]=null,i},X_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanVertical"),a=yn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(Fa(dd.xy,_n(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),K_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanHorizontal"),a=yn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(Fa(dd.xy,_n(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(Fa(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),Q_=[V_,k_,G_,z_];let Y_;const Z_=new gx;class J_ extends A_{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:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,yn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=r.biasNode||qc("bias","float",r).setGroup(_a);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=qc("near","float",r.camera).setGroup(_a),s=qc("far","float",r.camera).setGroup(_a);n=ig(e.negate(),t,s)}return a=Rn(a.x,a.y.oneMinus(),s.reversedDepthBuffer?n.sub(i):n.add(i)),a}getShadowFilterFn(e){return Q_[e]}setupRenderTarget(e,t){const r=new Z(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t,camera:r}=e,{light:s,shadow:i}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(i,e),o=t.shadowMap.type,u=t.hasCompatibility(E.TEXTURE_COMPARE);if(o!==ct&&o!==ht||!u?(n.minFilter=B,n.magFilter=B):(n.minFilter=le,n.magFilter=le),i.camera.coordinateSystem=r.coordinateSystem,i.camera.updateProjectionMatrix(),o===pt&&!0!==i.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}));let t=Kl(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Kl(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const s=qc("blurSamples","float",i).setGroup(_a),o=qc("radius","float",i).setGroup(_a),u=qc("mapSize","vec2",i).setGroup(_a);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new vg);l.fragmentNode=X_({samples:s,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new vg),l.fragmentNode=K_({samples:s,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=qc("intensity","float",i).setGroup(_a),d=qc("normalBias","float",i).setGroup(_a),c=y_(s),h=Rc.mul(d);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(w_.add(h));else{p=Sa("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(lc).add(c.mul(Cn(h,0)))}const g=this.setupShadowCoord(e,p),m=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=o===pt&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:f,shadowCoord:g,shadow:i,depthLayer:this.depthLayer});let b,x;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=$c(a.texture,g.xyz):(b=Kl(a.texture,g),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),x=b?gu(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():gu(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const T=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&x.toInspector(`${T} / Color`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture):Kl(this.shadowMap.texture)),x.toInspector(`${T} / Depth`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture).r.oneMinus():Ql(this.shadowMap.depthTexture,kl().mul(zl(Kl(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return cn(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let r=this._node;return this.setupShadowPosition(e),null===r&&(this._node=r=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(r=e.material.receivedShadowNode(r)),r})()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth);const a=n.name;n.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,i.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");Y_=D_(i,n,Y_),n.overrideMaterial=$_(r),i.setRenderObjectFunction(j_(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===pt&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,U_(i,n,Y_)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),Z_.material=this.vsmMaterialVertical,Z_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Z_.material=this.vsmMaterialHorizontal,Z_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,W_(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const ev=(e,t)=>new J_(e,t),tv=new e,rv=new a,sv=new r,iv=new r,nv=[new r(1,0,0),new r(-1,0,0),new r(0,-1,0),new r(0,1,0),new r(0,0,1),new r(0,0,-1)],av=[new r(0,-1,0),new r(0,-1,0),new r(0,0,-1),new r(0,0,1),new r(0,-1,0),new r(0,-1,0)],ov=[new r(1,0,0),new r(-1,0,0),new r(0,1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1)],uv=[new r(0,-1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1),new r(0,-1,0),new r(0,-1,0)],lv=cn(({depthTexture:e,bd3D:t,dp:r})=>$c(e,t).compare(r)),dv=cn(({depthTexture:e,bd3D:t,dp:r,shadow:s})=>{const i=qc("radius","float",s).setGroup(_a),n=qc("mapSize","vec2",s).setGroup(_a),a=i.div(n.x),o=Vo(t),u=Ro(au(t,o.x.greaterThan(o.z).select(Rn(0,1,0),Rn(1,0,0)))),l=au(t,u),d=_x(dd.xy).mul(6.28318530718),c=vx(0,5,d),h=vx(1,5,d),p=vx(2,5,d),g=vx(3,5,d),m=vx(4,5,d);return $c(e,t.add(u.mul(c.x).add(l.mul(c.y)).mul(a))).compare(r).add($c(e,t.add(u.mul(h.x).add(l.mul(h.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(p.x).add(l.mul(p.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(g.x).add(l.mul(g.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(m.x).add(l.mul(m.y)).mul(a))).compare(r)).mul(.2)}),cv=cn(({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s},i)=>{const n=r.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),u=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.near),l=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.far),d=qc("bias","float",s).setGroup(_a),c=yn(1).toVar();return gn(o.sub(l).lessThanEqual(0).and(o.sub(u).greaterThanEqual(0)),()=>{let r;i.renderer.reversedDepthBuffer?(r=rg(o.negate(),u,l),r.subAssign(d)):(r=tg(o.negate(),u,l),r.addAssign(d));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:r,shadow:s}))}),c});class hv extends J_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===gt?lv:dv}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i}){return cv({filterFn:t,depthTexture:r,shadowCoord:s,shadow:i})}setupRenderTarget(e,t){const r=new mt(e.mapSize.width);r.name="PointShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createCubeRenderTarget(e.mapSize.width);return s.texture.name="PointShadowMap",s.depthTexture=r,{shadowMap:s,depthTexture:r}}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.camera,o=t.matrix,u=i.coordinateSystem===h,l=u?nv:ov,d=u?av:uv;r.setSize(t.mapSize.width,t.mapSize.width);const c=i.autoClear,p=i.getClearColor(tv),g=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(r,e),i.clear();const u=s.distance||a.far;u!==a.far&&(a.far=u,a.updateProjectionMatrix()),sv.setFromMatrixPosition(s.matrixWorld),a.position.copy(sv),iv.copy(a.position),iv.add(l[e]),a.up.copy(d[e]),a.lookAt(iv),a.updateMatrixWorld(),o.makeTranslation(-sv.x,-sv.y,-sv.z),rv.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(rv,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${e+1}`,i.render(n,a),n.name=c}i.autoClear=c,i.setClearColor(p,g)}}const pv=(e,t)=>new hv(e,t);class gv extends Op{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Sa(this.color).setGroup(_a),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ri.FRAME,t&&t.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},t.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 __(this.light).sub(e.context.positionView||pc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return ev(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?tn(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(r=e.context.getShadow(this,e)),this.colorNode=r}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),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const mv=cn(({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)}),fv=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=mv({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class yv extends gv{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(2).setGroup(_a)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return pv(this.light)}setupDirect(e){return fv({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const bv=cn(([e=kl()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()}),xv=cn(([e=kl()],{renderer:t,material:r})=>{const s=pu(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.currentSamples>0){const e=yn(s.fwidth()).toVar();i=bu(e.oneMinus(),e.add(1),s).oneMinus()}else i=Au(s.greaterThan(1),0,1);return i}),Tv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=Tn(e).toVar();return Au(n,i,s)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),_v=cn(([e,t])=>{const r=Tn(t).toVar(),s=yn(e).toVar();return Au(r,s.negate(),s)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),vv=cn(([e])=>{const t=yn(e).toVar();return bn(No(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Nv=cn(([e,t])=>{const r=yn(e).toVar();return t.assign(vv(r)),r.sub(yn(t))}),Sv=Vb([cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=yn(s).toVar(),l=yn(r).toVar(),d=yn(t).toVar(),c=yn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=Rn(s).toVar(),l=Rn(r).toVar(),d=Rn(t).toVar(),c=Rn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),Rv=Vb([cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=yn(o).toVar(),m=yn(a).toVar(),f=yn(n).toVar(),y=yn(i).toVar(),b=yn(s).toVar(),x=yn(r).toVar(),T=yn(t).toVar(),_=yn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=Rn(o).toVar(),m=Rn(a).toVar(),f=Rn(n).toVar(),y=Rn(i).toVar(),b=Rn(s).toVar(),x=Rn(r).toVar(),T=Rn(t).toVar(),_=Rn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),Ev=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=xn(e).toVar(),a=xn(n.bitAnd(xn(7))).toVar(),o=yn(Tv(a.lessThan(xn(4)),i,s)).toVar(),u=yn(Da(2,Tv(a.lessThan(xn(4)),s,i))).toVar();return _v(o,Tn(a.bitAnd(xn(1)))).add(_v(u,Tn(a.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Av=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=xn(e).toVar(),u=xn(o.bitAnd(xn(15))).toVar(),l=yn(Tv(u.lessThan(xn(8)),a,n)).toVar(),d=yn(Tv(u.lessThan(xn(4)),n,Tv(u.equal(xn(12)).or(u.equal(xn(14))),a,i))).toVar();return _v(l,Tn(u.bitAnd(xn(1)))).add(_v(d,Tn(u.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),wv=Vb([Ev,Av]),Cv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=An(e).toVar();return Rn(wv(n.x,i,s),wv(n.y,i,s),wv(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Mv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=An(e).toVar();return Rn(wv(o.x,a,n,i),wv(o.y,a,n,i),wv(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),Bv=Vb([Cv,Mv]),Lv=cn(([e])=>{const t=yn(e).toVar();return Da(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Fv=cn(([e])=>{const t=yn(e).toVar();return Da(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Pv=Vb([Lv,cn(([e])=>{const t=Rn(e).toVar();return Da(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Dv=Vb([Fv,cn(([e])=>{const t=Rn(e).toVar();return Da(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Uv=cn(([e,t])=>{const r=bn(t).toVar(),s=xn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(bn(32).sub(r)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),Iv=cn(([e,t,r])=>{e.subAssign(r),e.bitXorAssign(Uv(r,bn(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Uv(e,bn(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Uv(t,bn(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(Uv(r,bn(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Uv(e,bn(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Uv(t,bn(4))),t.addAssign(e)}),Ov=cn(([e,t,r])=>{const s=xn(r).toVar(),i=xn(t).toVar(),n=xn(e).toVar();return s.bitXorAssign(i),s.subAssign(Uv(i,bn(14))),n.bitXorAssign(s),n.subAssign(Uv(s,bn(11))),i.bitXorAssign(n),i.subAssign(Uv(n,bn(25))),s.bitXorAssign(i),s.subAssign(Uv(i,bn(16))),n.bitXorAssign(s),n.subAssign(Uv(s,bn(4))),i.bitXorAssign(n),i.subAssign(Uv(n,bn(14))),s.bitXorAssign(i),s.subAssign(Uv(i,bn(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Vv=cn(([e])=>{const t=xn(e).toVar();return yn(t).div(yn(xn(bn(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),kv=cn(([e])=>{const t=yn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),Gv=Vb([cn(([e])=>{const t=bn(e).toVar(),r=xn(xn(1)).toVar(),s=xn(xn(bn(3735928559)).add(r.shiftLeft(xn(2))).add(xn(13))).toVar();return Ov(s.add(xn(t)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(xn(2)).toVar(),n=xn().toVar(),a=xn().toVar(),o=xn().toVar();return n.assign(a.assign(o.assign(xn(bn(3735928559)).add(i.shiftLeft(xn(2))).add(xn(13))))),n.addAssign(xn(s)),a.addAssign(xn(r)),Ov(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(xn(3)).toVar(),o=xn().toVar(),u=xn().toVar(),l=xn().toVar();return o.assign(u.assign(l.assign(xn(bn(3735928559)).add(a.shiftLeft(xn(2))).add(xn(13))))),o.addAssign(xn(n)),u.addAssign(xn(i)),l.addAssign(xn(s)),Ov(o,u,l)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),cn(([e,t,r,s])=>{const i=bn(s).toVar(),n=bn(r).toVar(),a=bn(t).toVar(),o=bn(e).toVar(),u=xn(xn(4)).toVar(),l=xn().toVar(),d=xn().toVar(),c=xn().toVar();return l.assign(d.assign(c.assign(xn(bn(3735928559)).add(u.shiftLeft(xn(2))).add(xn(13))))),l.addAssign(xn(o)),d.addAssign(xn(a)),c.addAssign(xn(n)),Iv(l,d,c),l.addAssign(xn(i)),Ov(l,d,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),cn(([e,t,r,s,i])=>{const n=bn(i).toVar(),a=bn(s).toVar(),o=bn(r).toVar(),u=bn(t).toVar(),l=bn(e).toVar(),d=xn(xn(5)).toVar(),c=xn().toVar(),h=xn().toVar(),p=xn().toVar();return c.assign(h.assign(p.assign(xn(bn(3735928559)).add(d.shiftLeft(xn(2))).add(xn(13))))),c.addAssign(xn(l)),h.addAssign(xn(u)),p.addAssign(xn(o)),Iv(c,h,p),c.addAssign(xn(a)),h.addAssign(xn(n)),Ov(c,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),zv=Vb([cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(Gv(s,r)).toVar(),n=An().toVar();return n.x.assign(i.bitAnd(bn(255))),n.y.assign(i.shiftRight(bn(8)).bitAnd(bn(255))),n.z.assign(i.shiftRight(bn(16)).bitAnd(bn(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(Gv(n,i,s)).toVar(),o=An().toVar();return o.x.assign(a.bitAnd(bn(255))),o.y.assign(a.shiftRight(bn(8)).bitAnd(bn(255))),o.z.assign(a.shiftRight(bn(16)).bitAnd(bn(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),$v=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=yn(Sv(wv(Gv(r,s),i,n),wv(Gv(r.add(bn(1)),s),i.sub(1),n),wv(Gv(r,s.add(bn(1))),i,n.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=yn(Rv(wv(Gv(r,s,i),n,a,o),wv(Gv(r.add(bn(1)),s,i),n.sub(1),a,o),wv(Gv(r,s.add(bn(1)),i),n,a.sub(1),o),wv(Gv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),wv(Gv(r,s,i.add(bn(1))),n,a,o.sub(1)),wv(Gv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),wv(Gv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Dv(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),Wv=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=Rn(Sv(Bv(zv(r,s),i,n),Bv(zv(r.add(bn(1)),s),i.sub(1),n),Bv(zv(r,s.add(bn(1))),i,n.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=Rn(Rv(Bv(zv(r,s,i),n,a,o),Bv(zv(r.add(bn(1)),s,i),n.sub(1),a,o),Bv(zv(r,s.add(bn(1)),i),n,a.sub(1),o),Bv(zv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),Bv(zv(r,s,i.add(bn(1))),n,a,o.sub(1)),Bv(zv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),Bv(zv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Dv(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),Hv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Vv(Gv(r))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Vv(Gv(r,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Vv(Gv(r,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Vv(Gv(r,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),qv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Rn(Vv(Gv(r,bn(0))),Vv(Gv(r,bn(1))),Vv(Gv(r,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Rn(Vv(Gv(r,s,bn(0))),Vv(Gv(r,s,bn(1))),Vv(Gv(r,s,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Rn(Vv(Gv(r,s,i,bn(0))),Vv(Gv(r,s,i,bn(1))),Vv(Gv(r,s,i,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Rn(Vv(Gv(r,s,i,n,bn(0))),Vv(Gv(r,s,i,n,bn(1))),Vv(Gv(r,s,i,n,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),jv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=yn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul($v(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Xv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul(Wv(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Kv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar();return _n(jv(o,a,n,i),jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Qv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(Xv(o,a,n,i)).toVar(),l=yn(jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i)).toVar();return Cn(u,l)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Yv=Vb([cn(([e,t,r,s,i,n,a])=>{const o=bn(a).toVar(),u=yn(n).toVar(),l=bn(i).toVar(),d=bn(s).toVar(),c=bn(r).toVar(),h=bn(t).toVar(),p=_n(e).toVar(),g=Rn(qv(_n(h.add(d),c.add(l)))).toVar(),m=_n(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=_n(_n(yn(h),yn(c)).add(m)).toVar(),y=_n(f.sub(p)).toVar();return gn(o.equal(bn(2)),()=>Vo(y.x).add(Vo(y.y))),gn(o.equal(bn(3)),()=>eu(Vo(y.x),Vo(y.y))),nu(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),cn(([e,t,r,s,i,n,a,o,u])=>{const l=bn(u).toVar(),d=yn(o).toVar(),c=bn(a).toVar(),h=bn(n).toVar(),p=bn(i).toVar(),g=bn(s).toVar(),m=bn(r).toVar(),f=bn(t).toVar(),y=Rn(e).toVar(),b=Rn(qv(Rn(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=Rn(Rn(yn(f),yn(m),yn(g)).add(b)).toVar(),T=Rn(x.sub(y)).toVar();return gn(l.equal(bn(2)),()=>Vo(T.x).add(Vo(T.y)).add(Vo(T.z))),gn(l.equal(bn(3)),()=>eu(Vo(T.x),Vo(T.y),Vo(T.z))),nu(T,T)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),Zv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();l.assign(Jo(l,r))})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Jv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.y.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),eN=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(r)}).ElseIf(r.lessThan(l.z),()=>{l.z.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),tN=Vb([Zv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();d.assign(Jo(d,n))})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),rN=Vb([Jv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.y.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),sN=Vb([eN,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.z.assign(d.y),d.y.assign(n)}).ElseIf(n.lessThan(d.z),()=>{d.z.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),iN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=_n(t).toVar(),p=_n(r).toVar(),g=_n(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(Rn(v,0),x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),nN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=Rn(t).toVar(),p=Rn(r).toVar(),g=Rn(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(v,x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),aN=cn(([e])=>{const t=e.y,r=e.z,s=Rn().toVar();return gn(t.lessThan(1e-4),()=>{s.assign(Rn(r,r,r))}).Else(()=>{let i=e.x;i=i.sub(No(i)).mul(6).toVar();const n=bn(Xo(i)),a=i.sub(yn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());gn(n.equal(bn(0)),()=>{s.assign(Rn(r,l,o))}).ElseIf(n.equal(bn(1)),()=>{s.assign(Rn(u,r,o))}).ElseIf(n.equal(bn(2)),()=>{s.assign(Rn(o,r,l))}).ElseIf(n.equal(bn(3)),()=>{s.assign(Rn(o,u,r))}).ElseIf(n.equal(bn(4)),()=>{s.assign(Rn(l,o,r))}).Else(()=>{s.assign(Rn(r,o,u))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),oN=cn(([e])=>{const t=Rn(e).toVar(),r=yn(t.x).toVar(),s=yn(t.y).toVar(),i=yn(t.z).toVar(),n=yn(Jo(r,Jo(s,i))).toVar(),a=yn(eu(r,eu(s,i))).toVar(),o=yn(a.sub(n)).toVar(),u=yn().toVar(),l=yn().toVar(),d=yn().toVar();return d.assign(a),gn(a.greaterThan(0),()=>{l.assign(o.div(a))}).Else(()=>{l.assign(0)}),gn(l.lessThanEqual(0),()=>{u.assign(0)}).Else(()=>{gn(r.greaterThanEqual(a),()=>{u.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{u.assign(Fa(2,i.sub(r).div(o)))}).Else(()=>{u.assign(Fa(4,r.sub(s).div(o)))}),u.mulAssign(1/6),gn(u.lessThan(0),()=>{u.addAssign(1)})}),Rn(u,l,d)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),uN=cn(([e])=>{const t=Rn(e).toVar(),r=wn(Ga(t,Rn(.04045))).toVar(),s=Rn(t.div(12.92)).toVar(),i=Rn(ou(eu(t.add(Rn(.055)),Rn(0)).div(1.055),Rn(2.4))).toVar();return gu(s,i,r)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lN=(e,t)=>{e=yn(e),t=yn(t);const r=_n(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return bu(e.sub(r),e.add(r),t)},dN=(e,t,r,s)=>gu(e,t,r[s].clamp()),cN=(e,t,r,s,i)=>gu(e,t,lN(r,s[i])),hN=cn(([e,t,r])=>{const s=Ro(e).toVar(),i=Pa(yn(.5).mul(t.sub(r)),cc).div(s).toVar(),n=Pa(yn(-.5).mul(t.sub(r)),cc).div(s).toVar(),a=Rn().toVar();a.x=s.x.greaterThan(yn(0)).select(i.x,n.x),a.y=s.y.greaterThan(yn(0)).select(i.y,n.y),a.z=s.z.greaterThan(yn(0)).select(i.z,n.z);const o=Jo(a.x,a.y,a.z).toVar();return cc.add(s.mul(o)).toVar().sub(r)}),pN=cn(([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(Da(r,r).sub(Da(s,s)))),n});var gN=Object.freeze({__proto__:null,BRDF_GGX:am,BRDF_Lambert:Hg,BasicPointShadowFilter:lv,BasicShadowFilter:V_,Break:Lp,Const:Ou,Continue:()=>Cl("continue").toStack(),DFGLUT:lm,D_GGX:sm,Discard:Ml,EPSILON:ao,F_Schlick:Wg,Fn:cn,HALF_PI:ho,INFINITY:oo,If:gn,Loop:Bp,NodeAccess:ii,NodeShaderStage:ti,NodeType:si,NodeUpdateType:ri,OnBeforeMaterialUpdate:e=>Rx(Sx.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>Rx(Sx.BEFORE_OBJECT,e),OnMaterialUpdate:e=>Rx(Sx.MATERIAL,e),OnObjectUpdate:e=>Rx(Sx.OBJECT,e),PCFShadowFilter:k_,PCFSoftShadowFilter:G_,PI:uo,PI2:lo,PointShadowFilter:dv,Return:()=>Cl("return").toStack(),Schlick_to_F0:hm,ShaderNode:en,Stack:mn,Switch:(...e)=>Si.Switch(...e),TBNViewMatrix:xh,TWO_PI:co,VSMShadowFilter:z_,V_GGX_SmithCorrelated:tm,Var:Iu,VarIntent:Vu,abs:Vo,acesFilmicToneMapping:dT,acos:Do,acosh:Uo,add:Fa,addMethodChaining:Ei,addNodeElement:function(e){d("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:gT,all:po,alphaT:Jn,and:Wa,anisotropy:ea,anisotropyB:ra,anisotropyT:ta,any:go,append:e=>(d("TSL: append() has been renamed to Stack().",new Is),mn(e)),array:Ea,arrayBuffer:e=>new vi(e,"ArrayBuffer"),asin:Fo,asinh:Po,assign:wa,atan:Io,atanh:Oo,atomicAdd:(e,t)=>zT(kT.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>zT(kT.ATOMIC_AND,e,t),atomicFunc:zT,atomicLoad:e=>zT(kT.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>zT(kT.ATOMIC_MAX,e,t),atomicMin:(e,t)=>zT(kT.ATOMIC_MIN,e,t),atomicOr:(e,t)=>zT(kT.ATOMIC_OR,e,t),atomicStore:(e,t)=>zT(kT.ATOMIC_STORE,e,t),atomicSub:(e,t)=>zT(kT.ATOMIC_SUB,e,t),atomicXor:(e,t)=>zT(kT.ATOMIC_XOR,e,t),attenuationColor:ma,attenuationDistance:ga,attribute:Vl,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ax(e,r,s);return Tp(i,t,e)},backgroundBlurriness:Bx,backgroundIntensity:Lx,backgroundRotation:Fx,batch:Ep,bentNormalView:_h,billboarding:Hb,bitAnd:Xa,bitNot:Ka,bitOr:Qa,bitXor:Ya,bitangentGeometry:mh,bitangentLocal:fh,bitangentView:yh,bitangentWorld:bh,bitcast:yb,blendBurn:mg,blendColor:xg,blendDodge:fg,blendOverlay:bg,blendScreen:yg,blur:pf,bool:Tn,buffer:Zl,bufferAttribute:ul,builtin:sd,builtinAOContext:Fu,builtinShadowContext:Lu,bumpMap:Ch,bvec2:Sn,bvec3:wn,bvec4:Ln,bypass:Rl,cache:Nl,call:Ma,cameraFar:Ld,cameraIndex:Md,cameraNear:Bd,cameraNormalMatrix:Id,cameraPosition:Od,cameraProjectionMatrix:Fd,cameraProjectionMatrixInverse:Pd,cameraViewMatrix:Dd,cameraViewport:Vd,cameraWorldMatrix:Ud,cbrt:hu,cdl:Qx,ceil:So,checker:bv,cineonToneMapping:uT,clamp:mu,clearcoat:qn,clearcoatNormalView:Ec,clearcoatRoughness:jn,clipSpace:oc,code:yT,color:fn,colorSpaceToWorking:Qu,colorToDirection:e=>tn(e).mul(2).sub(1),compute:Tl,computeKernel:xl,computeSkinning:(e,t=null)=>{const r=new wp(e);return r.positionNode=Tp(new q(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinIndexNode=Tp(new q(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinWeightNode=Tp(new q(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.bindMatrixNode=Sa(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Sa(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=Zl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,tn(r)},context:Cu,convert:In,convertColorSpace:(e,t,r)=>new Xu(tn(e),t,r),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():yx(e,...t),cos:Co,cosh:Mo,countLeadingZeros:vb,countOneBits:Nb,countTrailingZeros:_b,cross:au,cubeTexture:$c,cubeTextureBase:zc,dFdx:Wo,dFdy:Ho,dashSize:ua,debug:Pl,decrement:so,decrementBefore:to,defaultBuildStages:ai,defaultShaderStages:ni,defined:Zi,degrees:fo,deltaTime:Gb,densityFogFactor:vT,depth:ag,depthPass:(e,t,r)=>new iT(iT.DEPTH,e,t,r),determinant:Yo,difference:iu,diffuseColor:Gn,diffuseContribution:zn,directPointLight:fv,directionToColor:vh,directionToFaceDirection:bc,dispersion:fa,disposeShadowMaterial:W_,distance:su,div:Ua,dot:nu,drawIndex:yl,dynamicBufferAttribute:(e,t=null,r=0,s=0)=>ol(e,t,r,s,x),element:Un,emissive:$n,equal:Oa,equirectUV:Bg,exp:yo,exp2:bo,exponentialHeightFogFactor:NT,expression:Cl,faceDirection:yc,faceForward:xu,faceforward:Su,float:yn,floatBitsToInt:e=>new fb(e,"int","float"),floatBitsToUint:bb,floor:No,fog:ST,fract:Eo,frameGroup:Ta,frameId:zb,frontFacing:fc,fwidth:Ko,gain:(e,t)=>e.lessThan(.5)?Rb(e.mul(2),t).div(2):Pa(1,Rb(Da(Pa(1,e),2),t).div(2)),gapSize:la,getConstNodeType:Ji,getCurrentStack:pn,getDirection:lf,getDistanceAttenuation:mv,getGeometryRoughness:Jg,getNormalFromDepth:Tx,getParallaxCorrectNormal:hN,getRoughness:em,getScreenPosition:xx,getShIrradianceAt:pN,getShadowMaterial:$_,getShadowRenderObjectFunction:j_,getTextureIndex:pb,getViewPosition:bx,ggxConvolution:yf,globalId:FT,glsl:(e,t)=>yT(e,t,"glsl"),glslFn:(e,t)=>xT(e,t,"glsl"),grayscale:Hx,greaterThan:Ga,greaterThanEqual:$a,hash:Sb,highpModelNormalViewMatrix:ac,highpModelViewMatrix:nc,hue:Xx,increment:ro,incrementBefore:eo,inspector:Il,instance:vp,instanceIndex:pl,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ex(e,r,s);return Tp(i,t,i.count)},instancedBufferAttribute:ll,instancedDynamicBufferAttribute:dl,instancedMesh:Sp,int:bn,intBitsToFloat:e=>new fb(e,"float","int"),interleavedGradientNoise:_x,inverse:Zo,inverseSqrt:vo,inversesqrt:Ru,invocationLocalIndex:fl,invocationSubgroupIndex:ml,ior:ca,iridescence:Qn,iridescenceIOR:Yn,iridescenceThickness:Zn,isolate:vl,ivec2:vn,ivec3:En,ivec4:Mn,js:(e,t)=>yT(e,t,"js"),label:Pu,length:Go,lengthSq:pu,lessThan:ka,lessThanEqual:za,lightPosition:x_,lightProjectionUV:b_,lightShadowMatrix:y_,lightTargetDirection:v_,lightTargetPosition:T_,lightViewPosition:__,lightingContext:Gp,lights:(e=[])=>(new E_).setLights(e),linearDepth:og,linearToneMapping:aT,localId:PT,log:xo,log2:To,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(xo(r.div(t)));return yn(Math.E).pow(s).mul(t).negate()},luminance:Kx,mat2:Fn,mat3:Pn,mat4:Dn,matcapUV:ey,materialAO:gp,materialAlphaTest:Lh,materialAnisotropy:Yh,materialAnisotropyVector:mp,materialAttenuationColor:np,materialAttenuationDistance:ip,materialClearcoat:Hh,materialClearcoatNormal:jh,materialClearcoatRoughness:qh,materialColor:Fh,materialDispersion:hp,materialEmissive:Dh,materialEnvIntensity:Pc,materialEnvRotation:Dc,materialIOR:sp,materialIridescence:Zh,materialIridescenceIOR:Jh,materialIridescenceThickness:ep,materialLightMap:pp,materialLineDashOffset:dp,materialLineDashSize:op,materialLineGapSize:up,materialLineScale:ap,materialLineWidth:lp,materialMetalness:$h,materialNormal:Wh,materialOpacity:Uh,materialPointSize:cp,materialReference:Kc,materialReflectivity:Gh,materialRefractionRatio:Fc,materialRotation:Xh,materialRoughness:zh,materialSheen:Kh,materialSheenRoughness:Qh,materialShininess:Ph,materialSpecular:Ih,materialSpecularColor:Vh,materialSpecularIntensity:Oh,materialSpecularStrength:kh,materialThickness:rp,materialTransmission:tp,max:eu,maxMipLevel:Wl,mediumpModelViewMatrix:ic,metalness:Hn,min:Jo,mix:gu,mixElement:_u,mod:Ia,modInt:io,modelDirection:Kd,modelNormalMatrix:tc,modelPosition:Yd,modelRadius:ec,modelScale:Zd,modelViewMatrix:sc,modelViewPosition:Jd,modelViewProjection:fp,modelWorldMatrix:Qd,modelWorldMatrixInverse:rc,morphReference:Ip,mrt:mb,mul:Da,mx_aastep:lN,mx_add:(e,t=yn(0))=>Fa(e,t),mx_atan2:(e=yn(0),t=yn(1))=>Io(e,t),mx_cell_noise_float:(e=kl())=>Hv(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>yn(e).sub(r).mul(t).add(r),mx_divide:(e,t=yn(1))=>Ua(e,t),mx_fractal_noise_float:(e=kl(),t=3,r=2,s=.5,i=1)=>jv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec2:(e=kl(),t=3,r=2,s=.5,i=1)=>Kv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec3:(e=kl(),t=3,r=2,s=.5,i=1)=>Xv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec4:(e=kl(),t=3,r=2,s=.5,i=1)=>Qv(e,bn(t),r,s).mul(i),mx_frame:()=>zb,mx_heighttonormal:(e,t)=>(e=Rn(e),t=yn(t),Ch(e,t)),mx_hsvtorgb:aN,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=yn(1))=>Pa(t,e),mx_modulo:(e,t=yn(1))=>Ia(e,t),mx_multiply:(e,t=yn(1))=>Da(e,t),mx_noise_float:(e=kl(),t=1,r=0)=>$v(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=kl(),t=1,r=0)=>Wv(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=kl(),t=1,r=0)=>{e=e.convert("vec2|vec3");return Cn(Wv(e),$v(e.add(_n(19,73)))).mul(t).add(r)},mx_place2d:(e,t=_n(.5,.5),r=_n(1,1),s=yn(0),i=_n(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=_n(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=yn(1))=>ou(e,t),mx_ramp4:(e,t,r,s,i=kl())=>{const n=i.x.clamp(),a=i.y.clamp(),o=gu(e,t,n),u=gu(r,s,n);return gu(o,u,a)},mx_ramplr:(e,t,r=kl())=>dN(e,t,r,"x"),mx_ramptb:(e,t,r=kl())=>dN(e,t,r,"y"),mx_rgbtohsv:oN,mx_rotate2d:(e,t)=>{e=_n(e);const r=(t=yn(t)).mul(Math.PI/180);return iy(e,r)},mx_rotate3d:(e,t,r)=>{e=Rn(e),t=yn(t),r=Rn(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=yn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=yn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=kl())=>cN(e,t,r,s,"x"),mx_splittb:(e,t,r,s=kl())=>cN(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:uN,mx_subtract:(e,t=yn(0))=>Pa(e,t),mx_timer:()=>kb,mx_transform_uv:(e=1,t=0,r=kl())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>iN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>nN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=kl(),t=1)=>tN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec2:(e=kl(),t=1)=>rN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec3:(e=kl(),t=1)=>sN(e.convert("vec2|vec3"),t,bn(1)),negate:zo,neutralToneMapping:mT,nodeArray:nn,nodeImmutable:on,nodeObject:tn,nodeObjectIntent:rn,nodeObjects:sn,nodeProxy:an,nodeProxyIntent:un,normalFlat:_c,normalGeometry:xc,normalLocal:Tc,normalMap:Rh,normalView:Sc,normalViewGeometry:vc,normalWorld:Rc,normalWorldGeometry:Nc,normalize:Ro,not:qa,notEqual:Va,numWorkgroups:BT,objectDirection:zd,objectGroup:va,objectPosition:Wd,objectRadius:jd,objectScale:Hd,objectViewPosition:qd,objectWorldMatrix:$d,oneMinus:$o,or:Ha,orthographicDepthToViewZ:eg,oscSawtooth:(e=kb)=>e.fract(),oscSine:(e=kb)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=kb)=>e.fract().round(),oscTriangle:(e=kb)=>e.add(.5).fract().mul(2).sub(1).abs(),output:oa,outputStruct:lb,overloadingFn:Vb,packHalf2x16:Cb,packSnorm2x16:Ab,packUnorm2x16:wb,parabola:Rb,parallaxDirection:Th,parallaxUV:(e,t)=>e.sub(Th.mul(t)),parameter:(e,t)=>new sb(e,t),pass:(e,t,r)=>new iT(iT.COLOR,e,t,r),passTexture:(e,t)=>new rT(e,t),pcurve:(e,t,r)=>ou(Ua(ou(e,t),Fa(ou(e,t),ou(Pa(1,e),r))),1/t),perspectiveDepthToViewZ:sg,pmremTexture:Vf,pointShadow:pv,pointUV:Cx,pointWidth:da,positionGeometry:uc,positionLocal:lc,positionPrevious:dc,positionView:pc,positionViewDirection:gc,positionWorld:cc,positionWorldDirection:hc,posterize:Yx,pow:ou,pow2:uu,pow3:lu,pow4:du,premultiplyAlpha:Tg,property:Vn,quadBroadcast:g_,quadSwapDiagonal:u_,quadSwapX:a_,quadSwapY:o_,radians:mo,rand:Tu,range:wT,rangeFogFactor:_T,reciprocal:jo,reference:qc,referenceBuffer:jc,reflect:ru,reflectVector:Oc,reflectView:Uc,reflector:e=>new lx(e),refract:yu,refractVector:Vc,refractView:Ic,reinhardToneMapping:oT,remap:El,remapClamp:Al,renderGroup:_a,renderOutput:Ll,rendererReference:el,replaceDefaultUV:function(e,t=null){return Cu(t,{getUV:"function"==typeof e?e:()=>e})},rotate:iy,rotateUV:$b,roughness:Wn,round:qo,rtt:yx,sRGBTransferEOTF:Hu,sRGBTransferOETF:qu,sample:(e,t=null)=>new Nx(e,tn(t)),sampler:e=>(!0===e.isNode?e:Kl(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Kl(e)).convert("samplerComparison"),saturate:fu,saturation:qx,screenCoordinate:dd,screenDPR:od,screenSize:ld,screenUV:ud,select:Au,setCurrentStack:hn,setName:Bu,shaderStages:oi,shadow:ev,shadowPositionWorld:w_,shapeCircle:xv,sharedUniformGroup:xa,sheen:Xn,sheenRoughness:Kn,shiftLeft:Za,shiftRight:Ja,shininess:aa,sign:ko,sin:Ao,sinc:(e,t)=>Ao(uo.mul(t.mul(e).sub(1))).div(uo.mul(t.mul(e).sub(1))),sinh:wo,skinning:Cp,smoothstep:bu,smoothstepElement:vu,specularColor:sa,specularColorBlended:ia,specularF90:na,spherizeUV:Wb,split:(e,t)=>new yi(tn(e),t),spritesheetUV:jb,sqrt:_o,stack:nb,step:tu,stepElement:Nu,storage:Tp,storageBarrier:()=>IT("storage").toStack(),storageTexture:Dx,string:(e="")=>new vi(e,"string"),struct:(e,t=null)=>{const r=new ab(e,t),s=(...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;eOx(e,t).level(r),texture3DLoad:(...e)=>Ox(...e).setSampler(!1),textureBarrier:()=>IT("texture").toStack(),textureBicubic:Lm,textureBicubicLevel:Bm,textureCubeUV:df,textureLevel:(e,t,r)=>Kl(e,t).level(r),textureLoad:Ql,textureSize:zl,textureStore:(e,t,r)=>{let s;return!0===e.isStorageTextureNode?(s=e.clone(),s.uvNode=t,s.storeNode=r):s=Dx(e,t,r),null!==r&&s.toStack(),s},thickness:pa,time:kb,toneMapping:rl,toneMappingExposure:sl,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>new nT(t,r,tn(s),tn(i),tn(n)),transformDirection:cu,transformNormal:Ac,transformNormalToView:wc,transformedClearcoatNormalView:Bc,transformedNormalView:Cc,transformedNormalWorld:Mc,transmission:ha,transpose:Qo,triNoise3D:Ub,triplanarTexture:(...e)=>Xb(...e),triplanarTextures:Xb,trunc:Xo,uint:xn,uintBitsToFloat:e=>new fb(e,"float","uint"),uniform:Sa,uniformArray:td,uniformCubeTexture:(e=kc)=>zc(e),uniformFlow:Mu,uniformGroup:ba,uniformTexture:(e=ql)=>Kl(e),unpackHalf2x16:Fb,unpackNormal:Nh,unpackSnorm2x16:Bb,unpackUnorm2x16:Lb,unpremultiplyAlpha:_g,userData:(e,t,r)=>new Vx(e,t,r),uv:kl,uvec2:Nn,uvec3:An,uvec4:Bn,varying:$u,varyingProperty:kn,vec2:_n,vec3:Rn,vec4:Cn,vectorComponents:ui,velocity:Wx,vertexColor:gg,vertexIndex:hl,vertexStage:Wu,vibrance:jx,viewZToLogarithmicDepth:ig,viewZToOrthographicDepth:Jp,viewZToPerspectiveDepth:tg,viewZToReversedOrthographicDepth:(e,t,r)=>e.add(r).div(r.sub(t)),viewZToReversedPerspectiveDepth:rg,viewport:cd,viewportCoordinate:pd,viewportDepthTexture:Yp,viewportLinearDepth:ug,viewportMipTexture:qp,viewportOpaqueMipTexture:Xp,viewportResolution:md,viewportSafeUV:qb,viewportSharedTexture:eT,viewportSize:hd,viewportTexture:Hp,viewportUV:gd,vogelDiskSample:vx,wgsl:(e,t)=>yT(e,t,"wgsl"),wgslFn:(e,t)=>xT(e,t,"wgsl"),workgroupArray:(e,t)=>new VT("Workgroup",e,t),workgroupBarrier:()=>IT("workgroup").toStack(),workgroupId:LT,workingToColorSpace:Ku,xor:ja});const mN=new rb;class fN extends Ry{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,r){const s=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)s._clearColor.getRGB(mN),mN.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(mN),mN.a=1,n=!0;else if(!0===i.isNode){const u=this.get(e),l=i;mN.copy(s._clearColor);let d=u.backgroundMesh;if(void 0===d){const h=Cn(l).mul(Lx).context({getUV:()=>Fx.mul(Nc),getTextureLevel:()=>Bx}),p=Fd.element(3).element(3).equal(1),g=Ua(1,Fd.element(1).element(1)).mul(3),m=p.select(lc.mul(g),lc),f=sc.mul(Cn(m,0));let y=Fd.mul(Cn(f.xyz,1));y=y.setZ(y.w);const b=new vg;function x(){i.removeEventListener("dispose",x),d.material.dispose(),d.geometry.dispose()}b.name="Background.material",b.side=F,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=y,b.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=d=new oe(new ft(1,32,32),b),d.frustumCulled=!1,d.name="Background.mesh",i.addEventListener("dispose",x)}const c=l.getCacheKey();u.backgroundCacheKey!==c&&(u.backgroundMeshNode.node=Cn(l).mul(Lx),u.backgroundMeshNode.needsUpdate=!0,d.material.needsUpdate=!0,u.backgroundCacheKey=c),t.unshift(d,d.geometry,d.material,0,0,null,null)}else o("Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?mN.set(0,0,0,1):"alpha-blend"===a&&mN.set(0,0,0,0),!0===s.autoClear||!0===n){const T=r.clearColorValue;T.r=mN.r,T.g=mN.g,T.b=mN.b,T.a=mN.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(T.r*=T.a,T.g*=T.a,T.b*=T.a),r.depthClearValue=s.getClearDepth(),r.stencilClearValue=s.getClearStencil(),r.clearColor=!0===s.autoClearColor,r.clearDepth=!0===s.autoClearDepth,r.clearStencil=!0===s.autoClearStencil}else r.clearColor=!1,r.clearDepth=!1,r.clearStencil=!1}}let yN=0;class bN{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=yN++}}class xN{constructor(e,t,r,s,i,n,a,o,u,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=l,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new bN(t.name,[]);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class TN{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class _N{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}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 vN{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class NN extends vN{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class SN{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let RN=0;class EN{constructor(e=null){this.id=RN++,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 AN{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class wN{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 CN extends wN{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class MN extends wN{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class BN extends wN{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class LN extends wN{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class FN extends wN{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class PN extends wN{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class DN extends wN{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class UN extends wN{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class IN extends CN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ON extends MN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class VN extends BN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kN extends LN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GN extends FN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zN extends PN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $N extends DN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class WN extends UN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let HN=0;const qN=new WeakMap,jN=new WeakMap,XN=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),KN=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class QN{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=nb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new EN,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:HN++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&e.blending===tt&&!1===e.alphaToCoverage}createRenderTarget(e,t,r){return new ne(e,t,r)}createCubeRenderTarget(e,t){return new Lg(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=t[0].groupNode;let s,i=r.shared;if(i)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)r+=t.nodeUniform.node.id}else r+=e.nodeUniform.id;const i=this.renderer._currentRenderContext||this.renderer;let n=qN.get(i);void 0===n&&(n=new Map,qN.set(i,n));const a=Vs(r);s=n.get(a),void 0===s&&(s=new bN(e,t),n.set(a,s))}else s=new bN(e,t);return s}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of oi)for(const s in r[e]){const i=r[e][s],n=t[s]||(t[s]=[]);for(const e of i)!1===n.includes(e)&&n.push(e)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(n)}u`:"0u";if("bool"===i)return n?"true":"false";if("color"===i)return`${this.getType("vec3")}( ${KN(n.r)}, ${KN(n.g)}, ${KN(n.b)} )`;const a=this.getTypeLength(i),o=this.getComponentType(i),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==i)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(i)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(i)}()`;throw new Error(`NodeBuilder: Type '${i}' 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 r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new TN(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===R)return"int";if(t===S)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=Ws(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return XN.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof xt||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=nb(this.stack);const e=pn();return this.stacks.push(e),hn(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,hn(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const r=this.getDataFromNode(e,"vertex");let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new TN("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new AN(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new _N(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new vN(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new NN(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let i=1,n=s;for(;void 0!==r[n];)n=s+"_"+i++;i>1&&(e.name=n,d(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${n}'.`)),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new SN("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!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),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new bT,r=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=r,t}flowShaderNode(e){const t=e.layout,r={[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)r[e.name]=new sb(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new EN,this.stack=nb();for(const r of ai)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){d("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){d("Abstract function.")}getVaryings(){d("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e,t=!1){const r=[],s=this.vars[e];if(void 0!==s)for(const e of s)r.push(`${this.getVar(e.type,e.name,e.count)};`);return r.join(t?"\n":"\n\t")}getUniforms(){d("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}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(){d("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 r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}prebuild(){const{object:e,renderer:t,material:r}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:o('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),r&&r.contextNode&&(!0===r.contextNode.isContextNode?this.context={...this.context,...r.contextNode.getFlowContextData()}:o('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==r){let e=t.library.fromMaterial(r);null===e&&(o(`NodeBuilder: Material "${r.type}" is not compatible.`),e=new vg),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"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 ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this);await Tt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=jN.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const r=this.getSharedDataFromNode(e);let s=r.cache;if(void 0===s){if("float"===t||"int"===t||"uint"===t)s=new IN(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)s=new ON(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)s=new VN(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)s=new kN(e);else if("color"===t)s=new GN(e);else if("mat2"===t)s=new zN(e);else if("mat3"===t)s=new $N(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);s=new WN(e)}r.cache=s}return s}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${_t} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Ys(this.object).useVelocity}}class YN{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderId:0,frameId:0},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateBeforeMap,r);if(t.frameId!==this.frameId){const r=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=r)}}else if(t===ri.RENDER){const t=this._getMaps(this.updateBeforeMap,r);if(t.renderId!==this.renderId){const r=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=r)}}else t===ri.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateAfterMap,r);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateAfterMap,r);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateMap,r);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateMap,r);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&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 ZN{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}ZN.isNodeFunctionInput=!0;class JN extends gv{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class eS extends gv{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:v_(this.light),lightColor:e}}}class tS extends gv{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=x_(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Sa(new e).setGroup(_a)}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:r,lightDirectionNode:s}=this,i=Rc.dot(s).mul(.5).add(.5),n=gu(r,t,i);e.context.irradiance.addAssign(n)}}class rS extends gv{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Sa(0).setGroup(_a),this.penumbraCosNode=Sa(0).setGroup(_a),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(0).setGroup(_a),this.colorNode=Sa(this.color).setGroup(_a)}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:r,penumbraCosNode:s}=this;return bu(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=b_(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(v_(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=mv({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=Kl(i.map,h.xy).onRenderUpdate(()=>i.map)),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class sS extends rS{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);s=Kl(r,_n(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}class iS extends gv{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new r);this.lightProbe=td(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=pN(Rc,this.lightProbe);e.context.irradiance.addAssign(t)}}const nS=cn(([e,t])=>{const r=e.abs().sub(t);return Go(eu(r,0)).add(Jo(eu(r.x,r.y),0))});class aS extends rS{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=yn(0),r=this.penumbraCosNode,s=y_(this.light).mul(e.context.positionWorld||cc);return gn(s.w.greaterThan(0),()=>{const e=s.xyz.div(s.w),i=nS(e.xy.sub(_n(.5)),_n(.5)),n=Ua(-1,Pa(1,Do(r)).sub(1));t.assign(fu(i.mul(-2).mul(n)))}),t}}const oS=new a,uS=new a;let lS=null;class dS extends gv{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Sa(new r).setGroup(_a),this.halfWidth=Sa(new r).setGroup(_a),this.updateType=ri.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;uS.identity(),oS.copy(t.matrixWorld),oS.premultiply(r),uS.extractRotation(oS),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(uS),this.halfHeight.value.applyMatrix4(uS)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Kl(lS.LTC_FLOAT_1),r=Kl(lS.LTC_FLOAT_2)):(t=Kl(lS.LTC_HALF_1),r=Kl(lS.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:__(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){lS=e}}class cS{parseFunction(){d("Abstract function.")}}class hS{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){d("Abstract function.")}}hS.isNodeFunction=!0;const pS=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,gS=/[a-z_0-9]+/gi,mS="#pragma main";class fS extends hS{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(mS),r=-1!==t?e.slice(t+12):e,s=r.match(pS);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=gS.exec(i));)n.push(a);const o=[];let u=0;for(;u{let r=this._createNodeBuilder(e,e.material);try{t?await r.buildAsync():r.build()}catch(s){r=this._createNodeBuilder(e,new vg),t?await r.buildAsync():r.build(),o("TSL: "+s)}return r})().then(e=>(s=this._createNodeBuilderState(e),i.set(n,s),s.usedTimes++,r.nodeBuilderState=s,s));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(r){t=this._createNodeBuilder(e,new vg),t.build();let s=r.stackTrace;!s&&r.stack&&(s=new Is(r.stack)),o("TSL: "+r,s)}s=this._createNodeBuilderState(t),i.set(n,s)}}s.usedTimes++,r.nodeBuilderState=s}return s}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 r=this.getForRenderCacheKey(e),s=this.nodeBuilderCache.get(r);return void 0!==s?(s.usedTimes++,t.nodeBuilderState=s,s):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let r=t.nodeBuilderState;if(void 0===r){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),r=this._createNodeBuilderState(s),t.nodeBuilderState=r}return r}_createNodeBuilderState(e){return new xN(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const r=this.get(e);r.environmentNode&&(t=r.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const r=this.get(e);r.backgroundNode&&(t=r.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){bS[0]=e,bS[1]=t;const r=this.renderer.info.calls,s=this.callHashCache.get(bS)||{};if(s.callId!==r){const i=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&xS.push(t.getCacheKey(!0)),i&&xS.push(i.getCacheKey()),n&&xS.push(n.getCacheKey()),xS.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),xS.push(this.renderer.shadowMap.enabled?1:0),xS.push(this.renderer.shadowMap.type),s.callId=r,s.cacheKey=ks(xS),this.callHashCache.set(bS,s),xS.length=0}return bS[0]=null,bS[1]=null,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),r=e.background;if(r){const s=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,()=>{if(!0===r.isCubeTexture||r.mapping===ce||r.mapping===he||r.mapping===Ae){if(e.backgroundBlurriness>0||r.mapping===Ae)return Vf(r);{let e;return e=!0===r.isCubeTexture?$c(r):Kl(r),Ig(e)}}if(!0===r.isTexture)return Kl(r,ud.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&o("WebGPUNodes: Unsupported background configuration.",r)},s);t.backgroundNode=i,t.background=r,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(e){const t=this.get(e),r=e.fog;if(r){if(t.fog!==r){const e=this.getCacheNode("fog",r,()=>{if(r.isFogExp2){const e=qc("color","color",r).setGroup(_a),t=qc("density","float",r).setGroup(_a);return ST(e,vT(t))}if(r.isFog){const e=qc("color","color",r).setGroup(_a),t=qc("near","float",r).setGroup(_a),s=qc("far","float",r).setGroup(_a);return ST(e,_T(t,s))}o("Renderer: Unsupported fog configuration.",r)});t.fogNode=e,t.fog=r}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),r=e.environment;if(r){if(t.environment!==r){const e=this.getCacheNode("environment",r,()=>!0===r.isCubeTexture?$c(r):!0===r.isTexture?Kl(r):void o("Nodes: Unsupported environment configuration.",r));t.environmentNode=e,t.environment=r}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Kl(e,ud).depth(sd("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Kl(e,ud).renderOutput(t.toneMapping,t.currentColorSpace)}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new YN,this.nodeBuilderCache=new Map,this.cacheLib={}}}const _S=new ut;class vS{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,r){const s=e.length;for(let i=0;iLl(e,i.toneMapping,i.outputColorSpace)}),FS.set(r,n))}else n=r;i.contextNode=n,i.setRenderTarget(t.renderTarget),t.rendercall(),i.contextNode=r}i.setRenderTarget(o),i._setXRLayerSize(a.x,a.y),this.isPresenting=n}getSession(){return this._session}async setSession(e){const t=this._renderer,r=t.backend;this._gl=t.getContext();const s=this._gl,i=s.getContextAttributes();if(this._session=e,null!==e){if(!0===r.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await r.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let r=null,n=null,a=null;t.depth&&(a=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,r=t.stencil?qe:He,n=t.stencil?Ze:S);const o={colorFormat:s.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(o),l=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,c=new Z(u.textureWidth,u.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,r,d);if(this._xrRenderTarget=new MS(u.textureWidth,u.textureHeight,{format:Ee,type:Ve,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.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 fe({color:16777215,side:"cylinder"===e.type?F:St}),e.plane.material.blending=Rt,e.plane.material.blendEquation=it,e.plane.material.blendSrc=Et,e.plane.material.blendDst=Et,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{const r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,s,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new MS(i.framebufferWidth,i.framebufferHeight,{format:Ee,type:Ve,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=-5&i.layers.mask,a.layers.mask=-3&i.layers.mask;const o=e.parent,u=i.cameras;DS(i,o);for(let e=0;e=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function VS(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 kS(e,t){if(void 0===t)return;const r=this._cameraXR,i=this._renderer,n=i.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views;null!==this._glBaseLayer&&n.setXRTarget(a.framebuffer);let t=!1;e.length!==r.cameras.length&&(r.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const s=this._renderLists.get(e,t),i=this._renderContexts.get(this._renderTarget,this._mrt),n=e.overrideMaterial||r.material,a=this._objects.get(r,n,e,t,s.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:u}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:u}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new TS(this,r),this._animation=new xy(this,this._nodes,this.info),this._attributes=new By(r,this.info),this._background=new fN(this,this._nodes),this._geometries=new Dy(this._attributes,this.info),this._textures=new tb(this,r,this.info),this._pipelines=new zy(r,this._nodes,this.info),this._bindings=new $y(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Sy(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Ky(this.lighting),this._bundles=new RS,this._renderContexts=new Jy(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,u=this._compilationPromises;null===r&&(r=e);const l=!0===e.isScene?e:!0===r.isScene?r:$S,d=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(d,this._mrt),h=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,s.renderId++,s.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new vS),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const g=this._renderLists.get(l,t);if(g.begin(),this._projectObject(e,t,0,g,c.clippingContext),r!==e&&r.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&g.pushLight(e)}),g.finish(),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;r!==e?this._background.update(r,g,c):this._background.update(l,g,c);const m=g.opaque,f=g.transparent,y=g.transparentDoublePass,b=g.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,l,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,l,b),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=u;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,this._geometries.updateForRender(t),await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const r=[];this._pipelines.getForRender(t,r),r.length>0&&await Promise.all(r),this._nodes.updateAfter(t),await Tt()}}async renderAsync(e,t){v('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){o("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=nc,t.modelNormalViewMatrix=ac):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===nc&&e.modelNormalViewMatrix===ac}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return v('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}`),o(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i,a),u=this.backend.get(o),l=s.version!==u.version;if(l||void 0===u.bundleGPU){this.backend.beginBundle(a),(void 0===u.renderObjects||l)&&(u.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:d,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,i,t,r),!0===this.transparent&&d.length>0&&this._renderTransparents(d,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t{u.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(u)};u.addEventListener("dispose",e),this._frameBufferTargets.set(u,l)}const d=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==d?l.setSize(d.width,d.height,d.depth):l.setSize(i,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:u._viewport,h=this._outputRenderTarget?this._outputRenderTarget.scissor:u._scissor,g=this._outputRenderTarget?1:u._pixelRatio,f=this._outputRenderTarget?this._outputRenderTarget.scissorTest:u._scissorTest;return l.viewport.copy(c),l.scissor.copy(h),l.viewport.multiplyScalar(g),l.scissor.multiplyScalar(g),l.scissorTest=f,l.multiview=null!==d&&d.multiview,l.resolveDepthBuffer=null===d||d.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==d&&d._autoAllocateDepthBuffer,l}_renderScene(e,t,r=!0){if(!0===this._isDeviceLost)return;const s=r?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,u=this._handleObjectFunction;this._callDepth++;const l=!0===e.isScene?e:$S,d=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let p;if(null!==s?(p=s,this.setRenderTarget(p)):p=d,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p);const m=this.xr;if(!1===m.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const r=this.coordinateSystem;if(t.coordinateSystem!==r){if(t.coordinateSystem=r,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=r;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,x=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,x=1),this.getDrawingBufferSize(WS),HS.set(0,0,WS.width,WS.height);const T=void 0===y.minDepth?0:y.minDepth,_=void 0===y.maxDepth?1:y.maxDepth;g.viewportValue.copy(y).multiplyScalar(x).floor(),g.viewportValue.width>>=h,g.viewportValue.height>>=h,g.viewportValue.minDepth=T,g.viewportValue.maxDepth=_,g.viewport=!1===g.viewportValue.equals(HS),g.scissorValue.copy(b).multiplyScalar(x).floor(),g.scissor=f._scissorTest&&!1===g.scissorValue.equals(HS),g.scissorValue.width>>=h,g.scissorValue.height>>=h,g.clippingContext||(g.clippingContext=new vS),g.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const v=t.isArrayCamera?jS:qS;t.isArrayCamera||(XS.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(XS,t.coordinateSystem,t.reversedDepth));const N=this._renderLists.get(e,t);if(N.begin(),this._projectObject(e,t,0,N,g.clippingContext),N.finish(),!0===this.sortObjects&&N.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,h);const e=this._textures.get(p);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=WS.width,g.height=WS.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=h,g.height>>=h,g.activeCubeFace=c,g.activeMipmapLevel=h,g.occlusionQueryCount=N.occlusionQueryCount,g.scissorValue.max(KS.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(l,N,g),g.camera=t,this.backend.beginRender(g);const{bundles:S,lightsNode:R,transparentDoublePass:E,transparent:A,opaque:w}=N;return S.length>0&&this._renderBundles(S,l,R),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,R),!0===this.transparent&&A.length>0&&this._renderTransparents(A,E,t,l,R),this.backend.finishRender(g),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=u,this._callDepth--,null!==s&&(this.setRenderTarget(d,c,h),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_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 r,s=this._quadCache.get(e.texture);if(void 0===s){r=new gx(new vg),r.name="Output Color Transform",r.material.name="outputColorTransform",r.material.fragmentNode=this._nodes.getOutputNode(e.texture),s={quad:r,cacheKey:t},this._quadCache.set(e.texture,s);const i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",i)};e.texture.addEventListener("dispose",i)}else r=s.quad,s.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,s.cacheKey=t);const i=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(r,r.camera,!1),this.autoClear=i,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){let t=e;if(!0!==t.isReadbackBuffer){const r=e,s=this.backend.get(r);if(t=s.readbackBuffer,void 0===t){t=new zS(r);const e=()=>{r.removeEventListener("dispose",e),t.dispose(),delete s.readbackBuffer};r.addEventListener("dispose",e),s.readbackBuffer=t}}if(!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}return t.release(),await this.backend.getArrayBufferAsync(t)}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,r){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,r)}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,r)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,r,s){this._canvasTarget.setScissor(e,t,r,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,r,s,i=0,n=1){this._canvasTarget.setViewport(e,t,r,s,i,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.get(s,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer;const t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),!0===s.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){v('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,r)}async clearColorAsync(){v('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){v('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){v('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==m,t=this.currentColorSpace!==p.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:m}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:p.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!0===this._initialized){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}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 d("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.deleteForCompute(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s,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 v('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){v('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),r=this._renderContexts.get(e);r.textures=t.textures,r.depthTexture=t.depthTexture,r.width=t.width,r.height=t.height,r.renderTarget=e,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,this.backend.initRenderTarget(r)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=KS.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void o("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=KS.copy(t).floor()}else t=KS.set(0,0,e.image.width,e.image.height);let r,s=this._currentRenderContext;null!==s?r=s.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),null!==r&&(this._textures.updateRenderTarget(r),s=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,s,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(e,t,r,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)r=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?jS:qS;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&KS.setFromMatrixPosition(e.matrixWorld).applyMatrix4(XS);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,KS.z,null,i)}}else if(e.isLineLoop)o("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?jS:qS;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),KS.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(XS)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=F;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=St;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=P}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n(t.not().discard(),e))(u)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),r={version:t,colorNode:u,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,r)}return r}renderObject(e,t,r,s,i,n,a,o=null,u=null){let l,d,c,h,p=!1;if(e.onBeforeRender(this,t,r,s,i,n),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,l=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,h=t.overrideMaterial.side,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:r,positionNode:s}=this._getShadowNodes(i);this.shadowMap.type===pt?e.side=null!==i.shadowSide?i.shadowSide:i.side:e.side=null!==i.shadowSide?i.shadowSide:QS[i.side],null!==t&&(e.colorNode=t),null!==r&&(e.depthNode=r),null!==s&&(e.positionNode=s)}i=e}!0===i.transparent&&i.side===P&&!1===i.forceSinglePass?(i.side=F,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=St,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=P):this._handleObjectFunction(e,i,t,r,a,n,o,u),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=h),e.onAfterRender(this,t,r,s,i,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);if(u.drawRange=e.geometry.drawRange,u.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(u);l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),this._pipelines.isReady(u)&&(this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u))}_createObjectPipeline(e,t,r,s,i,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:r,camera:s,lightsNode:i,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class ZS{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class JS extends ZS{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(My-e%My)%My;var e}get buffer(){return this._buffer}update(){return!0}}class eR extends JS{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let tR=0;class rR extends eR{constructor(e,t){super("UniformBuffer_"+tR++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class sR extends eR{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const r=this.updateRanges,s={start:e.offset,count:e.itemSize};r.push(s),this._updateRangeCache.set(t,s)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let oR=0;class uR extends aR{constructor(e,t){super(e,t),this.id=oR++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class lR extends uR{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class dR extends lR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class cR extends lR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const hR={bitcast_int_uint:new fT("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new fT("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},pR={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},gR={low:"lowp",medium:"mediump",high:"highp"},mR={swizzleAssign:!0,storageBuffer:!1},fR={perspective:"smooth",linear:"noperspective"},yR={centroid:"centroid"},bR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class xR extends QN{constructor(e,t){super(e,t,new yS),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==T}_include(e){const t=hR[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==hR[e]&&this._include(e),pR[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?We:$e;2===s?n=i?je:$:3===s?n=i?Ke:Xe:4===s&&(n=i?Ft:Ee);const a={Float32Array:K,Uint8Array:Ve,Uint16Array:Ge,Uint32Array:S,Int8Array:Oe,Int16Array:ke,Int32Array:R,Uint8ClampedArray:Ve},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s0?i:"";t=`${r.name} {\n\t${s} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===s[t]){const e=this.uniformGroups[t];if(void 0!==e){const r=[];for(const t of e.uniforms){const e=t.getType(),s=this.getVectorType(e),i=t.nodeUniform.node.precision;let n=`${s} ${t.name};`;null!==i&&(n=gR[i]+" "+n),r.push("\t"+n)}s[t]=r}}i=!0}if(!i){const s=e.node.precision;null!==s&&(t=gR[s]+" "+t),t="uniform "+t,r.push(t)}}let i="";for(const e in s){const t=s[e];i+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==R){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return 0===s.length&&s.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${fR[s.interpolationType]||s.interpolationType} ${yR[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${fR[e.interpolationType]||e.interpolationType} ${yR[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){o("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){o("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){o("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,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.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 r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=mR[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}mR[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 r=0;r0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${s.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${s.result};`)))}const n=e[t];if(n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new lR(i.name,i.node,s),u.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new dR(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new cR(i.name,i.node,s),u.push(a);else if("buffer"===t){i.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let r=t.buffer;void 0===r&&(e.name=`NodeBuffer_${e.id}`,r=new rR(e,s),r.name=e.name,t.buffer=r),u.push(r),a=r}else{let e=this.uniformGroups[o];void 0===e?(e=new nR(o,s),this.uniformGroups[o]=e,u.push(e)):-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}}let TR=null,_R=null;class vR{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Pt.RENDER]:null,[Pt.COMPUTE]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),r=this.renderer.info.frame;let s;s=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+r}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:")?Pt.COMPUTE:Pt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void v("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return TR=TR||new t,this.renderer.getDrawingBufferSize(TR)}setScissorTest(){}getClearColor(){const e=this.renderer;return _R=_R||new rb,e.getClearColor(_R),_R.getRGB(_R),_R}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Dt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${_t} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let NR,SR,RR=0;class ER{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 AR{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===R,id:RR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new ER(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e{r.deleteBuffer(l),t.delete(e),e.removeEventListener("dispose",s)};e.addEventListener("dispose",s),u.writeBuffer=l}else r.bindBuffer(r.COPY_WRITE_BUFFER,l);r.copyBufferSubData(r.COPY_READ_BUFFER,r.COPY_WRITE_BUFFER,0,0,o),await t.utils._clientWaitAsync();const d=new s.array.constructor(a.length);return r.bindBuffer(r.COPY_WRITE_BUFFER,l),r.getBufferSubData(r.COPY_WRITE_BUFFER,0,d),r.bindBuffer(r.COPY_READ_BUFFER,null),r.bindBuffer(r.COPY_WRITE_BUFFER,null),d}_createBuffer(e,t,r,s){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,r,s),e.bindBuffer(t,null),i}}class wR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;NR={[it]:e.FUNC_ADD,[It]:e.FUNC_SUBTRACT,[Ut]:e.FUNC_REVERSE_SUBTRACT},SR={[Et]:e.ZERO,[Ht]:e.ONE,[Wt]:e.SRC_COLOR,[rt]:e.SRC_ALPHA,[$t]:e.SRC_ALPHA_SATURATE,[zt]:e.DST_COLOR,[Gt]:e.DST_ALPHA,[kt]:e.ONE_MINUS_SRC_COLOR,[st]:e.ONE_MINUS_SRC_ALPHA,[Vt]:e.ONE_MINUS_DST_COLOR,[Ot]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),r=e.getParameter(e.VIEWPORT);this.currentScissor=(new s).fromArray(t),this.currentViewport=(new s).fromArray(r),this._tempVec4=new s}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;e!==qt?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===jt?t.cullFace(t.BACK):e===Xt?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:r}=this;e!==t&&(r.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,r){const s=this.gl,i=this.backend.drawBuffersIndexedExt;if(i)for(let n=0;n0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()})}}let MR,BR,LR,FR=!1;class PR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===FR&&(this._init(),FR=!0)}_init(){const e=this.gl;MR={[kr]:e.REPEAT,[_e]:e.CLAMP_TO_EDGE,[Vr]:e.MIRRORED_REPEAT},BR={[B]:e.NEAREST,[Gr]:e.NEAREST_MIPMAP_NEAREST,[bt]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[yt]:e.LINEAR_MIPMAP_NEAREST,[Y]:e.LINEAR_MIPMAP_LINEAR},LR={[Hr]:e.NEVER,[Wr]:e.ALWAYS,[A]:e.LESS,[w]:e.LEQUAL,[$r]:e.EQUAL,[M]:e.GEQUAL,[C]:e.GREATER,[zr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!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,r}getInternalFormat(e,t,r,s,i,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];d("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let u=null;s&&(u=o.get("EXT_texture_norm16"),u||d("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(r===a.FLOAT&&(l=a.R32F),r===a.HALF_FLOAT&&(l=a.R16F),r===a.UNSIGNED_BYTE&&(l=a.R8),r===a.BYTE&&(l=a.R8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.R16_EXT),r===a.SHORT&&u&&(l=u.R16_SNORM_EXT)),t===a.RED_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.R8UI),r===a.UNSIGNED_SHORT&&(l=a.R16UI),r===a.UNSIGNED_INT&&(l=a.R32UI),r===a.BYTE&&(l=a.R8I),r===a.SHORT&&(l=a.R16I),r===a.INT&&(l=a.R32I)),t===a.RG&&(r===a.FLOAT&&(l=a.RG32F),r===a.HALF_FLOAT&&(l=a.RG16F),r===a.UNSIGNED_BYTE&&(l=a.RG8),r===a.BYTE&&(l=a.RG8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RG16_EXT),r===a.SHORT&&u&&(l=u.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RG8UI),r===a.UNSIGNED_SHORT&&(l=a.RG16UI),r===a.UNSIGNED_INT&&(l=a.RG32UI),r===a.BYTE&&(l=a.RG8I),r===a.SHORT&&(l=a.RG16I),r===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGB32F),r===a.HALF_FLOAT&&(l=a.RGB16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8:a.RGB8),r===a.BYTE&&(l=a.RGB8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGB16_EXT),r===a.SHORT&&u&&(l=u.RGB16_SNORM_EXT),r===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),r===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),r===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGB8UI),r===a.UNSIGNED_SHORT&&(l=a.RGB16UI),r===a.UNSIGNED_INT&&(l=a.RGB32UI),r===a.BYTE&&(l=a.RGB8I),r===a.SHORT&&(l=a.RGB16I),r===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGBA32F),r===a.HALF_FLOAT&&(l=a.RGBA16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8_ALPHA8:a.RGBA8),r===a.BYTE&&(l=a.RGBA8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGBA16_EXT),r===a.SHORT&&u&&(l=u.RGBA16_SNORM_EXT),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),r===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),r===a.UNSIGNED_INT&&(l=a.RGBA32UI),r===a.BYTE&&(l=a.RGBA8I),r===a.SHORT&&(l=a.RGBA16I),r===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(r===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),r===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),r===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&r===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,{state:n}=this.backend,a=p.getPrimaries(p.workingColorSpace),o=t.colorSpace===T?null:p.getPrimaries(t.colorSpace),u=t.colorSpace===T||a===o?r.NONE:r.BROWSER_DEFAULT_WEBGL;n.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,u),r.texParameteri(e,r.TEXTURE_WRAP_S,MR[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,MR[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,MR[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,BR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,d=t.minFilter===le&&l?Y:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,BR[d]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,LR[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===B)return;if(t.minFilter!==bt&&t.minFilter!==Y)return;if(t.type===K&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i})}createTexture(e,t){const{gl:r,backend:s}=this,{levels:i,width:n,height:a,depth:o}=t,u=s.utils.convert(e.format,e.colorSpace),l=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.normalized,e.colorSpace,e.isVideoTexture),c=r.createTexture(),h=this.getGLTextureType(e);s.state.bindTexture(h,c),this.setTextureParameters(h,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,i,d,n,a,o):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,i,d,n,a,o):e.isVideoTexture||r.texStorage2D(h,i,d,n,a),s.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{state:i}=s,{textureGPU:n,glTextureType:a,glFormat:o,glType:u}=s.get(t),{width:l,height:d}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(a,n),i.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(a,0,0,0,l,d,o,u,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t0){const t=jr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function DR(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 UR{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 IR{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 r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.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 OR={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 VR{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:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;sthis.maxQueries)return v(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){o("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){o("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,r]of this.queryOffsets){if("ended"===this.queryStates.get(r)){const s=this.queries[r];e.set(t,this.resolveQuery(s))}}if(0===e.size)return this.lastValue;const t={},r=[];for(const[s,i]of e){const e=s.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===r.includes(n)&&r.push(n),void 0===t[n]&&(t[n]=0);const a=await i;this.timestamps.set(s,a),t[n]+=a}const s=t[r[r.length-1]];return this.lastValue=s,this.frames=r,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return o("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 r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){o("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class zR extends vR{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,r={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new UR(this),this.capabilities=new IR(this),this.attributeUtils=new AR(this),this.textureUtils=new PR(this),this.bufferRenderer=new VR(this),this.state=new wR(this),this.utils=new CR(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:(d("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 c}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&d("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 GR(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.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,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.scissor(0,0,e,r)}this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e{let a=0;for(let t=0;t1?t.renderInstances(r,s,i):t.render(r,s)}draw(e){const{object:t,pipeline:r,material:s,context:i,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(r),{gl:o,state:u}=this,l=this.get(i),d=e.getDrawParameters();if(null===d)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;u.setMaterial(s,c,n),null!==i.mrt&&null!==i.textures&&u.setMRTBlending(i.textures,i.mrt,s),u.useProgram(a);const h=e.getAttributes(),p=this.get(h);let g=p.vaoGPU;if(void 0===g){const e=this._getVaoKey(h);g=this.vaoCache[e],void 0===g&&(g=this._createVao(h),this.vaoCache[e]=g,p.vaoGPU=g)}const m=e.getIndex(),f=null!==m?this.get(m).bufferGPU:null;u.setVertexState(g,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===s.wireframe?(u.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:x,instanceCount:T}=d;let{firstVertex:_}=d;if(b.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);b.index=m.count,b.type=e.type}else b.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()});return void t.push(i)}this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(e,t,r){if(this.renderer.debug.checkShaderErrors){const s=this.gl,i=(s.getProgramInfoLog(e)||"").trim();if(!1===s.getProgramParameter(e,s.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(s,e,r,t);else{const n=this._getShaderErrors(s,r,"vertex"),a=this._getShaderErrors(s,t,"fragment");o("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+n+"\n"+a)}else""!==i&&d("WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;eOR[t]===e),r=this.extensions;for(let e=0;e1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=Zy(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const $R="point-list",WR="line-list",HR="line-strip",qR="triangle-list",jR="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},XR="never",KR="less",QR="equal",YR="less-equal",ZR="greater",JR="not-equal",eE="greater-equal",tE="always",rE="store",sE="load",iE="clear",nE="ccw",aE="cw",oE="none",uE="back",lE="uint16",dE="uint32",cE="r8unorm",hE="r8snorm",pE="r8uint",gE="r8sint",mE="r16uint",fE="r16sint",yE="r16float",bE="rg8unorm",xE="rg8snorm",TE="rg8uint",_E="rg8sint",vE="r16unorm",NE="r16snorm",SE="r32uint",RE="r32sint",EE="r32float",AE="rg16uint",wE="rg16sint",CE="rg16float",ME="rgba8unorm",BE="rgba8unorm-srgb",LE="rgba8snorm",FE="rgba8uint",PE="rgba8sint",DE="bgra8unorm",UE="bgra8unorm-srgb",IE="rg16unorm",OE="rg16snorm",VE="rgb9e5ufloat",kE="rgb10a2unorm",GE="rg11b10ufloat",zE="rg32uint",$E="rg32sint",WE="rg32float",HE="rgba16uint",qE="rgba16sint",jE="rgba16float",XE="rgba16unorm",KE="rgba16snorm",QE="rgba32uint",YE="rgba32sint",ZE="rgba32float",JE="depth16unorm",eA="depth24plus",tA="depth24plus-stencil8",rA="depth32float",sA="depth32float-stencil8",iA="bc1-rgba-unorm",nA="bc1-rgba-unorm-srgb",aA="bc2-rgba-unorm",oA="bc2-rgba-unorm-srgb",uA="bc3-rgba-unorm",lA="bc3-rgba-unorm-srgb",dA="bc4-r-unorm",cA="bc4-r-snorm",hA="bc5-rg-unorm",pA="bc5-rg-snorm",gA="bc6h-rgb-ufloat",mA="bc6h-rgb-float",fA="bc7-rgba-unorm",yA="bc7-rgba-unorm-srgb",bA="etc2-rgb8unorm",xA="etc2-rgb8unorm-srgb",TA="etc2-rgb8a1unorm",_A="etc2-rgb8a1unorm-srgb",vA="etc2-rgba8unorm",NA="etc2-rgba8unorm-srgb",SA="eac-r11unorm",RA="eac-r11snorm",EA="eac-rg11unorm",AA="eac-rg11snorm",wA="astc-4x4-unorm",CA="astc-4x4-unorm-srgb",MA="astc-5x4-unorm",BA="astc-5x4-unorm-srgb",LA="astc-5x5-unorm",FA="astc-5x5-unorm-srgb",PA="astc-6x5-unorm",DA="astc-6x5-unorm-srgb",UA="astc-6x6-unorm",IA="astc-6x6-unorm-srgb",OA="astc-8x5-unorm",VA="astc-8x5-unorm-srgb",kA="astc-8x6-unorm",GA="astc-8x6-unorm-srgb",zA="astc-8x8-unorm",$A="astc-8x8-unorm-srgb",WA="astc-10x5-unorm",HA="astc-10x5-unorm-srgb",qA="astc-10x6-unorm",jA="astc-10x6-unorm-srgb",XA="astc-10x8-unorm",KA="astc-10x8-unorm-srgb",QA="astc-10x10-unorm",YA="astc-10x10-unorm-srgb",ZA="astc-12x10-unorm",JA="astc-12x10-unorm-srgb",ew="astc-12x12-unorm",tw="astc-12x12-unorm-srgb",rw="clamp-to-edge",sw="repeat",iw="mirror-repeat",nw="linear",aw="nearest",ow="zero",uw="one",lw="src",dw="one-minus-src",cw="src-alpha",hw="one-minus-src-alpha",pw="dst",gw="one-minus-dst",mw="dst-alpha",fw="one-minus-dst-alpha",yw="src-alpha-saturated",bw="constant",xw="one-minus-constant",Tw="add",_w="subtract",vw="reverse-subtract",Nw="min",Sw="max",Rw=0,Ew=15,Aw="keep",ww="zero",Cw="replace",Mw="invert",Bw="increment-clamp",Lw="decrement-clamp",Fw="increment-wrap",Pw="decrement-wrap",Dw="storage",Uw="read-only-storage",Iw="write-only",Ow="read-only",Vw="read-write",kw="non-filtering",Gw="comparison",zw="float",$w="unfilterable-float",Ww="depth",Hw="sint",qw="uint",jw="2d",Xw="3d",Kw="2d",Qw="2d-array",Yw="cube",Zw="3d",Jw="all",eC="vertex",tC="instance",rC={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"},sC={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class iC extends aR{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class nC extends JS{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let aC=0;class oC extends nC{constructor(e,t){super("StorageBuffer_"+aC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ii.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class uC extends Ry{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:nw}),this.flipYSampler=e.createSampler({minFilter:aw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const r=`${e}-${t=t||"2d-array"}`;let s=this.transferPipelines[r];return void 0===s&&(s=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[r]=s),s}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.device.createTexture({size:{width:i,height:n},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(s,e.textureBindingViewDimension),u=this.getTransferPipeline(s,a.textureBindingViewDimension),l=this.device.createCommandEncoder({}),d=(e,t,r,s,i,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),u=l.beginRenderPass({colorAttachments:[{view:s.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:i,arrayLayerCount:1}),loadOp:iE,storeOp:rE}]});u.setPipeline(e),u.setBindGroup(0,o),u.draw(3,1,0,r),u.end()};d(o,e,r,a,0,!1),d(u,a,0,e,r,!0),this.device.queue.submit([l.finish()]),a.destroy()}generateMipmaps(e,t=null){const r=this.get(e),s=r.layers||this._mipmapCreateBundles(e),i=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(i,s),null===t&&this.device.queue.submit([i.finish()]),r.layers=s}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",r=this.getTransferPipeline(e.format,t),s=r.getBindGroupLayout(0),i=[];for(let n=1;n0)for(let t=0,n=s.length;t0){for(const s of e.layerUpdates)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);e.clearLayerUpdates()}else for(let s=0;s0)for(let t=0,n=s.length;t{const t=e.changedElements;for(const e of r)t.includes(e.image)&&(e.needsUpdate=!0)}}dispose(){this._samplerCache.clear(),this._htmlTextures.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new N;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,format:e}),this.defaultTexture[e]=t=r}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const r=new D;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=r}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,r){const s=e.images,i=e.mipmaps;for(let n=0;n<6;n++){const a=s[n],o=!0===e.flipY?dC[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha);for(let s=0;s0?e.width:r.size.width,l=a>0?e.height:r.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:n},{width:u,height:l,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new uC(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},u,{offset:e.width*e.height*l*n,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r){const s=this.backend.device,i=this._getBlockData(r.format),n=r.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,gC=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,mC={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",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 fC extends hS{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(pC);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=gC.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class yC extends cS{parseFunction(e){return new fC(e)}}const bC={[ii.READ_ONLY]:"read",[ii.WRITE_ONLY]:"write",[ii.READ_WRITE]:"read_write"},xC={[kr]:"repeat",[_e]:"clamp",[Vr]:"mirror"},TC={vertex:jR.VERTEX,fragment:jR.FRAGMENT,compute:jR.COMPUTE},_C={instance:!0,swizzleAssign:!1,storageBuffer:!0},vC={"^^":"tsl_xor"},NC={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},SC={},RC={tsl_xor:new fT("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new fT("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new fT("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new fT("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new fT("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new fT("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new fT("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new fT("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new fT("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new fT("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new fT("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 fT("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new fT("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new fT("\nfn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},EC={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let AC="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(AC+="diagnostic( off, derivative_uniformity );\n");class wC extends QN{constructor(e,t){super(e,t,new yC),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${xC[e.wrapS]}S_${xC[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let r=SC[t];if(void 0===r){const s=[],i=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===kr?(s.push(RC.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===_e?(s.push(RC.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Vr?(s.push(RC.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,d(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",SC[t]=r=new fT(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Du(new wl(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Du(new wl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Du(new wl("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2(${s}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${r} ), ${o}, u32( ${n} ), u32( ${i} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${r} ), ${o}, u32( ${i} ) )`)}generateTextureLod(e,t,r,s,i,n="0u"){if(!0===e.isCubeTexture){i&&(r=`${r} + vec3(${i})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}(${i}) / ${u}( ${o} )`);return r=`${u}( clamp( floor( ${a}( ${r} ) * ${u}( ${o} ) ), ${`${u}( 0 )`}, ${`${u}( ${o} - ${"vec3"===u?"vec3( 1, 1, 1 )":"vec2( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,r,n,s,null)}generateStorageTextureLoad(e,t,r,s,i,n){let a;return n&&(r=`${r} + ${n}`),a=i?`textureLoad( ${t}, ${r}, ${i} )`:`textureLoad( ${t}, ${r} )`,a}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0u"),n&&(r=`${r} + ${n}`),i?a=`textureLoad( ${t}, ${r}, ${i}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(E.TEXTURE_COMPARE)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===K||!1===this.isSampleCompare(e)&&e.minFilter===B&&e.magFilter===B||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;o(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`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,r=e.type;return"texture"===r||"cubeTexture"===r||"cubeDepthTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=vC[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(d("WebGPURenderer: Atomic operations are only supported in compute shaders."),ii.READ_WRITE):ii.READ_ONLY:e.access}getStorageAccess(e,t){return bC[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);"texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new cR(i.name,i.node,o,n):new lR(i.name,i.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?s=new dR(i.name,i.node,o,n):"texture3D"===t&&(s=new cR(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(TC[r]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new iC(`${i.name}_sampler`,i.node,o);e.setVisibility(TC[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let u=n.buffer;if(void 0===u){u=new("buffer"===t?rR:oC)(e,o),n.buffer=u}u.setVisibility(u.getVisibility()|TC[r]),l.push(u),a=u,i.name=s||"NodeBuffer_"+i.id}else{let e=this.uniformGroups[u];void 0===e&&(e=new nR(u,o),e.setVisibility(jR.VERTEX|jR.FRAGMENT|jR.COMPUTE),this.uniformGroups[u]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),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,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null,s=""){let i=`var${s} ${t} : `;return i+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),i}getVars(e,t=!1){let r="";t&&(r="");const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count,r)};`);return t?s.join("\n"):`\n\t${s.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];let i=0;for(let n=0;nr.value.itemSize;return s&&!i}getUniforms(e){const t=this.renderer.backend,r=this.uniforms[e],s=[],i=[],n=[],a={};for(const n of r){const r=n.groupNode.name,o=this.bindingsIndexes[r];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const r=n.node.value;let i;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==n.node.isStorageTextureNode)&&(this.isSampleCompare(r)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let a="";const{primarySamples:u}=t.utils.getTextureSampleData(r);if(u>1&&(a="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)i="texture_depth_cube";else if(!0===r.isCubeTexture)i="texture_cube";else if(!0===r.isDepthTexture)i=t.compatibilityMode&&null===r.compareFunction?`texture${a}_2d`:`texture_depth${a}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const s=hC(r,t.device),a=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,u=n.node.value.isArrayTexture;i=`texture_storage_${o?"3d":"2d"+(u?"_array":"")}<${s}, ${a}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture)i="texture_2d_array";else if(!0===r.is3DTexture||!0===r.isData3DTexture)i="texture_3d";else{i=`texture${a}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${i};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,r=this.getType(t.getNodeType(this)),s=t.bufferCount,a=s>0&&"buffer"===n.type?", "+s:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${u}> ${n.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${a} >`;i.push(this._getWGSLStructBinding(n.name,e,u,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const r=[];for(const e of t.uniforms){const t=e.getType(),s=this.getType(this.getVectorType(t));r.push(`\t${e.name} : ${s}`)}let s=this.uniformGroupsBindings[e];void 0===s&&(s={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=s),a[e]={index:s.index,id:s.id,snippets:r}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=this.allowGlobalVariables,s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t,r),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,u=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const r=this.getFlowData(e),n=e.name;if(n&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${n}\n`),i+=`${r.code}\n\t`,e===a&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(u)s.returnType=o.getNodeType(this),s.structs+="var output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location( 0 ) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return NC[e]||e}isAvailable(e){let t=_C[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),_C[e]=t),t}_getWGSLMethod(e){return void 0!==RC[e]&&this._include(e),EC[e]}_include(e){const t=RC[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${AC}\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[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\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 * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * 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,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class CC{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?sA:tA:!0===this.backend.renderer.reversedDepthBuffer?rA:eA),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}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?$R:e.isLineSegments||e.isMesh&&!0===t.wireframe?WR:e.isLine?HR:e.isMesh?qR:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ve)return DE;if(e===Te)return jE;throw new Error("Unsupported output buffer type.")}}const MC=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&MC.set(Float16Array,["float16"]);const BC=new Map([[xt,["float16"]]]),LC=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class FC{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o=r.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e{o.unmap()},u=()=>{o.destroy(),t.delete(e),e.removeEventListener("release",i),e.removeEventListener("dispose",u)};e.addEventListener("release",i),e.addEventListener("dispose",u),a.readBufferGPU=o}const u=r.createCommandEncoder({label:`readback_encoder_${s.name}`});u.copyBufferToBuffer(i,0,o,0,n);const l=u.finish();r.queue.submit([l]),await o.mapAsync(GPUMapMode.READ);return o.getMappedRange()}_getVertexFormat(e){const{itemSize:t,normalized:r}=e,s=e.array.constructor,i=e.constructor;let n;if(1===t)n=LC.get(s);else{const e=(BC.get(i)||MC.get(s))[r?1:0];if(e){const r=s.BYTES_PER_ELEMENT*t,i=4*Math.floor((r+3)/4)/s.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${i}`}}return n||o("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class PC{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class DC{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,r=t.device,s=t.get(e);if(s.layout)return s.layout.layoutGPU;const i=this._createLayoutEntries(e),n=Vs(JSON.stringify(i));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new PC(r.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,s.layout=a,s.layoutKey=n,a.layoutGPU}createBindings(e,t,r,s=0){const{backend:i}=this,n=i.get(e),a=this.createBindingsLayout(e);let o;r>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[r]===s&&(o=n.groups[r])),void 0===o&&(o=this.createBindGroup(e,a),r>0&&(n.groups[r]=o,n.versions[r]=s)),n.group=o}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer,n=e.updateRanges;if(0===n.length)r.queue.writeBuffer(i,0,s,0);else{const e=Xr(s),t=e?1:s.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${r}-${s}`,a=e[i],void 0===a){const n=Jw;let o;o=t.isSampledCubeTexture?Yw:t.isSampledTexture3D?Zw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Qw:Kw,a=e[i]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:r,baseMipLevel:s})}}n.push({binding:i,resource:a})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let r=0;for(const s of e.bindings){const e=this.backend,i={binding:r,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const e={};s.isStorageBuffer&&(s.visibility&jR.COMPUTE&&(s.access===ii.READ_WRITE||s.access===ii.WRITE_ONLY)?e.type=Dw:e.type=Uw),i.buffer=e}else if(s.isSampledTexture&&s.store){const e={};e.format=this.backend.get(s.texture).texture.format;const t=s.access;e.access=t===ii.READ_WRITE?Vw:t===ii.WRITE_ONLY?Iw:Ow,s.texture.isArrayTexture?e.viewDimension=Qw:s.texture.is3DTexture&&(e.viewDimension=Zw),i.storageTexture=e}else if(s.isSampledTexture){const t={},{primarySamples:r}=e.utils.getTextureSampleData(s.texture);if(r>1&&(t.multisampled=!0,s.texture.isDepthTexture||(t.sampleType=$w)),s.texture.isDepthTexture)e.compatibilityMode&&null===s.texture.compareFunction?t.sampleType=$w:t.sampleType=Ww;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture||s.texture.isStorageTexture){const e=s.texture.type;e===R?t.sampleType=Hw:e===S?t.sampleType=qw:e===K&&(this.backend.hasFeature("float32-filterable")?t.sampleType=zw:t.sampleType=$w)}s.isSampledCubeTexture?t.viewDimension=Yw:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?t.viewDimension=Qw:s.isSampledTexture3D&&(t.viewDimension=Zw),i.texture=t}else if(s.isSampler){const t={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction&&e.hasCompatibility(E.TEXTURE_COMPARE)?t.type=Gw:t.type=kw),i.sampler=t}else o(`WebGPUBindingUtils: Unsupported binding "${s}".`);t.push(i),r++}return t}deleteBindGroupData(e){const{backend:t}=this,r=t.get(e);r.layout&&(r.layout.usedTimes--,0===r.layout.usedTimes&&this._bindGroupLayoutCache.delete(r.layoutKey),r.layout=void 0,r.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class UC{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class IC{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:r,material:s,geometry:i,pipeline:n}=e,{vertexProgram:a,fragmentProgram:u}=n,l=this.backend,d=l.device,c=l.utils,h=l.get(n),p=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:r}=e.layout;p.push(r)}const g=l.attributeUtils.createShaderVertexBuffers(e);let m;s.blending===re||s.blending===tt&&!1===s.transparent||(m=this._getBlending(s));let f={};!0===s.stencilWrite&&(f={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const y=this._getColorWriteMask(s),b=[];if(null!==e.context.textures){const t=e.context.textures,r=e.context.mrt;for(let e=0;e1},layout:d.createPipelineLayout({bindGroupLayouts:p})},A={},w=e.context.depth,C=e.context.stencil;if(!0!==w&&!0!==C||(!0===w&&(A.format=S,A.depthWriteEnabled=s.depthWrite,A.depthCompare=N),!0===C&&(A.stencilFront=f,A.stencilBack=f,A.stencilReadMask=s.stencilFuncMask,A.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(A.depthBias=s.polygonOffsetUnits,A.depthBiasSlopeScale=s.polygonOffsetFactor,A.depthBiasClamp=0),E.depthStencil=A),d.pushErrorScope("validation"),null===t)h.pipeline=d.createRenderPipeline(E),d.popErrorScope().then(e=>{null!==e&&(h.error=!0,o(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await d.createRenderPipelineAsync(E)}catch(e){}const t=await d.popErrorScope();null!==t&&(h.error=!0,o(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:s.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e),{layoutGPU:s}=t.layout;a.push(s)}n.pipeline=s.createComputePipeline({compute:i,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,r;const s=e.blending,i=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(s===Rt){const s=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,u=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},r={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(u)}}else{const i=(e,s,i,n)=>{t={srcFactor:e,dstFactor:s,operation:Tw},r={srcFactor:i,dstFactor:n,operation:Tw}};if(e.premultipliedAlpha)switch(s){case tt:i(uw,hw,uw,hw);break;case Yt:i(uw,uw,uw,uw);break;case Qt:i(ow,dw,ow,uw);break;case Kt:i(pw,hw,ow,uw)}else switch(s){case tt:i(cw,hw,uw,hw);break;case Yt:i(cw,uw,uw,uw);break;case Qt:o(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Kt:o(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};o("WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Et:t=ow;break;case Ht:t=uw;break;case Wt:t=lw;break;case kt:t=dw;break;case rt:t=cw;break;case st:t=hw;break;case zt:t=pw;break;case Vt:t=gw;break;case Gt:t=mw;break;case Ot:t=fw;break;case $t:t=yw;break;case 211:t=bw;break;case 212:t=xw;break;default:o("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case rs:t=XR;break;case ts:t=tE;break;case es:t=KR;break;case Jr:t=YR;break;case Zr:t=QR;break;case Yr:t=eE;break;case Qr:t=ZR;break;case Kr:t=JR;break;default:o("WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case ds:t=Aw;break;case ls:t=ww;break;case us:t=Cw;break;case os:t=Mw;break;case as:t=Bw;break;case ns:t=Lw;break;case is:t=Fw;break;case ss:t=Pw;break;default:o("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case it:t=Tw;break;case It:t=_w;break;case Ut:t=vw;break;case hs:t=Nw;break;case cs:t=Sw;break;default:o("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?lE:dE);let n=r.side===F;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),s.frontFace=!0===n?aE:nE,s.cullMode=r.side===P?oE:uE,s}_getColorWriteMask(e){return!0===e.colorWrite?Ew:Rw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=tE;else{const r=this.backend.parameters.reversedDepthBuffer?ar[e.depthFunc]:e.depthFunc;switch(r){case nr:t=XR;break;case ir:t=tE;break;case sr:t=KR;break;case rr:t=YR;break;case tr:t=QR;break;case er:t=eE;break;case Jt:t=ZR;break;case Zt:t=JR;break;default:o("WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class OC extends kR{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r)),a={},o=[];for(const[t,r]of e){const e=t.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===o.includes(s)&&o.push(s),void 0===a[s]&&(a[s]=0);const i=n[r],u=n[r+1],l=Number(u-i)/1e6;this.timestamps.set(t,l),a[s]+=l}const u=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=u,this.frames=o,u}catch(e){return o("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){o("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){o("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const VC={r:0,g:0,b:0,a:1};class kC extends vR{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 CC(this),this.attributeUtils=new FC(this),this.bindingUtils=new DC(this),this.capabilities=new UC(this),this.pipelineUtils=new IC(this),this.textureUtils=new cC(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[E.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},s="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===s)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(rC),n=[];for(const e of i)s.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};r=await s.requestDevice(a)}else r=t.device;this.compatibilityMode=!r.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),r.lost.then(t=>{if("destroyed"===t.reason)return;const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}),this.device=r,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(rC.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let r=t.context;if(void 0===r){const s=this.parameters;r=!0===e.isDefaultCanvasTarget&&void 0!==s.context?s.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${_t} webgpu`);const i=s.alpha?"premultiplied":"opaque",n=s.outputType===Te?"extended":"standard";r.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),t.context=r}return r}get coordinateSystem(){return h}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),r=this.get(t),s=e.currentSamples;let i=r.descriptor;if(void 0===i||r.samples!==s){i={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(i.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=i.colorAttachments[0];s>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,r.descriptor=i,r.samples=s}const n=i.colorAttachments[0];return s>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;void 0!==i&&s.width===r.width&&s.height===r.height&&s.samples===r.samples||(i={},s.descriptors=i);const n=e.getCacheKey();let a=i[n];if(void 0===a){const t=e.textures,o=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s1)if(!0===l){const t=e.camera.cameras;for(let e=0;e0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=r.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:sE}),this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(i=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,i));const n=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),n.dispatchSize=i}i=n.dispatchSize}a.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,r,s,i,n,a,o,u){const{object:l,material:d,context:c}=e,h=e.getIndex(),p=null!==h;this.pipelineUtils.setPipeline(o,s),u.pipeline=s;const g=u.bindingGroups;for(let e=0,t=i.length;e65535?4:2);for(let n=0;n0){const i=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===i.indexesGPU||i.indexesGPU.length!==a.length){const e=this.get(c),t=[],r=new Uint32Array([0,0,0,0]);for(let s=0,i=a.length;s(d("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new zR(e)));super(new t(e),e),this.library=new $C,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class HC extends Es{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class qC{constructor(e,t=Cn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new vg;r.name="RenderPipeline",this._quadMesh=new gx(r),this._quadMesh.name="Render Pipeline",this._context=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){const e=this.renderer;this._update(),null!==this._context.onBeforeRenderPipeline&&this._context.onBeforeRenderPipeline();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=m,e.outputColorSpace=p.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterRenderPipeline&&this._context.onAfterRenderPipeline()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),!0===this.needsUpdate){const e=this._toneMapping,t=this._outputColorSpace,r={renderPipeline:this,onBeforeRenderPipeline:null,onAfterRenderPipeline:null};let s=this.outputNode;!0===this.outputColorTransform?(s=s.context(r),s=Ll(s,e,t)):(r.toneMapping=e,r.outputColorSpace=t,s=s.context(r)),this._context=r,this._quadMesh.material.fragmentNode=s,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){v('RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}}class jC extends qC{constructor(e,t){v('PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.'),super(e,t)}}class XC extends N{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class KC extends N{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!1,this.image={width:e,height:t,depth:r},this.magFilter=le,this.minFilter=le,this.wrapR=_e,this.isStorageTexture=!0,this.is3DTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class QC extends N{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!0,this.image={width:e,height:t,depth:r},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class YC extends Ax{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class ZC extends As{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new ws(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{try{t(this.parse(JSON.parse(r)))}catch(t){s?s(t):o(t),this.manager.itemError(e)}},r,s)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return void 0===this.nodes[e]?(o("NodeLoader: Node type not found:",e),yn()):new this.nodes[e]}}class JC extends Cs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class eM extends Ms{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}parseNodes(e,t){if(void 0!==e){const r=new ZC;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new JC;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={id:s.id,version:s.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=Ps.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Ps.set(e,t)),t}getMaterialData(e){let t=Fs.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:s.version}:t[r]=s.clone():t[r]=s)}Fs.set(e,t)}return t}equals(e,t,r){const{object:s,material:i,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(s.matrixWorld))return a.worldMatrix.copy(s.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==r){o._renderId=r;for(const e in o){const t=o[e],r=i[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),o._equal=!1,!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,o._equal=!1,!1}else if(t!==r)return o[e]=r,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:r}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==r)return a.bufferWidth=t,a.bufferHeight=r,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==r){u._renderId=r;const e=n.attributes,t=u.attributes;let s=0,i=0;for(const t in e)s++;for(const r in t){i++;const s=t[r],n=e[r];if(void 0===n)return delete t[r],u._equal=!1,!1;if(s.id!==n.id||s.version!==n.version)return s.id=n.id,s.version=n.version,u._equal=!1,!1}if(i!==s)return u.attributes=this.getAttributesData(e),u._equal=!1,!1;const a=n.index,o=u.indexId,l=u.indexVersion,d=a?a.id:null,c=a?a.version:null;if(o!==d||l!==c)return u.indexId=d,u.indexVersion=c,u._equal=!1,!1;if(u.drawRange.start!==n.drawRange.start||u.drawRange.count!==n.drawRange.count)return u.drawRange.start=n.drawRange.start,u.drawRange.count=n.drawRange.count,u._equal=!1,!1;u._equal=!0}else if(!1===u._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t{const r=e.match(t);if(!r)return null;const s=r[1]||r[2]||"",i=r[3].split("?")[0],n=parseInt(r[4],10),a=parseInt(r[5],10);return{fn:s,file:i.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Ds.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Os(e,t=0){let r=3735928559^t,s=1103547991^t;if(Array.isArray(e))for(let t,i=0;i>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const Vs=e=>Os(e),ks=e=>Os(e),Gs=(...e)=>Os(e),zs=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),$s=new WeakMap;function Ws(e){return zs.get(e)}function Hs(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function qs(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function js(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Xs(e){return/float|int|uint/.test(e)?4:/vec2/.test(e)?8:/vec3/.test(e)||/vec4/.test(e)?16:/mat2/.test(e)?8:/mat3/.test(e)||/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Ks(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 Qs(o,...u){const l=o?o.slice(-4):void 0;return 1===u.length&&("vec2"===l?u=[u[0],u[0]]:"vec3"===l?u=[u[0],u[0],u[0]]:"vec4"===l&&(u=[u[0],u[0],u[0],u[0]])),"color"===o?new e(...u):"vec2"===l?new t(...u):"vec3"===l?new r(...u):"vec4"===l?new s(...u):"mat2"===l?new i(...u):"mat3"===l?new n(...u):"mat4"===l?new a(...u):"bool"===o?u[0]||!1:"float"===o||"int"===o||"uint"===o?u[0]||0:"string"===o?u[0]||"":"ArrayBuffer"===o?Js(u[0]):null}function Ys(e){let t=$s.get(e);return void 0===t&&(t={},$s.set(e,t)),t}function Zs(e){let t="";const r=new Uint8Array(e);for(let e=0;ee.charCodeAt(0)).buffer}var ei=Object.freeze({__proto__:null,arrayBufferToBase64:Zs,base64ToArrayBuffer:Js,getAlignmentFromType:Xs,getDataFromObject:Ys,getLengthFromType:qs,getMemoryLengthFromType:js,getTypeFromLength:Ws,getTypedArrayFromType:Hs,getValueFromType:Qs,getValueType:Ks,hash:Gs,hashArray:ks,hashString:Vs});const ti={VERTEX:"vertex",FRAGMENT:"fragment"},ri={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},si={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},ii={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ni=["fragment","vertex"],ai=["setup","analyze","generate"],oi=[...ni,"compute"],ui=["x","y","z","w"],li={analyze:"setup",generate:"analyze"};let di=0;class ci extends u{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ri.NONE,this.updateBeforeType=ri.NONE,this.updateAfterType=ri.NONE,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=di++,this.stackTrace=null,!0===ci.captureStackTrace&&(this.stackTrace=new Is)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=l.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,ri.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ri.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ri.OBJECT)}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 r of Object.getOwnPropertyNames(this)){const s=this[r];if(!0!==r.startsWith("_")&&!e.has(s))if(!0===Array.isArray(s))for(let e=0;e0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}ci.captureStackTrace=!1;class hi extends ci{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 pi extends ci{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class gi extends ci{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 r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class mi extends gi{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,r)=>t+e.getTypeLength(r.getNodeType(e)),0))}generate(e,t){const r=this.getNodeType(e),s=e.getTypeLength(r),i=this.nodes,n=e.getComponentType(r),a=[];let u=0;for(const t of i){if(u>=s){o(`TSL: Length of parameters exceeds maximum length of function '${r}()' type.`,this.stackTrace);break}let i,l=t.getNodeType(e),d=e.getTypeLength(l);u+d>s&&(o(`TSL: Length of '${r}()' data exceeds maximum length of output type.`,this.stackTrace),d=s-u,l=e.getTypeFromLength(d)),u+=d,i=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(d,n);i=e.format(i,l,t)}a.push(i)}const l=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(l,r,t)}}const fi=ui.join("");class yi extends ci{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(ui.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 r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===fi.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class bi extends gi{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");ci.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Si?Si.assign(this,...e):o("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Is),this;{const t=Ri.get("assign");return this.addToStack(t(...e))}},ci.prototype.toVarIntent=function(){return this},ci.prototype.get=function(e){return new Ni(this,e)};const wi={};function Ci(e,t,r){wi[e]=wi[t]=wi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new yi(this,e),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();ci.prototype["set"+s]=ci.prototype["set"+i]=ci.prototype["set"+n]=function(t){const r=Ei(e);return new bi(this,r,tn(t))},ci.prototype["flip"+s]=ci.prototype["flip"+i]=ci.prototype["flip"+n]=function(){const t=Ei(e);return new xi(this,t)}}const Mi=["x","y","z","w"],Bi=["r","g","b","a"],Li=["s","t","p","q"];for(let e=0;e<4;e++){let t=Mi[e],r=Bi[e],s=Li[e];Ci(t,r,s);for(let i=0;i<4;i++){t=Mi[e]+Mi[i],r=Bi[e]+Bi[i],s=Li[e]+Li[i],Ci(t,r,s);for(let n=0;n<4;n++){t=Mi[e]+Mi[i]+Mi[n],r=Bi[e]+Bi[i]+Bi[n],s=Li[e]+Li[i]+Li[n],Ci(t,r,s);for(let a=0;a<4;a++)t=Mi[e]+Mi[i]+Mi[n]+Mi[a],r=Bi[e]+Bi[i]+Bi[n]+Bi[a],s=Li[e]+Li[i]+Li[n]+Li[a],Ci(t,r,s)}}}for(let e=0;e<32;e++)wi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new hi(this,new vi(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};Object.defineProperties(ci.prototype,wi);const Fi=new WeakMap,Pi=function(e,t=null){for(const r in e)e[r]=tn(e[r],t);return e},Ui=function(e,t=null){const r=e.length;for(let s=0;su?(o(`TSL: "${r}" parameter length exceeds limit.`,new Is),t.slice(0,u)):t}return null===t?n=(...t)=>i(new e(...nn(d(t)))):null!==r?(r=tn(r),n=(...s)=>i(new e(t,...nn(d(s)),r))):n=(...r)=>i(new e(t,...nn(d(r)))),n.setParameterLength=(...e)=>(1===e.length?a=u=e[0]:2===e.length&&([a,u]=e),n),n.setName=e=>(l=e,n),n},Ii=function(e,...t){return new e(...nn(t))};class Oi extends ci{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:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let u=null;if(t.layout){let s=Fi.get(e.constructor);void 0===s&&(s=new WeakMap,Fi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=tn(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i);const n=r?function(e){let t;sn(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(r):null;u=tn(i.call(n))}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return sn(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield tn(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof ci&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=tn(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,o=n||a.length>1?a(i,s):a(s);u=tn(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(s[n]=u),u}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return e.fnCall=o,r}}class Vi extends ci{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 Oi(this,e)}setup(){return this.call()}}const ki=[!1,!0],Gi=[0,1,2,3],zi=[-1,-2],$i=[.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],Wi=new Map;for(const e of ki)Wi.set(e,new vi(e));const Hi=new Map;for(const e of Gi)Hi.set(e,new vi(e,"uint"));const qi=new Map([...Hi].map(e=>new vi(e.value,"int")));for(const e of zi)qi.set(e,new vi(e,"int"));const ji=new Map([...qi].map(e=>new vi(e.value)));for(const e of $i)ji.set(e,new vi(e));for(const e of $i)ji.set(-e,new vi(-e));const Xi={bool:Wi,uint:Hi,ints:qi,float:ji},Ki=new Map([...Wi,...ji]),Qi=(e,t)=>Ki.has(e)?Ki.get(e):!0===e.isNode?e:new vi(e,t),Yi=function(e,t=null){return(...r)=>{for(const t of r)if(void 0===t)return o(`TSL: Invalid parameter for the type "${e}".`,new Is),new vi(0,e);if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(r=[Qs(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return rn(t.get(r[0]));if(1===r.length){const t=Qi(r[0],e);return t.nodeType===e?rn(t):rn(new pi(t,e))}const s=r.map(e=>Qi(e));return rn(new mi(s,e))}};function Zi(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}const Ji=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function en(e,t){return new Vi(e,t)}const tn=(e,t=null)=>function(e,t=null){const r=Ks(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?tn(Qi(e,t)):"shader"===r?e.isFn?e:cn(e):e}(e,t),rn=(e,t=null)=>tn(e,t).toVarIntent(),sn=(e,t=null)=>new Pi(e,t),nn=(e,t=null)=>new Ui(e,t),an=(e,t=null,r=null,s=null)=>new Di(e,t,r,s),on=(e,...t)=>new Ii(e,...t),un=(e,t=null,r=null,s={})=>new Di(e,t,r,{...s,intent:!0});let ln=0;class dn extends ci{constructor(e,t=null){super();let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:o("TSL: Invalid layout type.",new Is),t=null)),this.shaderNode=new en(e,r),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+ln++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}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 o('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function cn(e,t=null){const r=new dn(e,t);return new Proxy(()=>{},{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const hn=e=>{Si=e},pn=()=>Si,gn=(...e)=>Si.If(...e);function mn(e){return Si&&Si.addToStack(e),e}Ai("toStack",mn);const fn=new Yi("color"),yn=new Yi("float",Xi.float),bn=new Yi("int",Xi.ints),xn=new Yi("uint",Xi.uint),Tn=new Yi("bool",Xi.bool),_n=new Yi("vec2"),vn=new Yi("ivec2"),Nn=new Yi("uvec2"),Sn=new Yi("bvec2"),Rn=new Yi("vec3"),An=new Yi("ivec3"),En=new Yi("uvec3"),wn=new Yi("bvec3"),Cn=new Yi("vec4"),Mn=new Yi("ivec4"),Bn=new Yi("uvec4"),Ln=new Yi("bvec4"),Fn=new Yi("mat2"),Pn=new Yi("mat3"),Un=new Yi("mat4");Ai("toColor",fn),Ai("toFloat",yn),Ai("toInt",bn),Ai("toUint",xn),Ai("toBool",Tn),Ai("toVec2",_n),Ai("toIVec2",vn),Ai("toUVec2",Nn),Ai("toBVec2",Sn),Ai("toVec3",Rn),Ai("toIVec3",An),Ai("toUVec3",En),Ai("toBVec3",wn),Ai("toVec4",Cn),Ai("toIVec4",Mn),Ai("toUVec4",Bn),Ai("toBVec4",Ln),Ai("toMat2",Fn),Ai("toMat3",Pn),Ai("toMat4",Un);const Dn=an(hi).setParameterLength(2),In=(e,t)=>new pi(tn(e),t);Ai("element",Dn),Ai("convert",In);Ai("append",e=>(d("TSL: .append() has been renamed to .toStack().",new Is),mn(e)));class On extends ci{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1){super(e),this.name=t,this.varying=r,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Vs(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Vn=(e,t)=>new On(e,t),kn=(e,t)=>new On(e,t,!0),Gn=on(On,"vec4","DiffuseColor"),zn=on(On,"vec3","DiffuseContribution"),$n=on(On,"vec3","EmissiveColor"),Wn=on(On,"float","Roughness"),Hn=on(On,"float","Metalness"),qn=on(On,"float","Clearcoat"),jn=on(On,"float","ClearcoatRoughness"),Xn=on(On,"vec3","Sheen"),Kn=on(On,"float","SheenRoughness"),Qn=on(On,"float","Iridescence"),Yn=on(On,"float","IridescenceIOR"),Zn=on(On,"float","IridescenceThickness"),Jn=on(On,"float","AlphaT"),ea=on(On,"float","Anisotropy"),ta=on(On,"vec3","AnisotropyT"),ra=on(On,"vec3","AnisotropyB"),sa=on(On,"color","SpecularColor"),ia=on(On,"color","SpecularColorBlended"),na=on(On,"float","SpecularF90"),aa=on(On,"float","Shininess"),oa=on(On,"vec4","Output"),ua=on(On,"float","dashSize"),la=on(On,"float","gapSize"),da=on(On,"float","pointWidth"),ca=on(On,"float","IOR"),ha=on(On,"float","Transmission"),pa=on(On,"float","Thickness"),ga=on(On,"float","AttenuationDistance"),ma=on(On,"color","AttenuationColor"),fa=on(On,"float","Dispersion");class ya extends ci{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1,s=null){super("string"),this.name=e,this.shared=t,this.order=r,this.updateType=s,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 ba=(e,t=1,r=null)=>new ya(e,!1,t,r),xa=(e,t=0,r=null)=>new ya(e,!0,t,r),Ta=xa("frame",0,ri.FRAME),_a=xa("render",0,ri.RENDER),va=ba("object",1,ri.OBJECT);class Na extends Ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=va}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const r=e(t,this);void 0!==r&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const Sa=(e,t)=>{const r=Ji(t||e);if(r===e&&(e=Qs(r)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new Na(e,r)};class Ra extends gi{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,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 Aa=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Ra(null,r.length,r)}else{const r=e[0],s=e[1];t=new Ra(r,s)}return tn(t)};Ai("toArray",(e,t)=>Aa(Array(t).fill(e)));class Ea extends gi{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 r=e.getTypeLength(t.node.getNodeType(e));return ui.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getDataFromNode(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t{const s=r.type;let i;return i="pointer"===s?"&"+t.build(e):t.build(e,s),i};if(Array.isArray(i)){if(i.length>s.length)o("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=s.length;else if(i.length(t=t.length>1||t[0]&&!0===t[0].isNode?nn(t):sn(t[0]),new Ca(tn(e),t));Ai("call",Ma);const Ba={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class La extends gi{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new La(e,t,r);for(let t=0;t>"===r||"<<"===r)return e.getIntegerType(n);if("!"===r||"&&"===r||"||"===r||"^^"===r)return"bool";if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),l=i?i.build(e,o):null,d=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===c;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${r} ${l} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${l} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(d)return e.format(`${d}( ${u}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${l}`,n,t);{let i=`( ${u} ${r} ${l} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return d?e.format(`${d}( ${u}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${r} ${u}`,n,t):e.format(`${u} ${r} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Fa=un(La,"+").setParameterLength(2,1/0).setName("add"),Pa=un(La,"-").setParameterLength(2,1/0).setName("sub"),Ua=un(La,"*").setParameterLength(2,1/0).setName("mul"),Da=un(La,"/").setParameterLength(2,1/0).setName("div"),Ia=un(La,"%").setParameterLength(2).setName("mod"),Oa=un(La,"==").setParameterLength(2).setName("equal"),Va=un(La,"!=").setParameterLength(2).setName("notEqual"),ka=un(La,"<").setParameterLength(2).setName("lessThan"),Ga=un(La,">").setParameterLength(2).setName("greaterThan"),za=un(La,"<=").setParameterLength(2).setName("lessThanEqual"),$a=un(La,">=").setParameterLength(2).setName("greaterThanEqual"),Wa=un(La,"&&").setParameterLength(2,1/0).setName("and"),Ha=un(La,"||").setParameterLength(2,1/0).setName("or"),qa=un(La,"!").setParameterLength(1).setName("not"),ja=un(La,"^^").setParameterLength(2).setName("xor"),Xa=un(La,"&").setParameterLength(2).setName("bitAnd"),Ka=un(La,"~").setParameterLength(1).setName("bitNot"),Qa=un(La,"|").setParameterLength(2).setName("bitOr"),Ya=un(La,"^").setParameterLength(2).setName("bitXor"),Za=un(La,"<<").setParameterLength(2).setName("shiftLeft"),Ja=un(La,">>").setParameterLength(2).setName("shiftRight"),eo=cn(([e])=>(e.addAssign(1),e)),to=cn(([e])=>(e.subAssign(1),e)),ro=cn(([e])=>{const t=bn(e).toConst();return e.addAssign(1),t}),so=cn(([e])=>{const t=bn(e).toConst();return e.subAssign(1),t});Ai("add",Fa),Ai("sub",Pa),Ai("mul",Ua),Ai("div",Da),Ai("mod",Ia),Ai("equal",Oa),Ai("notEqual",Va),Ai("lessThan",ka),Ai("greaterThan",Ga),Ai("lessThanEqual",za),Ai("greaterThanEqual",$a),Ai("and",Wa),Ai("or",Ha),Ai("not",qa),Ai("xor",ja),Ai("bitAnd",Xa),Ai("bitNot",Ka),Ai("bitOr",Qa),Ai("bitXor",Ya),Ai("shiftLeft",Za),Ai("shiftRight",Ja),Ai("incrementBefore",eo),Ai("decrementBefore",to),Ai("increment",ro),Ai("decrement",so);const io=(e,t)=>(d('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Is),Ia(bn(e),bn(t)));Ai("modInt",io);class no extends gi{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===no.MAX||e===no.MIN)&&arguments.length>3){let i=new no(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}generateNodeType(e){const t=this.method;return t===no.LENGTH||t===no.DISTANCE||t===no.DOT?"float":t===no.CROSS?"vec3":t===no.ALL||t===no.ANY?"bool":t===no.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===no.ONE_MINUS)i=Pa(1,t);else if(s===no.RECIPROCAL)i=Da(1,t);else if(s===no.DIFFERENCE)i=Vo(Pa(t,r));else if(s===no.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=Cn(Rn(n),0):s=Cn(Rn(s),0);const a=Ua(s,n).xyz;i=Ro(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===no.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const l=[];return r===no.CROSS?l.push(n.build(e,s),a.build(e,s)):u===c&&r===no.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==c||r!==no.MIN&&r!==no.MAX?r===no.REFRACT?l.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===no.MIX?l.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===h&&r===no.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==no.DFDX&&r!==no.DFDY||(d(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),r="/*"+r+"*/"),l.push(n.build(e,i)),null!==a&&l.push(a.build(e,i)),null!==o&&l.push(o.build(e,i))):l.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${l.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}no.ALL="all",no.ANY="any",no.RADIANS="radians",no.DEGREES="degrees",no.EXP="exp",no.EXP2="exp2",no.LOG="log",no.LOG2="log2",no.SQRT="sqrt",no.INVERSE_SQRT="inversesqrt",no.FLOOR="floor",no.CEIL="ceil",no.NORMALIZE="normalize",no.FRACT="fract",no.SIN="sin",no.SINH="sinh",no.COS="cos",no.COSH="cosh",no.TAN="tan",no.TANH="tanh",no.ASIN="asin",no.ASINH="asinh",no.ACOS="acos",no.ACOSH="acosh",no.ATAN="atan",no.ATANH="atanh",no.ABS="abs",no.SIGN="sign",no.LENGTH="length",no.NEGATE="negate",no.ONE_MINUS="oneMinus",no.DFDX="dFdx",no.DFDY="dFdy",no.ROUND="round",no.RECIPROCAL="reciprocal",no.TRUNC="trunc",no.FWIDTH="fwidth",no.TRANSPOSE="transpose",no.DETERMINANT="determinant",no.INVERSE="inverse",no.EQUALS="equals",no.MIN="min",no.MAX="max",no.STEP="step",no.REFLECT="reflect",no.DISTANCE="distance",no.DIFFERENCE="difference",no.DOT="dot",no.CROSS="cross",no.POW="pow",no.TRANSFORM_DIRECTION="transformDirection",no.MIX="mix",no.CLAMP="clamp",no.REFRACT="refract",no.SMOOTHSTEP="smoothstep",no.FACEFORWARD="faceforward";const ao=yn(1e-6),oo=yn(1e6),uo=yn(Math.PI),lo=yn(2*Math.PI),co=yn(2*Math.PI),ho=yn(.5*Math.PI),po=un(no,no.ALL).setParameterLength(1),go=un(no,no.ANY).setParameterLength(1),mo=un(no,no.RADIANS).setParameterLength(1),fo=un(no,no.DEGREES).setParameterLength(1),yo=un(no,no.EXP).setParameterLength(1),bo=un(no,no.EXP2).setParameterLength(1),xo=un(no,no.LOG).setParameterLength(1),To=un(no,no.LOG2).setParameterLength(1),_o=un(no,no.SQRT).setParameterLength(1),vo=un(no,no.INVERSE_SQRT).setParameterLength(1),No=un(no,no.FLOOR).setParameterLength(1),So=un(no,no.CEIL).setParameterLength(1),Ro=un(no,no.NORMALIZE).setParameterLength(1),Ao=un(no,no.FRACT).setParameterLength(1),Eo=un(no,no.SIN).setParameterLength(1),wo=un(no,no.SINH).setParameterLength(1),Co=un(no,no.COS).setParameterLength(1),Mo=un(no,no.COSH).setParameterLength(1),Bo=un(no,no.TAN).setParameterLength(1),Lo=un(no,no.TANH).setParameterLength(1),Fo=un(no,no.ASIN).setParameterLength(1),Po=un(no,no.ASINH).setParameterLength(1),Uo=un(no,no.ACOS).setParameterLength(1),Do=un(no,no.ACOSH).setParameterLength(1),Io=un(no,no.ATAN).setParameterLength(1,2),Oo=un(no,no.ATANH).setParameterLength(1),Vo=un(no,no.ABS).setParameterLength(1),ko=un(no,no.SIGN).setParameterLength(1),Go=un(no,no.LENGTH).setParameterLength(1),zo=un(no,no.NEGATE).setParameterLength(1),$o=un(no,no.ONE_MINUS).setParameterLength(1),Wo=un(no,no.DFDX).setParameterLength(1),Ho=un(no,no.DFDY).setParameterLength(1),qo=un(no,no.ROUND).setParameterLength(1),jo=un(no,no.RECIPROCAL).setParameterLength(1),Xo=un(no,no.TRUNC).setParameterLength(1),Ko=un(no,no.FWIDTH).setParameterLength(1),Qo=un(no,no.TRANSPOSE).setParameterLength(1),Yo=un(no,no.DETERMINANT).setParameterLength(1),Zo=un(no,no.INVERSE).setParameterLength(1),Jo=un(no,no.MIN).setParameterLength(2,1/0),eu=un(no,no.MAX).setParameterLength(2,1/0),tu=un(no,no.STEP).setParameterLength(2),ru=un(no,no.REFLECT).setParameterLength(2),su=un(no,no.DISTANCE).setParameterLength(2),iu=un(no,no.DIFFERENCE).setParameterLength(2),nu=un(no,no.DOT).setParameterLength(2),au=un(no,no.CROSS).setParameterLength(2),ou=un(no,no.POW).setParameterLength(2),uu=e=>Ua(e,e),lu=e=>Ua(e,e,e),du=e=>Ua(e,e,e,e),cu=un(no,no.TRANSFORM_DIRECTION).setParameterLength(2),hu=e=>Ua(ko(e),ou(Vo(e),1/3)),pu=e=>nu(e,e),gu=un(no,no.MIX).setParameterLength(3),mu=(e,t=0,r=1)=>new no(no.CLAMP,tn(e),tn(t),tn(r)),fu=e=>mu(e),yu=un(no,no.REFRACT).setParameterLength(3),bu=un(no,no.SMOOTHSTEP).setParameterLength(3),xu=un(no,no.FACEFORWARD).setParameterLength(3),Tu=cn(([e])=>{const t=nu(e.xy,_n(12.9898,78.233)),r=Ia(t,uo);return Ao(Eo(r).mul(43758.5453))}),_u=(e,t,r)=>gu(t,r,e),vu=(e,t,r)=>bu(t,r,e),Nu=(e,t)=>tu(t,e),Su=xu,Ru=vo;Ai("all",po),Ai("any",go),Ai("radians",mo),Ai("degrees",fo),Ai("exp",yo),Ai("exp2",bo),Ai("log",xo),Ai("log2",To),Ai("sqrt",_o),Ai("inverseSqrt",vo),Ai("floor",No),Ai("ceil",So),Ai("normalize",Ro),Ai("fract",Ao),Ai("sin",Eo),Ai("sinh",wo),Ai("cos",Co),Ai("cosh",Mo),Ai("tan",Bo),Ai("tanh",Lo),Ai("asin",Fo),Ai("asinh",Po),Ai("acos",Uo),Ai("acosh",Do),Ai("atan",Io),Ai("atanh",Oo),Ai("abs",Vo),Ai("sign",ko),Ai("length",Go),Ai("lengthSq",pu),Ai("negate",zo),Ai("oneMinus",$o),Ai("dFdx",Wo),Ai("dFdy",Ho),Ai("round",qo),Ai("reciprocal",jo),Ai("trunc",Xo),Ai("fwidth",Ko),Ai("min",Jo),Ai("max",eu),Ai("step",Nu),Ai("reflect",ru),Ai("distance",su),Ai("dot",nu),Ai("cross",au),Ai("pow",ou),Ai("pow2",uu),Ai("pow3",lu),Ai("pow4",du),Ai("transformDirection",cu),Ai("mix",_u),Ai("clamp",mu),Ai("refract",yu),Ai("smoothstep",vu),Ai("faceForward",xu),Ai("difference",iu),Ai("saturate",fu),Ai("cbrt",hu),Ai("transpose",Qo),Ai("determinant",Yo),Ai("inverse",Zo),Ai("rand",Tu);class Au extends ci{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}generateNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode,r=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?Vn(r).build(e):"";s.nodeProperty=l;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(c,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=n.build(e,r);if(h&&(u?h=l+" = "+h+";":(h="return "+h+";",null===o&&(d("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,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Eu=an(Au).setParameterLength(2,3);Ai("select",Eu);class wu extends ci{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const r=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(r),s}}const Cu=(e=null,t={})=>{let r=e;return null!==r&&!0===r.isNode||(t=r||t,r=null),new wu(r,t)},Mu=e=>Cu(e,{uniformFlow:!0}),Bu=(e,t)=>Cu(e,{nodeName:t});function Lu(e,t,r=null){return Cu(r,{getShadow:({light:r,shadowColorNode:s})=>t===r?s.mul(e):s})}function Fu(e,t=null){return Cu(t,{getAO:(t,{material:r})=>!0===r.transparent?t:null!==t?t.mul(e):e})}function Pu(e,t){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),Bu(e,t)}Ai("context",Cu),Ai("label",Pu),Ai("uniformFlow",Mu),Ai("setName",Bu),Ai("builtinShadowContext",(e,t,r)=>Lu(t,r,e)),Ai("builtinAOContext",(e,t)=>Fu(t,e));class Uu extends ci{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const r=t.getBaseStack();e?r.addToStackBefore(this):r.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,u=!1;s&&(a=e.isDeterministic(t),u=n?s:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&o('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const d=e.getVectorType(l),c=t.build(e,d),h=e.getVarFromNode(this,r,d,void 0,u),p=e.getPropertyName(h);let g=p;if(u)if(n)g=a?`const ${p}`:`let ${p}`;else{const r=t.getArrayCount(e);g=`const ${e.getVar(h.type,p,r)}`}return e.addLineFlowCode(`${g} = ${c}`,this),p}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Du=an(Uu),Iu=(e,t=null)=>Du(e,t).toStack(),Ou=(e,t=null)=>Du(e,t,!0).toStack(),Vu=e=>Du(e).setIntent(!0).toStack();Ai("toVar",Iu),Ai("toConst",Ou),Ai("toVarIntent",Vu);class ku extends ci{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),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 r=this.node.build(e,...t);return e.removeSubBuild(),r}}const Gu=(e,t,r=null)=>new ku(tn(e),t,r);class zu extends ci{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Gu(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 r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=Gu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,ti.VERTEX);e.flowNodeFromShaderStage(ti.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const $u=an(zu).setParameterLength(1,2),Wu=e=>$u(e);Ai("toVarying",$u),Ai("toVertexStage",Wu);const Hu=cn(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return gu(t,r,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),qu=cn(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return gu(t,r,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ju="WorkingColorSpace";class Xu extends gi{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===ju?p.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==p.enabled&&r!==s&&r&&s?(p.getTransfer(r)===g&&(i=Cn(Hu(i.rgb),i.a)),p.getPrimaries(r)!==p.getPrimaries(s)&&(i=Cn(Pn(p._getMatrix(new n,r,s)).mul(i.rgb),i.a)),p.getTransfer(s)===g&&(i=Cn(qu(i.rgb),i.a)),i):i}}const Ku=(e,t)=>new Xu(tn(e),ju,t),Qu=(e,t)=>new Xu(tn(e),t,ju);Ai("workingToColorSpace",Ku),Ai("colorSpaceToWorking",Qu);let Yu=class extends hi{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),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class Zu extends ci{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=ri.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Yu(this,tn(e))}setNodeType(e){const t=Sa(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 r=e[t[0]];for(let e=1;enew Ju(e,t,r);class tl extends gi{static get type(){return"ToneMappingNode"}constructor(e,t=sl,r=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Gs(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,r=this._toneMapping;if(r===m)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=Cn(i(t.rgb,this.exposureNode),t.a):(o("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const rl=(e,t,r)=>new tl(e,tn(t),tn(r)),sl=el("toneMappingExposure","float");Ai("toneMapping",(e,t,r)=>rl(t,r,e));const il=new WeakMap;function nl(e,t){let r=il.get(e);return void 0===r&&(r=new b(e,t),il.set(e,r)),r}class al extends Ti{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=f,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.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),r=e.getTypeLength(t),s=this.value,i=this.bufferStride||r,n=this.bufferOffset;let a;a=!0===s.isInterleavedBuffer?s:!0===s.isBufferAttribute?nl(s.array,i):nl(s,i);const o=new y(a,r,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(r);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=s,i=s;else{i=$u(this).build(e,t)}return i}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 ol(e,t=null,r=0,s=0,i=f,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Pn(new al(e,"vec3",9,0).setUsage(i).setInstanced(n),new al(e,"vec3",9,3).setUsage(i).setInstanced(n),new al(e,"vec3",9,6).setUsage(i).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Un(new al(e,"vec4",16,0).setUsage(i).setInstanced(n),new al(e,"vec4",16,4).setUsage(i).setInstanced(n),new al(e,"vec4",16,8).setUsage(i).setInstanced(n),new al(e,"vec4",16,12).setUsage(i).setInstanced(n)):new al(e,t,r,s).setUsage(i)}const ul=(e,t=null,r=0,s=0)=>ol(e,t,r,s),ll=(e,t=null,r=0,s=0)=>ol(e,t,r,s,f,!0),dl=(e,t=null,r=0,s=0)=>ol(e,t,r,s,x,!0);Ai("toAttribute",e=>ul(e.value));class cl extends ci{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===cl.VERTEX)s=e.getVertexIndex();else if(r===cl.INSTANCE)s=e.getInstanceIndex();else if(r===cl.DRAW)s=e.getDrawIndex();else if(r===cl.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===cl.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==cl.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=$u(this).build(e,t)}return i}}cl.VERTEX="vertex",cl.INSTANCE="instance",cl.SUBGROUP="subgroup",cl.INVOCATION_LOCAL="invocationLocal",cl.INVOCATION_SUBGROUP="invocationSubgroup",cl.DRAW="draw";const hl=on(cl,cl.VERTEX),pl=on(cl,cl.INSTANCE),gl=on(cl,cl.SUBGROUP),ml=on(cl,cl.INVOCATION_SUBGROUP),fl=on(cl,cl.INVOCATION_LOCAL),yl=on(cl,cl.DRAW);class bl extends ci{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=ri.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=Sa(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:r}=e;if("compute"===r){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"),r=pl.build(e,"uint");e.flow.code=`${e.tab}if ( ${r} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const xl=(e,t=[64])=>{(0===t.length||t.length>3)&&o("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Is);for(let e=0;e{const s=xl(e,r);return"number"==typeof t?s.count=t:s.dispatchSize=t,s};Ai("compute",Tl),Ai("computeKernel",xl);class _l extends ci{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(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vl=e=>new _l(tn(e));function Nl(e,t=!0){return d('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vl(e).setParent(t)}Ai("cache",Nl),Ai("isolate",vl);class Sl extends ci{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)}}const Rl=an(Sl).setParameterLength(2);Ai("bypass",Rl);const Al=cn(([e,t,r,s=yn(0),i=yn(1),n=Tn(!1)])=>{let a=e.sub(t).div(r.sub(t));return Zi(n)&&(a=a.clamp()),a.mul(i.sub(s)).add(s)});function El(e,t,r,s=yn(0),i=yn(1)){return Al(e,t,r,s,i,!0)}Ai("remap",Al),Ai("remapClamp",El);class wl extends ci{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Cl=an(wl).setParameterLength(1,2),Ml=e=>(e?Eu(e,Cl("discard")):Cl("discard")).toStack();Ai("discard",Ml);class Bl extends gi{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||m,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||T;return r!==m&&(t=t.toneMapping(r)),s!==T&&s!==p.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Ll=(e,t=null,r=null)=>new Bl(tn(e),t,r);Ai("renderOutput",Ll);class Fl extends gi{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,r=this.node.build(e);if(null!==t)t(e,r);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(t.length);let i="";i+="// #"+t+"#\n",i+=e.flow.code.replace(/^\t/gm,"")+"\n",i+="/* ... */ "+r+" /* ... */\n",i+="// #"+s+"#\n",_(i)}return r}}const Pl=(e,t=null)=>new Fl(tn(e),t).toStack();Ai("debug",Pl);class Ul extends u{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Dl extends ci{static get type(){return"InspectorNode"}constructor(e,t="",r=null){super(),this.node=e,this.name=t,this.callback=r,this.updateType=ri.FRAME,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!==Ul&&v('TSL: ".toInspector()" is only available with WebGPU.'),t}}function Il(e,t="",r=null){return(e=tn(e)).before(new Dl(e,t,r))}Ai("toInspector",Il);class Ol extends ci{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 r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return $u(this).build(e,r)}return d(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Vl=(e,t=null)=>new Ol(e,t),kl=(e=0)=>Vl("uv"+(e>0?e:""),"vec2");class Gl extends ci{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const zl=an(Gl).setParameterLength(1,2);class $l extends Na{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ri.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const Wl=an($l).setParameterLength(1);class Hl extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const ql=new N;class jl extends Na{static get type(){return"TextureNode"}constructor(e=ql,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ri.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===S?"uvec4":this.value.type===R?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return kl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Sa(this.value.matrix)),this._matrixUniform.mul(Rn(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Sa(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(bn(zl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Hl("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const s=cn(()=>{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?ri.OBJECT:ri.NONE,t})();let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(A.TEXTURE_COMPARE))n=this.compareNode;else{const e=r.compareFunction;null===e||e===E||e===w||e===C||e===M?a=this.compareNode:(n=this.compareNode,v('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;let d;return d=i?e.generateTextureBias(l,t,r,i,n,u):o?e.generateTextureGrad(l,t,r,o,n,u):a?e.generateTextureCompare(l,t,r,a,n,u):!1===this.sampler?e.generateTextureLoad(l,t,r,s,n,u):s?e.generateTextureLevel(l,t,r,s,n,u):e.generateTexture(l,t,r,n,u),d}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:u,biasNode:l,compareNode:d,compareStepNode:c,depthNode:h,gradNode:p,offsetNode:g}=s,m=this.generateUV(e,t),f=u?u.build(e,"float"):null,y=l?l.build(e,"float"):null,b=h?h.build(e,"int"):null,x=d?d.build(e,"float"):null,T=c?c.build(e,"float"):null,_=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,v=g?this.generateOffset(e,g):null;let N=b;null===N&&r.isArrayTexture&&!0!==this.isTexture3DNode&&(N="0");const S=e.getVarFromNode(this);o=e.getPropertyName(S);let R=this.generateSnippet(e,i,m,f,y,N,x,_,v);if(null!==T){const t=r.compareFunction;R=t===C||t===M?tu(Cl(R,a),Cl(T,"float")).build(e,a):tu(Cl(T,"float"),Cl(R,a)).build(e,a)}e.addLineFlowCode(`${o} = ${R}`,this),n.snippet=R,n.propertyName=o}let u=o;return e.needsToWorkingColorSpace(r)&&(u=Qu(Cl(u,a),r.colorSpace).setup(e).build(e,a)),e.format(u,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=tn(e),t.referenceNode=this.getBase(),tn(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=tn(e).mul(Wl(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===B||r.magFilter===B)&&(d("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),tn(t)}level(e){const t=this.clone();return t.levelNode=tn(e),t.referenceNode=this.getBase(),tn(t)}size(e){return zl(this,e)}bias(e){const t=this.clone();return t.biasNode=tn(e),t.referenceNode=this.getBase(),tn(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=tn(e),t.referenceNode=this.getBase(),tn(t)}grad(e,t){const r=this.clone();return r.gradNode=[tn(e),tn(t)],r.referenceNode=this.getBase(),tn(r)}depth(e){const t=this.clone();return t.depthNode=tn(e),t.referenceNode=this.getBase(),tn(t)}offset(e){const t=this.clone();return t.offsetNode=tn(e),t.referenceNode=this.getBase(),tn(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 r=this._flipYUniform;null!==r&&(r.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const Xl=an(jl).setParameterLength(1,4).setName("texture"),Kl=(e=ql,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=tn(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=Xl(e,t,r,s),i},Ql=(...e)=>Kl(...e).setSampler(!1);class Yl extends Na{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r,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 Zl=(e,t,r)=>new Yl(e,t,r);class Jl extends hi{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(e),s=this.node.getPaddedType();return e.format(t,s,r)}}class ed extends Yl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ks(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ri.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rnew ed(e,t);class rd extends ci{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const sd=an(rd).setParameterLength(1);let id,nd;class ad extends ci{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===ad.DPR?"float":this.scope===ad.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ri.NONE;return this.scope!==ad.SIZE&&this.scope!==ad.VIEWPORT&&this.scope!==ad.DPR||(e=ri.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===ad.VIEWPORT?null!==t?nd.copy(t.viewport):(e.getViewport(nd),nd.multiplyScalar(e.getPixelRatio())):this.scope===ad.DPR?this._output.value=e.getPixelRatio():null!==t?(id.width=t.width,id.height=t.height):e.getDrawingBufferSize(id)}setup(){const e=this.scope;let r=null;return r=e===ad.SIZE?Sa(id||(id=new t)):e===ad.VIEWPORT?Sa(nd||(nd=new s)):e===ad.DPR?Sa(1):_n(dd.div(ld)),this._output=r,r}generate(e){if(this.scope===ad.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(ld).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}ad.COORDINATE="coordinate",ad.VIEWPORT="viewport",ad.SIZE="size",ad.UV="uv",ad.DPR="dpr";const od=on(ad,ad.DPR),ud=on(ad,ad.UV),ld=on(ad,ad.SIZE),dd=on(ad,ad.COORDINATE),cd=on(ad,ad.VIEWPORT),hd=cd.zw,pd=dd.sub(cd.xy),gd=pd.div(hd),md=cn(()=>(d('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new Is),ld),"vec2").once()();let fd=null,yd=null,bd=null,xd=null,Td=null,_d=null,vd=null,Nd=null,Sd=null,Rd=null,Ad=null,Ed=null,wd=null,Cd=null;const Md=Sa(0,"uint").setName("u_cameraIndex").setGroup(xa("cameraIndex")).toVarying("v_cameraIndex"),Bd=Sa("float").setName("cameraNear").setGroup(_a).onRenderUpdate(({camera:e})=>e.near),Ld=Sa("float").setName("cameraFar").setGroup(_a).onRenderUpdate(({camera:e})=>e.far),Fd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);null===yd?yd=td(r).setGroup(_a).setName("cameraProjectionMatrices"):yd.array=r,t=yd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrix")}else null===fd&&(fd=Sa(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=fd;return t}).once()(),Pd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);null===xd?xd=td(r).setGroup(_a).setName("cameraProjectionMatricesInverse"):xd.array=r,t=xd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrixInverse")}else null===bd&&(bd=Sa(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=bd;return t}).once()(),Ud=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);null===_d?_d=td(r).setGroup(_a).setName("cameraViewMatrices"):_d.array=r,t=_d.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraViewMatrix")}else null===Td&&(Td=Sa(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=Td;return t}).once()(),Dd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);null===Nd?Nd=td(r).setGroup(_a).setName("cameraWorldMatrices"):Nd.array=r,t=Nd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraWorldMatrix")}else null===vd&&(vd=Sa(e.matrixWorld).setName("cameraWorldMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=vd;return t}).once()(),Id=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);null===Rd?Rd=td(r).setGroup(_a).setName("cameraNormalMatrices"):Rd.array=r,t=Rd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraNormalMatrix")}else null===Sd&&(Sd=Sa(e.normalMatrix).setName("cameraNormalMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.normalMatrix)),t=Sd;return t}).once()(),Od=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t{const r=e.cameras,s=t.array;for(let e=0,t=r.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=Ad;return t}).once()(),Vd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);null===Cd?Cd=td(r,"vec4").setGroup(_a).setName("cameraViewports"):Cd.array=r,t=Cd.element(Md).toConst("cameraViewport")}else null===wd&&(wd=Cn(0,0,ld.x,ld.y).toConst("cameraViewport")),t=wd;return t}).once()(),kd=new L;class Gd extends ci{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ri.OBJECT,this.uniformNode=new Na(null)}generateNodeType(){const e=this.scope;return e===Gd.WORLD_MATRIX?"mat4":e===Gd.POSITION||e===Gd.VIEW_POSITION||e===Gd.DIRECTION||e===Gd.SCALE?"vec3":e===Gd.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Gd.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gd.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gd.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gd.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===Gd.VIEW_POSITION){const i=e.camera;s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Gd.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),kd.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=kd.radius}}generate(e){const t=this.scope;return t===Gd.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Gd.POSITION||t===Gd.VIEW_POSITION||t===Gd.DIRECTION||t===Gd.SCALE?this.uniformNode.nodeType="vec3":t===Gd.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}}Gd.WORLD_MATRIX="worldMatrix",Gd.POSITION="position",Gd.SCALE="scale",Gd.VIEW_POSITION="viewPosition",Gd.DIRECTION="direction",Gd.RADIUS="radius";const zd=an(Gd,Gd.DIRECTION).setParameterLength(1),$d=an(Gd,Gd.WORLD_MATRIX).setParameterLength(1),Wd=an(Gd,Gd.POSITION).setParameterLength(1),Hd=an(Gd,Gd.SCALE).setParameterLength(1),qd=an(Gd,Gd.VIEW_POSITION).setParameterLength(1),jd=an(Gd,Gd.RADIUS).setParameterLength(1);class Xd extends Gd{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Kd=on(Xd,Xd.DIRECTION),Qd=on(Xd,Xd.WORLD_MATRIX),Yd=on(Xd,Xd.POSITION),Zd=on(Xd,Xd.SCALE),Jd=on(Xd,Xd.VIEW_POSITION),ec=on(Xd,Xd.RADIUS),tc=Sa(new n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),rc=Sa(new a).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),sc=cn(e=>e.context.modelViewMatrix||ic).once()().toVar("modelViewMatrix"),ic=Ud.mul(Qd),nc=cn(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Sa("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),ac=cn(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Sa("mat3").onObjectUpdate(({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),oc=cn(e=>"fragment"!==e.shaderStage?(v("TSL: `clipSpace` is only available in fragment stage."),Cn()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),uc=Vl("position","vec3"),lc=uc.toVarying("positionLocal"),dc=uc.toVarying("positionPrevious"),cc=cn(e=>Qd.mul(lc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),hc=cn(()=>lc.transformDirection(Qd).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),pc=cn(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Pd.mul(oc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),gc=cn(e=>{let t;return t=e.camera.isOrthographicCamera?Rn(0,0,1):pc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class mc extends ci{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===F?"false":e.getFrontFacing()}}const fc=on(mc),yc=yn(fc).mul(2).sub(1),bc=cn(([e],{material:t})=>{const r=t.side;return r===F?e=e.mul(-1):r===P&&(e=e.mul(yc)),e}),xc=Vl("normal","vec3"),Tc=cn(e=>!1===e.geometry.hasAttribute("normal")?(d('TSL: Vertex attribute "normal" not found on geometry.'),Rn(0,1,0)):xc,"vec3").once()().toVar("normalLocal"),_c=pc.dFdx().cross(pc.dFdy()).normalize().toVar("normalFlat"),vc=cn(e=>{let t;return t=e.isFlatShading()?_c:wc(Tc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Nc=cn(e=>{let t=vc.transformDirection(Ud);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Sc=cn(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=vc,!0!==e.isFlatShading()&&(t=bc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Rc=Sc.transformDirection(Ud).toVar("normalWorld"),Ac=cn(({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Sc:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Ec=cn(([e,t=Qd])=>{const r=Pn(t),s=e.div(Rn(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz}),wc=cn(([e],t)=>{const r=t.context.modelNormalViewMatrix;if(r)return r.transformDirection(e);const s=tc.mul(e);return Ud.transformDirection(s)}),Cc=cn(()=>(d('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Sc)).once(["NORMAL","VERTEX"])(),Mc=cn(()=>(d('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Rc)).once(["NORMAL","VERTEX"])(),Bc=cn(()=>(d('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ac)).once(["NORMAL","VERTEX"])(),Lc=new a,Fc=Sa(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Pc=Sa(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Uc=Sa(new a).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const r=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?Lc.makeRotationFromEuler(r).transpose():Lc.identity(),Lc}),Dc=gc.negate().reflect(Sc),Ic=gc.negate().refract(Sc,Fc),Oc=Dc.transformDirection(Ud).toVar("reflectVector"),Vc=Ic.transformDirection(Ud).toVar("reflectVector"),kc=new U;class Gc extends jl{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===D?Oc:e.mapping===I?Vc:(o('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Rn(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!0===r.isDepthTexture?e.renderer.coordinateSystem===h?Rn(t.x,t.y.negate(),t.z):t:(t=Uc.mul(t),e.renderer.coordinateSystem!==h&&r.isRenderTargetTexture||(t=Rn(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const zc=an(Gc).setParameterLength(1,4).setName("cubeTexture"),$c=(e=kc,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=tn(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=zc(e,t,r,s),i};class Wc extends hi{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),r=this.referenceNode.getNodeType(e),s=this.getNodeType(e);return e.format(t,r,s)}}class Hc extends ci{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=ri.OBJECT}element(e){return new Wc(this,tn(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Zl(null,e,this.count):Array.isArray(this.getValueFromReference())?td(null,e):"texture"===e?Kl(null):"cubeTexture"===e?$c(null):Sa(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 r=e[t[0]];for(let e=1;enew Hc(e,t,r),jc=(e,t,r,s)=>new Hc(e,t,s,r);class Xc extends Hc{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Kc=(e,t,r=null)=>new Xc(e,t,r),Qc=kl(),Yc=pc.dFdx(),Zc=pc.dFdy(),Jc=Qc.dFdx(),eh=Qc.dFdy(),th=Sc,rh=Zc.cross(th),sh=th.cross(Yc),ih=rh.mul(Jc.x).add(sh.mul(eh.x)),nh=rh.mul(Jc.y).add(sh.mul(eh.y)),ah=ih.dot(ih).max(nh.dot(nh)),oh=ah.equal(0).select(0,ah.inverseSqrt()),uh=ih.mul(oh).toVar("tangentViewFrame"),lh=nh.mul(oh).toVar("bitangentViewFrame"),dh=Vl("tangent","vec4"),ch=dh.xyz.toVar("tangentLocal"),hh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?sc.mul(Cn(ch,0)).xyz.toVarying("v_tangentView").normalize():uh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ph=hh.transformDirection(Ud).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),gh=cn(([e,t],r)=>{let s=e.mul(dh.w).xyz;return"NORMAL"===r.subBuildFn&&!0!==r.isFlatShading()&&(s=s.toVarying(t)),s}).once(["NORMAL"]),mh=gh(xc.cross(dh),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),fh=gh(Tc.cross(ch),"v_bitangentLocal").normalize().toVar("bitangentLocal"),yh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?gh(Sc.cross(hh),"v_bitangentView").normalize():lh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),bh=gh(Rc.cross(ph),"v_bitangentWorld").normalize().toVar("bitangentWorld"),xh=Pn(hh,yh,Sc).toVar("TBNViewMatrix"),Th=gc.mul(xh),_h=cn(()=>{let e=ra.cross(gc);return e=e.cross(ra).normalize(),e=gu(e,Sc,ea.mul(Wn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),vh=e=>tn(e).mul(.5).add(.5),Nh=e=>Rn(e,_o(fu(yn(1).sub(nu(e,e)))));class Sh extends gi{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=O,this.unpackNormalMode=V}setup(e){const{normalMapType:t,scaleNode:r,unpackNormalMode:s}=this;let i=this.node.mul(2).sub(1);if(t===O?s===k?i=Nh(i.xy):s===G?i=Nh(i.yw):s!==V&&o(`THREE.NodeMaterial: Unexpected unpack normal mode: ${s}`):s!==V&&o(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${s}'`),null!==r){let t=r;!0===e.isFlatShading()&&(t=bc(t)),i=Rn(i.xy.mul(t),i.z)}let n=null;return t===z?n=wc(i):t===O?n=xh.mul(i).normalize():(o(`NodeMaterial: Unsupported normal map type: ${t}`),n=Sc),n}}const Rh=an(Sh).setParameterLength(1,2),Ah=cn(({textureNode:e,bumpScale:t})=>{const r=t=>e.isolate().context({getUV:e=>t(e.uvNode||kl()),forceUVContext:!0}),s=yn(r(e=>e));return _n(yn(r(e=>e.add(e.dFdx()))).sub(s),yn(r(e=>e.add(e.dFdy()))).sub(s)).mul(t)}),Eh=cn(e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(yc),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()});class wh extends gi{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Ah({textureNode:this.textureNode,bumpScale:e});return Eh({surf_pos:pc,surf_norm:Sc,dHdxy:t})}}const Ch=an(wh).setParameterLength(1,2),Mh=new Map;class Bh extends ci{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Mh.get(e);return void 0===r&&(r=Kc(e,t),Mh.set(e,r)),r}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,r=this.scope;let s=null;if(r===Bh.COLOR){const e=void 0!==t.color?this.getColor(r):Rn();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Bh.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Bh.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:yn(1);else if(r===Bh.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Bh.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Bh.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Bh.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Bh.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Bh.NORMAL)t.normalMap?(s=Rh(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType,t.normalMap.format!=$&&t.normalMap.format!=W&&t.normalMap.format!=H||(s.unpackNormalMode=k)):s=t.bumpMap?Ch(this.getTexture("bump").r,this.getFloat("bumpScale")):Sc;else if(r===Bh.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Rh(this.getTexture(r),this.getCache(r+"Scale","vec2")):Sc;else if(r===Bh.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Bh.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(1e-4,1)}else if(r===Bh.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=Fn(mp.x,mp.y,mp.y.negate(),mp.x).mul(e.rg.mul(2).sub(_n(1)).normalize().mul(e.b))}else s=mp;else if(r===Bh.IRIDESCENCE_THICKNESS){const e=qc("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=qc("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Bh.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Bh.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Bh.IOR)s=this.getFloat(r);else if(r===Bh.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Bh.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Bh.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):yn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Bh.ALPHA_TEST="alphaTest",Bh.COLOR="color",Bh.OPACITY="opacity",Bh.SHININESS="shininess",Bh.SPECULAR="specular",Bh.SPECULAR_STRENGTH="specularStrength",Bh.SPECULAR_INTENSITY="specularIntensity",Bh.SPECULAR_COLOR="specularColor",Bh.REFLECTIVITY="reflectivity",Bh.ROUGHNESS="roughness",Bh.METALNESS="metalness",Bh.NORMAL="normal",Bh.CLEARCOAT="clearcoat",Bh.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Bh.CLEARCOAT_NORMAL="clearcoatNormal",Bh.EMISSIVE="emissive",Bh.ROTATION="rotation",Bh.SHEEN="sheen",Bh.SHEEN_ROUGHNESS="sheenRoughness",Bh.ANISOTROPY="anisotropy",Bh.IRIDESCENCE="iridescence",Bh.IRIDESCENCE_IOR="iridescenceIOR",Bh.IRIDESCENCE_THICKNESS="iridescenceThickness",Bh.IOR="ior",Bh.TRANSMISSION="transmission",Bh.THICKNESS="thickness",Bh.ATTENUATION_DISTANCE="attenuationDistance",Bh.ATTENUATION_COLOR="attenuationColor",Bh.LINE_SCALE="scale",Bh.LINE_DASH_SIZE="dashSize",Bh.LINE_GAP_SIZE="gapSize",Bh.LINE_WIDTH="linewidth",Bh.LINE_DASH_OFFSET="dashOffset",Bh.POINT_SIZE="size",Bh.DISPERSION="dispersion",Bh.LIGHT_MAP="light",Bh.AO="ao";const Lh=on(Bh,Bh.ALPHA_TEST),Fh=on(Bh,Bh.COLOR),Ph=on(Bh,Bh.SHININESS),Uh=on(Bh,Bh.EMISSIVE),Dh=on(Bh,Bh.OPACITY),Ih=on(Bh,Bh.SPECULAR),Oh=on(Bh,Bh.SPECULAR_INTENSITY),Vh=on(Bh,Bh.SPECULAR_COLOR),kh=on(Bh,Bh.SPECULAR_STRENGTH),Gh=on(Bh,Bh.REFLECTIVITY),zh=on(Bh,Bh.ROUGHNESS),$h=on(Bh,Bh.METALNESS),Wh=on(Bh,Bh.NORMAL),Hh=on(Bh,Bh.CLEARCOAT),qh=on(Bh,Bh.CLEARCOAT_ROUGHNESS),jh=on(Bh,Bh.CLEARCOAT_NORMAL),Xh=on(Bh,Bh.ROTATION),Kh=on(Bh,Bh.SHEEN),Qh=on(Bh,Bh.SHEEN_ROUGHNESS),Yh=on(Bh,Bh.ANISOTROPY),Zh=on(Bh,Bh.IRIDESCENCE),Jh=on(Bh,Bh.IRIDESCENCE_IOR),ep=on(Bh,Bh.IRIDESCENCE_THICKNESS),tp=on(Bh,Bh.TRANSMISSION),rp=on(Bh,Bh.THICKNESS),sp=on(Bh,Bh.IOR),ip=on(Bh,Bh.ATTENUATION_DISTANCE),np=on(Bh,Bh.ATTENUATION_COLOR),ap=on(Bh,Bh.LINE_SCALE),op=on(Bh,Bh.LINE_DASH_SIZE),up=on(Bh,Bh.LINE_GAP_SIZE),lp=on(Bh,Bh.LINE_WIDTH),dp=on(Bh,Bh.LINE_DASH_OFFSET),cp=on(Bh,Bh.POINT_SIZE),hp=on(Bh,Bh.DISPERSION),pp=on(Bh,Bh.LIGHT_MAP),gp=on(Bh,Bh.AO),mp=Sa(new t).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))}),fp=cn(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class yp extends hi{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 r=this.storageBufferNode.structTypeNode;return r?r.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 r;const s=e.context.assign;if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const bp=an(yp).setParameterLength(2);class xp extends Yl{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStruct?(s="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Ws(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=ii.READ_WRITE,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return bp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ii.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=ul(this.value),this._varying=$u(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:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Tp=(e,t=null,r=0)=>new xp(e,t,r);class _p extends ci{static get type(){return"InstanceNode"}constructor(e,t,r=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=r,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=ri.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:r}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:s,isStorageColor:i}=this;if(s&&null===r){if(i)r=Tp(s,"vec3",Math.max(s.count,1)).element(pl);else{const e=new q(s.array,3),t=s.usage===x?dl:ll;this.bufferColor=e,r=Rn(t(e,"vec3",3,0))}this.instanceColorNode=r}const n=t.mul(lc).xyz;if(lc.assign(n),e.needsPreviousData()&&dc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=Ec(Tc,t);Tc.assign(e)}null!==this.instanceColorNode&&kn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(dc).xyz}_createInstanceMatrixNode(e,t){let r;const{instanceMatrix:s}=this,{count:i}=s;if(this.isStorageMatrix)r=Tp(s,"mat4",Math.max(i,1)).element(pl);else{if(16*i*4<=t.getUniformBufferLimit())r=Zl(s.array,"mat4",Math.max(i,1)).element(pl);else{const t=new j(s.array,16,1);!0===e&&(this.buffer=t);const i=s.usage===x?dl:ll,n=[i(t,"vec4",16,0),i(t,"vec4",16,4),i(t,"vec4",16,8),i(t,"vec4",16,12)];r=Un(...n)}}return r}}const vp=an(_p).setParameterLength(2,3);class Np extends _p{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Sp=an(Np).setParameterLength(1);class Rp extends ci{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=pl:this.batchingIdNode=yl);const t=cn(([e])=>{const t=bn(zl(Ql(this.batchMesh._indirectTexture),0).x).toConst(),r=bn(e).mod(t).toConst(),s=bn(e).div(t).toConst();return Ql(this.batchMesh._indirectTexture,vn(r,s)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(bn(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=bn(zl(Ql(s),0).x).toConst(),n=yn(r).mul(4).toInt().toConst(),a=n.mod(i).toConst(),o=n.div(i).toConst(),u=Un(Ql(s,vn(a,o)),Ql(s,vn(a.add(1),o)),Ql(s,vn(a.add(2),o)),Ql(s,vn(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=cn(([e])=>{const t=bn(zl(Ql(l),0).x).toConst(),r=e,s=r.mod(t).toConst(),i=r.div(t).toConst();return Ql(l,vn(s,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);kn("vec3","vBatchColor").assign(t)}const d=Pn(u);lc.assign(u.mul(lc));const c=Tc.div(Rn(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Tc.assign(h),e.hasGeometryAttribute("tangent")&&ch.mulAssign(d)}}const Ap=an(Rp).setParameterLength(1),Ep=new WeakMap;class wp extends ci{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=ri.OBJECT,this.skinIndexNode=Vl("skinIndex","uvec4"),this.skinWeightNode=Vl("skinWeight","vec4"),this.bindMatrixNode=qc("bindMatrix","mat4"),this.bindMatrixInverseNode=qc("bindMatrixInverse","mat4"),this.boneMatricesNode=jc("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=lc,this.toPositionNode=lc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w),d=i.mul(t),c=Fa(a.mul(s.x).mul(d),o.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=Tc,r=ch){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(s.x),u=e.element(s.y),l=e.element(s.z),d=e.element(s.w);let c=Fa(i.x.mul(o),i.y.mul(u),i.z.mul(l),i.w.mul(d));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(r).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=jc("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,dc)}setup(e){e.needsPreviousData()&&dc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:r}=this.getSkinnedNormalAndTangent();Tc.assign(t),e.hasGeometryAttribute("tangent")&&ch.assign(r)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Ep.get(t)!==e.frameId&&(Ep.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Cp=e=>new wp(e);class Mp extends ci{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 r={};for(let e=0,t=this.params.length-1;eNumber(l)?">=":"<")),a)n=`while ( ${l} )`;else{const r={start:u,end:l},s=r.start,i=r.end;let a;const g=()=>h.includes("<")?"+=":"-=";if(null!=p)switch(typeof p){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=d+" "+g()+" "+e.generateConst(c,p);break;case"string":a=d+" "+p;break;default:p.isNode?a=d+" "+g()+" "+p.build(e):(o("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else p="int"===c||"uint"===c?h.includes("<")?"++":"--":g()+" 1.",a=d+" "+p;n=`for ( ${e.getVar(c,d)+" = "+s}; ${d+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tnew Mp(nn(e,"int")).toStack(),Lp=()=>Cl("break").toStack(),Fp=new WeakMap,Pp=new s,Up=cn(({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=bn(hl).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ql(e,vn(u,o)).depth(i).xyz.mul(t)});class Dp extends ci{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Sa(1),this.updateType=ri.OBJECT}setup(e){const{geometry:r}=e,s=void 0!==r.morphAttributes.position,i=r.hasAttribute("normal")&&void 0!==r.morphAttributes.normal,n=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,a=void 0!==n?n.length:0,{texture:o,stride:u,size:l}=function(e){const r=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=Fp.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===r&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new X(m,h,p,a);f.type=K,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=yn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ql(this.mesh.morphTexture,vn(bn(e).add(1),bn(pl))).r):t.assign(qc("morphTargetInfluences","float").element(e).toVar()),gn(t.notEqual(0),()=>{!0===s&&lc.addAssign(Up({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(0)})),!0===i&&Tc.addAssign(Up({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const Ip=an(Dp).setParameterLength(1);class Op extends ci{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vp extends Op{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class kp extends wu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=null,s=null){super(e),this.lightingModel=t,this.backdropNode=r,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,r={directDiffuse:Rn().toVar("directDiffuse"),directSpecular:Rn().toVar("directSpecular"),indirectDiffuse:Rn().toVar("indirectDiffuse"),indirectSpecular:Rn().toVar("indirectSpecular")};return{radiance:Rn().toVar("radiance"),irradiance:Rn().toVar("irradiance"),iblIrradiance:Rn().toVar("iblIrradiance"),ambientOcclusion:yn(1).toVar("ambientOcclusion"),reflectedLight:r,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Gp=an(kp);class zp extends Op{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const $p=new t;class Wp extends jl{static get type(){return"ViewportTextureNode"}constructor(e=ud,t=null,r=null){let s=null;null===r?(s=new Q,s.minFilter=Y,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=ri.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;null===i?t.getDrawingBufferSize($p):i.getDrawingBufferSize?i.getDrawingBufferSize($p):$p.set(i.width,i.height);const n=this.getTextureForReference(i);n.image.width===$p.width&&n.image.height===$p.height||(n.image.width=$p.width,n.image.height=$p.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Hp=an(Wp).setParameterLength(0,3),qp=an(Wp,null,null,{generateMipmaps:!0}).setParameterLength(0,3),jp=qp(),Xp=(e=ud,t=null)=>jp.sample(e,t);let Kp=null;class Qp extends Wp{static get type(){return"ViewportDepthTextureNode"}constructor(e=ud,t=null,r=null){null===r&&(null===Kp&&(Kp=new Z),r=Kp),super(e,t,r)}}const Yp=an(Qp).setParameterLength(0,3);class Zp extends ci{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===Zp.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Zp.DEPTH_BASE)null!==r&&(s=ng().assign(r));else if(t===Zp.DEPTH)s=e.isPerspectiveCamera?tg(pc.z,Bd,Ld):Jp(pc.z,Bd,Ld);else if(t===Zp.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=sg(r,Bd,Ld);s=Jp(e,Bd,Ld)}else s=r;else s=Jp(pc.z,Bd,Ld);return s}}Zp.DEPTH_BASE="depthBase",Zp.DEPTH="depth",Zp.LINEAR_DEPTH="linearDepth";const Jp=(e,t,r)=>e.add(t).div(t.sub(r)),eg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?r.sub(t).mul(e).sub(r):t.sub(r).mul(e).sub(t)),tg=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),rg=(e,t,r)=>t.mul(e.add(r)).div(e.mul(t.sub(r))),sg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?t.mul(r).div(t.sub(r).mul(e).sub(t)):t.mul(r).div(r.sub(t).mul(e).sub(r))),ig=(e,t,r)=>{t=t.max(1e-6).toVar();const s=To(e.negate().div(t)),i=To(r.div(t));return s.div(i)},ng=an(Zp,Zp.DEPTH_BASE),ag=on(Zp,Zp.DEPTH),og=an(Zp,Zp.LINEAR_DEPTH).setParameterLength(0,1),ug=og(Yp());ag.assign=e=>ng(e);class lg extends ci{static get type(){return"ClippingNode"}constructor(e=lg.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===lg.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===lg.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return cn(()=>{const r=yn().toVar("distanceToPlane"),s=yn().toVar("distanceToGradient"),i=yn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=td(t).setGroup(_a);Bp(n,({i:t})=>{const n=e.element(t);r.assign(pc.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(bu(s.negate(),s,r))})}const a=e.length;if(a>0){const t=td(e).setGroup(_a),n=yn(1).toVar("intersectionClipOpacity");Bp(a,({i:e})=>{const i=t.element(e);r.assign(pc.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(bu(s.negate(),s,r).oneMinus())}),i.mulAssign(n.oneMinus())}Gn.a.mulAssign(i),Gn.a.equal(0).discard()})()}setupDefault(e,t){return cn(()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=td(t).setGroup(_a);Bp(r,({i:t})=>{const r=e.element(t);pc.dot(r.xyz).greaterThan(r.w).discard()})}const s=e.length;if(s>0){const t=td(e).setGroup(_a),r=Tn(!0).toVar("clipped");Bp(s,({i:e})=>{const s=t.element(e);r.assign(pc.dot(s.xyz).greaterThan(s.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),cn(()=>{const s=td(e).setGroup(_a),i=sd(t.getClipDistance());Bp(r,({i:e})=>{const t=s.element(e),r=pc.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)})})()}}lg.ALPHA_TO_COVERAGE="alphaToCoverage",lg.DEFAULT="default",lg.HARDWARE="hardware";const dg=cn(([e])=>Ao(Ua(1e4,Eo(Ua(17,e.x).add(Ua(.1,e.y)))).mul(Fa(.1,Vo(Eo(Ua(13,e.y).add(e.x))))))),cg=cn(([e])=>dg(_n(dg(e.xy),e.z))),hg=cn(([e])=>{const t=eu(Go(Wo(e.xyz)),Go(Ho(e.xyz))),r=yn(1).div(yn(.05).mul(t)).toVar("pixScale"),s=_n(bo(No(To(r))),bo(So(To(r)))),i=_n(cg(No(s.x.mul(e.xyz))),cg(No(s.y.mul(e.xyz)))),n=Ao(To(r)),a=Fa(Ua(n.oneMinus(),i.x),Ua(n,i.y)),o=Jo(n,n.oneMinus()),u=Rn(a.mul(a).div(Ua(2,o).mul(Pa(1,o))),a.sub(Ua(.5,o)).div(Pa(1,o)),Pa(1,Pa(1,a).mul(Pa(1,a)).div(Ua(2,o).mul(Pa(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return mu(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class pg extends Ol{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 r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new s(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const gg=(e=0)=>new pg(e),mg=cn(([e,t])=>Jo(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),fg=cn(([e,t])=>Jo(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yg=cn(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bg=cn(([e,t])=>gu(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),tu(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xg=cn(([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return Cn(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),Tg=cn(([e])=>Cn(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),_g=cn(([e])=>(gn(e.a.equal(0),()=>Cn(0)),Cn(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class vg extends J{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const r=this[t];r&&!0===r.isNode&&e.push({property:t,childNode:r})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:r}of this._getNodeChildren())e.push(Vs(t.slice(0,-4)),r.getCacheKey());return this.type+ks(e)}build(e){this.setup(e)}setupObserver(e){return new Us(e)}setup(e){e.context.setupNormal=()=>Gu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=this.setupVertex(e),i=Gu(this.vertexNode||s,"VERTEX");let n;e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const i=Cn(s,Gn.a).max(0);n=this.setupOutput(e,i),oa.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&oa.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Cn(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?s=new lg(lg.ALPHA_TO_COVERAGE):e.stack.addToStack(new lg)}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new lg(lg.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?ig(pc.z,Bd,Ld):Jp(pc.z,Bd,Ld))}null!==s&&ag.assign(s).toStack()}setupPositionView(){return sc.mul(lc).xyz}setupModelViewProjection(){return Fd.mul(pc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),fp}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&Ip(t).toStack(),!0===t.isSkinnedMesh&&Cp(t).toStack(),this.displacementMap){const e=Kc("displacementMap","texture"),t=Kc("displacementScale","float"),r=Kc("displacementBias","float");lc.addAssign(Tc.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Ap(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Sp(t).toStack(),null!==this.positionNode&&lc.assign(Gu(this.positionNode,"POSITION","vec3")),lc}setupDiffuseColor(e){const{object:t,geometry:r}=e;null!==this.maskNode&&Tn(this.maskNode).not().discard();let s=this.colorNode?Cn(this.colorNode):Fh;if(!0===this.vertexColors&&r.hasAttribute("color")&&(s=s.mul(gg())),t.instanceColor){s=kn("vec3","vInstanceColor").mul(s)}if(t.isBatchedMesh&&t._colorsTexture){s=kn("vec3","vBatchColor").mul(s)}Gn.assign(s);const i=this.opacityNode?yn(this.opacityNode):Dh;Gn.a.assign(Gn.a.mul(i));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?yn(this.alphaTestNode):Lh,!0===this.alphaToCoverage?(Gn.a=bu(n,n.add(Ko(Gn.a)),Gn.a),Gn.a.lessThanEqual(0).discard()):Gn.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Gn.a.lessThan(hg(lc)).discard(),e.isOpaque()&&Gn.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Rn(0):Gn.rgb}setupNormal(){return this.normalNode?Rn(this.normalNode):Wh}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Kc("envMap","cubeTexture"):Kc("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zp(pp)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);s&&s.isLightingNode&&t.push(s);let i=this.aoNode;null===i&&e.material.aoMap&&(i=gp),e.context.getAO&&(i=e.context.getAO(i,e)),i&&t.push(new Vp(i));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Gp(n,t,r,s)}else null!==r&&(a=Rn(null!==s?gu(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&($n.assign(Rn(i||Uh)),a=a.add($n)),a}setupFog(e,t){const r=e.fogNode;return r&&(oa.assign(t),t=Cn(r.toVar())),t}setupPremultipliedAlpha(e,t){return Tg(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 r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.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 r=J.prototype.toJSON.call(this,e);r.inputNodes={};for(const{property:t,childNode:s}of this._getNodeChildren())r.inputNodes[t]=s.toJSON(e).uuid;function s(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const Ng=new ee;class Sg extends vg{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Ng),this.setValues(e)}}const Rg=new te;class Ag extends vg{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Rg),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?yn(this.offsetNode):dp,t=this.dashScaleNode?yn(this.dashScaleNode):ap,r=this.dashSizeNode?yn(this.dashSizeNode):op,s=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(r),la.assign(s);const i=$u(Vl("lineDistance").mul(t));(e?i.add(e):i).mod(ua.add(la)).greaterThan(ua).discard()}}const Eg=new te;class wg extends vg{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Eg),this.vertexColors=e.vertexColors,this.dashOffset=0,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=re,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.vertexColors,i=this._useDash,n=this._useWorldUnits,a=cn(({start:e,end:t})=>{const r=Fd.element(2).element(2),s=Fd.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return Cn(gu(e.xyz,t.xyz,s),t.w)}).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=cn(()=>{const e=Vl("instanceStart"),t=Vl("instanceEnd"),r=Cn(sc.mul(Cn(e,1))).toVar("start"),s=Cn(sc.mul(Cn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?yn(this.dashScaleNode):ap,t=this.offsetNode?yn(this.offsetNode):dp,r=Vl("instanceDistanceStart"),s=Vl("instanceDistanceEnd");let i=uc.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),kn("float","lineDistance").assign(i)}n&&(kn("vec3","worldStart").assign(r.xyz),kn("vec3","worldEnd").assign(s.xyz));const o=cd.z.div(cd.w),u=Fd.element(2).element(3).equal(-1);gn(u,()=>{gn(r.z.lessThan(0).and(s.z.greaterThan(0)),()=>{s.assign(a({start:r,end:s}))}).ElseIf(s.z.lessThan(0).and(r.z.greaterThanEqual(0)),()=>{r.assign(a({start:s,end:r}))})});const l=Fd.mul(r),d=Fd.mul(s),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const g=Cn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=gu(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=kn("vec4","worldPos");o.assign(uc.y.lessThan(.5).select(r,s));const u=lp.mul(.5);o.addAssign(Cn(uc.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(Cn(uc.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(Cn(a.mul(u),0)),gn(uc.y.greaterThan(1).or(uc.y.lessThan(0)),()=>{o.subAssign(Cn(a.mul(2).mul(u),0))})),g.assign(Fd.mul(o));const l=Rn().toVar();l.assign(uc.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=_n(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(uc.x.lessThan(0).select(e.negate(),e)),gn(uc.y.lessThan(0),()=>{e.assign(e.sub(p))}).ElseIf(uc.y.greaterThan(1),()=>{e.assign(e.add(p))}),e.assign(e.mul(lp)),e.assign(e.div(cd.w.div(od))),g.assign(uc.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(Cn(e,0,0)))}return g})();const o=cn(({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return _n(h,p)});if(this.colorNode=cn(()=>{const e=kl();if(i){const t=this.dashSizeNode?yn(this.dashSizeNode):op,r=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(t),la.assign(r);const s=kn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(ua.add(la)).greaterThan(ua).discard()}const a=yn(1).toVar("alpha");if(n){const e=kn("vec3","worldStart"),s=kn("vec3","worldEnd"),n=kn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:Rn(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(lp);if(!i)if(r&&t.currentSamples>0){const e=h.fwidth();a.assign(bu(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.currentSamples>0){const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1)),s=t.mul(t).add(r.mul(r)),i=yn(s.fwidth()).toVar("dlen");gn(e.y.abs().greaterThan(1),()=>{a.assign(bu(i.oneMinus(),i.add(1),s).oneMinus())})}else gn(e.y.abs().greaterThan(1),()=>{const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1));t.mul(t).add(r.mul(r)).greaterThan(1).discard()});let u;if(this.lineColorNode)u=this.lineColorNode;else if(s){const e=Vl("instanceColorStart"),t=Vl("instanceColorEnd");u=uc.y.lessThan(.5).select(e,t).mul(Fh)}else u=Fh;return Cn(u,a)})(),this.transparent){const e=this.opacityNode?yn(this.opacityNode):Dh;this.outputNode=Cn(this.colorNode.rgb.mul(e).add(Xp().rgb.mul(e.oneMinus())),this.colorNode.a)}super.setup(e)}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}copy(e){return super.copy(e),this.vertexColors=e.vertexColors,this.dashOffset=e.dashOffset,this.lineColorNode=e.lineColorNode,this.offsetNode=e.offsetNode,this.dashScaleNode=e.dashScaleNode,this.dashSizeNode=e.dashSizeNode,this.gapSizeNode=e.gapSizeNode,this._useDash=e._useDash,this._useAlphaToCoverage=e._useAlphaToCoverage,this._useWorldUnits=e._useWorldUnits,this}}const Cg=new se;class Mg extends vg{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Cg),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?yn(this.opacityNode):Dh;Gn.assign(Qu(Cn(vh(Sc),e),ie))}}const Bg=cn(([e=hc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return _n(t,r)});class Lg extends ne{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const r={width:e,height:e,depth:1},s=[r,r,r,r,r,r];this.texture=new U(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=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 i=new ae(5,5,5),n=Bg(hc),a=new vg;a.colorNode=Kl(t,n,0),a.side=F,a.blending=re;const o=new oe(i,a),u=new ue;u.add(o),t.minFilter===Y&&(t.minFilter=le);const l=new de(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.generateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,r=!0,s=!0){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,r,s);e.setRenderTarget(i)}}const Fg=new WeakMap;class Pg extends gi{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=$c(null);const t=new U;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ri.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===ce||r===he){if(Fg.has(e)){const t=Fg.get(e);Dg(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Lg(r.height);s.fromEquirectangularTexture(t,e),Dg(s.texture,e.mapping),this._cubeTexture=s.texture,Fg.set(e,s.texture),e.addEventListener("dispose",Ug)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Ug(e){const t=e.target;t.removeEventListener("dispose",Ug);const r=Fg.get(t);void 0!==r&&(Fg.delete(t),r.dispose())}function Dg(e,t){t===ce?e.mapping=D:t===he&&(e.mapping=I)}const Ig=an(Pg).setParameterLength(1);class Og extends Op{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Ig(this.envNode)}}class Vg extends Op{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=yn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class kg{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Gg extends kg{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(Cn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(Cn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(Gn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case me:s.rgb.assign(gu(s.rgb,s.rgb.mul(i.rgb),kh.mul(Gh)));break;case ge:s.rgb.assign(gu(s.rgb,i.rgb,kh.mul(Gh)));break;case pe:s.rgb.addAssign(i.rgb.mul(kh.mul(Gh)));break;default:d("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const zg=new fe;class $g extends vg{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(zg),this.setValues(e)}setupNormal(){return bc(vc)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Vg(pp)),t}setupOutgoingLight(){return Gn.rgb}setupLightingModel(){return new Gg}}const Wg=cn(({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))}),Hg=cn(e=>e.diffuseColor.mul(1/Math.PI)),qg=cn(({dotNH:e})=>aa.mul(yn(.5)).add(1).mul(yn(1/Math.PI)).mul(e.pow(aa))),jg=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(t).clamp(),s=gc.dot(t).clamp(),i=Wg({f0:sa,f90:1,dotVH:s}),n=yn(.25),a=qg({dotNH:r});return i.mul(n).mul(a)});class Xg extends Gg{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:Gn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(jg({lightDirection:e})).mul(kh))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Kg=new ye;class Qg extends vg{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Kg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg(!1)}}const Yg=new be;class Zg extends vg{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Yg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg}setupVariants(){const e=(this.shininessNode?yn(this.shininessNode):Ph).max(1e-4);aa.assign(e);const t=this.specularNode||Ih;sa.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Jg=cn(e=>{if(!1===e.geometry.hasAttribute("normal"))return yn(0);const t=vc.dFdx().abs().max(vc.dFdy().abs());return t.x.max(t.y).max(t.z)}),em=cn(e=>{const{roughness:t}=e,r=Jg();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s}),tm=cn(({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return Da(.5,i.add(n).max(ao))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),rm=cn(({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(Rn(e.mul(r),t.mul(s),a).length()),l=a.mul(Rn(e.mul(i),t.mul(n),o).length());return Da(.5,u.add(l).max(ao))}).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"}]}),sm=cn(({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),im=yn(1/Math.PI),nm=cn(({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=Rn(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return im.mul(n.mul(u.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"}]}),am=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Sc,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(gc).normalize(),d=n.dot(e).clamp(),c=n.dot(gc).clamp(),h=n.dot(l).clamp(),p=gc.dot(l).clamp();let g,m,f=Wg({f0:t,f90:r,dotVH:p});if(Zi(a)&&(f=Qn.mix(f,i)),Zi(o)){const t=ta.dot(e),r=ta.dot(gc),s=ta.dot(l),i=ra.dot(e),n=ra.dot(gc),a=ra.dot(l);g=rm({alphaT:Jn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=nm({alphaT:Jn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=tm({alpha:u,dotNL:d,dotNV:c}),m=sm({alpha:u,dotNH:h});return f.mul(g).mul(m)}),om=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 um=null;const lm=cn(({roughness:e,dotNV:t})=>{null===um&&(um=new xe(om,16,16,$,Te),um.name="DFG_LUT",um.minFilter=le,um.magFilter=le,um.wrapS=_e,um.wrapT=_e,um.generateMipmaps=!1,um.needsUpdate=!0);const r=_n(e,t);return Kl(um,r).rg}),dm=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=am({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),u=Sc.dot(e).clamp(),l=Sc.dot(gc).clamp(),d=lm({roughness:s,dotNV:l}),c=lm({roughness:s,dotNV:u}),h=t.mul(d.x).add(r.mul(d.y)),p=t.mul(c.x).add(r.mul(c.y)),g=d.x.add(d.y),m=c.x.add(c.y),f=yn(1).sub(g),y=yn(1).sub(m),b=t.add(t.oneMinus().mul(.047619)),x=h.mul(p).mul(b).div(yn(1).sub(f.mul(y).mul(b).mul(b)).add(ao)),T=f.mul(y),_=x.mul(T);return o.add(_)}),cm=cn(e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=lm({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))}),hm=cn(({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(Rn(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),pm=cn(({roughness:e,dotNH:t})=>{const r=e.pow2(),s=yn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return yn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),gm=cn(({dotNV:e,dotNL:t})=>yn(1).div(yn(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),mm=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(e).clamp(),s=Sc.dot(gc).clamp(),i=Sc.dot(t).clamp(),n=pm({roughness:Kn,dotNH:i}),a=gm({dotNV:s,dotNL:r});return Xn.mul(n).mul(a)}),fm=cn(({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=_n(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),ym=cn(({f:e})=>{const t=e.length();return eu(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),bm=cn(({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,eu(r.mul(r).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"}]}),xm=cn(({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=Rn().toVar();return gn(d.dot(r.sub(i)).greaterThanEqual(0),()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(Pn(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=Rn(0).toVar();f.addAssign(bm({v1:h,v2:p})),f.addAssign(bm({v1:p,v2:g})),f.addAssign(bm({v1:g,v2:m})),f.addAssign(bm({v1:m,v2:h})),c.assign(Rn(ym({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Tm=cn(({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=Rn().toVar();return gn(o.dot(e.sub(t)).greaterThanEqual(0),()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=Rn(0).toVar();d.addAssign(bm({v1:n,v2:a})),d.addAssign(bm({v1:a,v2:o})),d.addAssign(bm({v1:o,v2:l})),d.addAssign(bm({v1:l,v2:n})),u.assign(Rn(ym({f:d.abs()})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),_m=1/6,vm=e=>Ua(_m,Ua(e,Ua(e,e.negate().add(3)).sub(3)).add(1)),Nm=e=>Ua(_m,Ua(e,Ua(e,Ua(3,e).sub(6))).add(4)),Sm=e=>Ua(_m,Ua(e,Ua(e,Ua(-3,e).add(3)).add(3)).add(1)),Rm=e=>Ua(_m,ou(e,3)),Am=e=>vm(e).add(Nm(e)),Em=e=>Sm(e).add(Rm(e)),wm=e=>Fa(-1,Nm(e).div(vm(e).add(Nm(e)))),Cm=e=>Fa(1,Rm(e).div(Sm(e).add(Rm(e)))),Mm=(e,t,r)=>{const s=e.uvNode,i=Ua(s,t.zw).add(.5),n=No(i),a=Ao(i),o=Am(a.x),u=Em(a.x),l=wm(a.x),d=Cm(a.x),c=wm(a.y),h=Cm(a.y),p=_n(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=_n(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=_n(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=_n(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Am(a.y).mul(Fa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Em(a.y).mul(Fa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},Bm=cn(([e,t])=>{const r=_n(e.size(bn(t))),s=_n(e.size(bn(t.add(1)))),i=Da(1,r),n=Da(1,s),a=Mm(e,Cn(i,r),No(t)),o=Mm(e,Cn(n,s),So(t));return Ao(t).mix(a,o)}),Lm=cn(([e,t])=>{const r=t.mul(Wl(e));return Bm(e,r)}),Fm=cn(([e,t,r,s,i])=>{const n=Rn(yu(t.negate(),Ro(e),Da(1,s))),a=Rn(Go(i[0].xyz),Go(i[1].xyz),Go(i[2].xyz));return Ro(n).mul(r.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"}]}),Pm=cn(([e,t])=>e.mul(mu(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Um=qp(),Dm=Xp(),Im=cn(([e,t,r],{material:s})=>{const i=(s.side===F?Um:Dm).sample(e),n=To(ld.x).mul(Pm(t,r));return Bm(i,n)}),Om=cn(([e,t,r])=>(gn(r.notEqual(0),()=>{const s=xo(t).negate().div(r);return yo(s.negate().mul(e))}),Rn(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Vm=cn(([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=Cn().toVar(),f=Rn().toVar();const i=d.sub(1).mul(g.mul(.025)),n=Rn(d.sub(i),d,d.add(i));Bp({start:0,end:3},({i:i})=>{const d=n.element(i),g=Fm(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(Cn(y,1))),x=_n(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(_n(x.x,x.y.oneMinus()));const T=Im(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(Om(Go(g),h,p).element(i)))}),m.a.divAssign(3)}else{const i=Fm(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(Cn(n,1))),y=_n(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(_n(y.x,y.y.oneMinus())),m=Im(y,r,d),f=s.mul(Om(Go(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=Rn(cm({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return Cn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())}),km=Pn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Gm=(e,t)=>e.sub(t).div(e.add(t)).pow2(),zm=cn(({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=gu(e,t,bu(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();gn(a.lessThan(0),()=>Rn(1));const o=a.sqrt(),u=Gm(n,e),l=Wg({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=yn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Rn(1).add(t).div(Rn(1).sub(t))})(i.clamp(0,.9999)),g=Gm(p,n.toVec3()),m=Wg({f0:g,f90:1,dotVH:o}),f=Rn(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=Rn(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(Rn(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Bp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=Rn(54856e-17,44201e-17,52481e-17),i=Rn(1681e3,1795300,2208400),n=Rn(43278e5,93046e5,66121e5),a=yn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=Rn(o.x.add(a),o.y,o.z).div(1.0685e-7),km.mul(o)})(yn(e).mul(y),yn(e).mul(b)).mul(2);v.addAssign(N.mul(t))}),v.max(Rn(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"}]}),$m=cn(({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.mul(r),n=r.add(.1).reciprocal(),a=yn(-1.9362).add(r.mul(1.0678)).add(i.mul(.4573)).sub(n.mul(.8469)),o=yn(-.6014).add(r.mul(.5538)).sub(i.mul(.467)).sub(n.mul(.1255));return a.mul(s).add(o).exp().saturate()}),Wm=Rn(.04),Hm=yn(1);class qm extends kg{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Rn().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Rn().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Rn().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Rn().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Rn().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Sc.dot(gc).clamp(),t=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:sa}),r=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:Gn.rgb});this.iridescenceFresnel=gu(t,r,Hn),this.iridescenceF0Dielectric=hm({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=hm({f:r,f90:1,dotVH:e}),this.iridescenceF0=gu(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Hn)}if(!0===this.transmission){const t=cc,r=Od.sub(cc).normalize(),s=Rc,i=e.context;i.backdrop=Vm(s,r,Wn,zn,ia,na,t,Qd,Ud,Fd,ca,pa,ma,ga,this.dispersion?fa:null),i.backdropAlpha=ha,Gn.a.mulAssign(gu(1,i.backdrop.a,ha))}super.start(e)}computeMultiscattering(e,t,r,s,i=null){const n=Sc.dot(gc).clamp(),a=lm({roughness:Wn,dotNV:n}),o=i?Qn.mix(s,i):s,u=o.mul(a.x).add(r.mul(a.y)),l=a.x.add(a.y).oneMinus(),d=o.add(o.oneMinus().mul(.047619)),c=u.mul(d).div(l.mul(d).oneMinus());e.addAssign(u),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(s.mul(mm({lightDirection:e})));const t=$m({normal:Sc,viewDir:gc,roughness:Kn}),r=$m({normal:Sc,viewDir:e,roughness:Kn}),i=Xn.r.max(Xn.g).max(Xn.b).mul(t.max(r)).oneMinus();s.mulAssign(i)}if(!0===this.clearcoat){const r=Ac.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(am({lightDirection:e,f0:Wm,f90:Hm,roughness:jn,normalView:Ac})))}r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:zn}))),r.directSpecular.addAssign(s.mul(dm({lightDirection:e,f0:ia,f90:1,roughness:Wn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Sc,h=gc,p=pc.toVar(),g=fm({N:c,V:h,roughness:Wn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=Pn(Rn(m.x,0,m.y),Rn(0,1,0),Rn(m.z,0,m.w)).toVar(),b=ia.mul(f.x).add(na.sub(ia).mul(f.y)).toVar();if(i.directSpecular.addAssign(e.mul(b).mul(xm({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(zn).mul(xm({N:c,V:h,P:p,mInv:Pn(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d}))),!0===this.clearcoat){const t=Ac,r=fm({N:t,V:h,roughness:jn}),s=n.sample(r),i=a.sample(r),c=Pn(Rn(s.x,0,s.y),Rn(0,1,0),Rn(s.z,0,s.w)),g=Wm.mul(i.x).add(Hm.sub(Wm).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(g).mul(xm({N:t,V:h,P:p,mInv:c,p0:o,p1:u,p2:l,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context,s=t.mul(Hg({diffuseColor:zn})).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();s.mulAssign(t)}r.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Xn,$m({normal:Sc,viewDir:gc,roughness:Kn}))),!0===this.clearcoat){const e=Ac.dot(gc).clamp(),t=cm({dotNV:e,specularColor:Wm,specularF90:Hm,roughness:jn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Rn().toVar("singleScatteringDielectric"),n=Rn().toVar("multiScatteringDielectric"),a=Rn().toVar("singleScatteringMetallic"),o=Rn().toVar("multiScatteringMetallic");this.computeMultiscattering(i,n,na,sa,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,na,Gn.rgb,this.iridescenceF0Metallic);const u=gu(i,a,Hn),l=gu(n,o,Hn),d=i.add(n),c=zn.mul(d.oneMinus()),h=r.mul(1/Math.PI),p=t.mul(u).add(l.mul(h)).toVar(),g=c.mul(h).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();p.mulAssign(t),g.mulAssign(t)}s.indirectSpecular.addAssign(p),s.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Sc.dot(gc).clamp().add(t),i=Wn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ac.dot(gc).clamp(),r=Wg({dotVH:e,f0:Wm,f90:Hm}),s=t.mul(qn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(qn));t.assign(s)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const jm=yn(1),Xm=yn(-2),Km=yn(.8),Qm=yn(-1),Ym=yn(.4),Zm=yn(2),Jm=yn(.305),ef=yn(3),tf=yn(.21),rf=yn(4),sf=yn(4),nf=yn(16),af=cn(([e])=>{const t=Rn(Vo(e)).toVar(),r=yn(-1).toVar();return gn(t.x.greaterThan(t.z),()=>{gn(t.x.greaterThan(t.y),()=>{r.assign(Eu(e.x.greaterThan(0),0,3))}).Else(()=>{r.assign(Eu(e.y.greaterThan(0),1,4))})}).Else(()=>{gn(t.z.greaterThan(t.y),()=>{r.assign(Eu(e.z.greaterThan(0),2,5))}).Else(()=>{r.assign(Eu(e.y.greaterThan(0),1,4))})}),r}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),of=cn(([e,t])=>{const r=_n().toVar();return gn(t.equal(0),()=>{r.assign(_n(e.z,e.y).div(Vo(e.x)))}).ElseIf(t.equal(1),()=>{r.assign(_n(e.x.negate(),e.z.negate()).div(Vo(e.y)))}).ElseIf(t.equal(2),()=>{r.assign(_n(e.x.negate(),e.y).div(Vo(e.z)))}).ElseIf(t.equal(3),()=>{r.assign(_n(e.z.negate(),e.y).div(Vo(e.x)))}).ElseIf(t.equal(4),()=>{r.assign(_n(e.x.negate(),e.z).div(Vo(e.y)))}).Else(()=>{r.assign(_n(e.x,e.y).div(Vo(e.z)))}),Ua(.5,r.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),uf=cn(([e])=>{const t=yn(0).toVar();return gn(e.greaterThanEqual(Km),()=>{t.assign(jm.sub(e).mul(Qm.sub(Xm)).div(jm.sub(Km)).add(Xm))}).ElseIf(e.greaterThanEqual(Ym),()=>{t.assign(Km.sub(e).mul(Zm.sub(Qm)).div(Km.sub(Ym)).add(Qm))}).ElseIf(e.greaterThanEqual(Jm),()=>{t.assign(Ym.sub(e).mul(ef.sub(Zm)).div(Ym.sub(Jm)).add(Zm))}).ElseIf(e.greaterThanEqual(tf),()=>{t.assign(Jm.sub(e).mul(rf.sub(ef)).div(Jm.sub(tf)).add(ef))}).Else(()=>{t.assign(yn(-2).mul(To(Ua(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),lf=cn(([e,t])=>{const r=e.toVar();r.assign(Ua(2,r).sub(1));const s=Rn(r,1).toVar();return gn(t.equal(0),()=>{s.assign(s.zyx)}).ElseIf(t.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),df=cn(([e,t,r,s,i,n])=>{const a=yn(r),o=Rn(t),u=mu(uf(a),Xm,n),l=Ao(u),d=No(u),c=Rn(cf(e,o,d,s,i,n)).toVar();return gn(l.notEqual(0),()=>{const t=Rn(cf(e,o,d.add(1),s,i,n)).toVar();c.assign(gu(c,t,l))}),c}),cf=cn(([e,t,r,s,i,n])=>{const a=yn(r).toVar(),o=Rn(t),u=yn(af(o)).toVar(),l=yn(eu(sf.sub(a),0)).toVar();a.assign(eu(a,sf));const d=yn(bo(a)).toVar(),c=_n(of(o,u).mul(d.sub(2)).add(1)).toVar();return gn(u.greaterThan(2),()=>{c.y.addAssign(d),u.subAssign(3)}),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(Ua(3,nf))),c.y.addAssign(Ua(4,bo(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(_n(),_n())}),hf=cn(({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Co(s),l=r.mul(u).add(i.cross(r).mul(Eo(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return cf(e,l,t,n,a,o)}),pf=cn(({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=Rn(Eu(t,r,au(r,s))).toVar();gn(h.equal(Rn(0)),()=>{h.assign(Rn(s.z,0,s.x.negate()))}),h.assign(Ro(h));const p=Rn().toVar();return p.addAssign(i.element(0).mul(hf({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Bp({start:bn(1),end:e},({i:e})=>{gn(e.greaterThanEqual(n),()=>{Lp()});const t=yn(a.mul(yn(e))).toVar();p.addAssign(i.element(e).mul(hf({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(hf({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))}),Cn(p,1)}),gf=cn(([e])=>{const t=xn(e).toVar();return t.assign(t.shiftLeft(xn(16)).bitOr(t.shiftRight(xn(16)))),t.assign(t.bitAnd(xn(1431655765)).shiftLeft(xn(1)).bitOr(t.bitAnd(xn(2863311530)).shiftRight(xn(1)))),t.assign(t.bitAnd(xn(858993459)).shiftLeft(xn(2)).bitOr(t.bitAnd(xn(3435973836)).shiftRight(xn(2)))),t.assign(t.bitAnd(xn(252645135)).shiftLeft(xn(4)).bitOr(t.bitAnd(xn(4042322160)).shiftRight(xn(4)))),t.assign(t.bitAnd(xn(16711935)).shiftLeft(xn(8)).bitOr(t.bitAnd(xn(4278255360)).shiftRight(xn(8)))),yn(t).mul(2.3283064365386963e-10)}),mf=cn(([e,t])=>_n(yn(e).div(yn(t)),gf(e))),ff=cn(([e,t,r])=>{const s=r.mul(r).toConst(),i=Rn(1,0,0).toConst(),n=au(t,i).toConst(),a=_o(e.x).toConst(),o=Ua(2,3.14159265359).mul(e.y).toConst(),u=a.mul(Co(o)).toConst(),l=a.mul(Eo(o)).toVar(),d=Ua(.5,t.z.add(1)).toConst();l.assign(d.oneMinus().mul(_o(u.mul(u).oneMinus())).add(d.mul(l)));const c=i.mul(u).add(n.mul(l)).add(t.mul(_o(eu(0,u.mul(u).add(l.mul(l)).oneMinus()))));return Ro(Rn(s.mul(c.x),s.mul(c.y),eu(0,c.z)))}),yf=cn(({roughness:e,mipInt:t,envMap:r,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Rn(s).toVar(),l=Rn(0).toVar(),d=yn(0).toVar();return gn(e.lessThan(.001),()=>{l.assign(cf(r,u,t,n,a,o))}).Else(()=>{const s=Eu(Vo(u.z).lessThan(.999),Rn(0,0,1),Rn(1,0,0)),c=Ro(au(s,u)).toVar(),h=au(u,c).toVar();Bp({start:xn(0),end:i},({i:s})=>{const p=mf(s,i),g=ff(p,Rn(0,0,1),e),m=Ro(c.mul(g.x).add(h.mul(g.y)).add(u.mul(g.z))),f=Ro(m.mul(nu(u,m).mul(2)).sub(u)),y=eu(nu(u,f),0);gn(y.greaterThan(0),()=>{const e=cf(r,f,t,n,a,o);l.addAssign(e.mul(y)),d.addAssign(y)})}),gn(d.greaterThan(0),()=>{l.assign(l.div(d))})}),Cn(l,1)}),bf=[.125,.215,.35,.446,.526,.582],xf=20,Tf=new Ne(-1,1,1,-1,0,1),_f=new Se(90,1),vf=new e;let Nf=null,Sf=0,Rf=0;const Af=new r,Ef=new WeakMap,wf=[3,1,5,0,4,2],Cf=lf(kl(),Vl("faceIndex")).normalize(),Mf=Rn(Cf.x,Cf.y,Cf.z);class Bf{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Af,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){d('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}Nf=this._renderer.getRenderTarget(),Sf=this._renderer.getActiveCubeFace(),Rf=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget();return u.depthBuffer=!0,this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return v('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){d('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return v('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){d("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return v('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Uf(),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===D||e.mapping===I?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;ee-4?o=bf[a-e+4-1]:0===a&&(o=0),r.push(o);const u=1/(n-2),l=-u,d=1+u,c=[l,l,d,l,d,d,l,l,d,d,l,d],h=6,p=6,g=3,m=2,f=1,y=new Float32Array(g*p*h),b=new Float32Array(m*p*h),x=new Float32Array(f*p*h);for(let e=0;e2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=wf[e];y.set(s,g*p*i),b.set(c,m*p*i);const n=[i,i,i,i,i,i];x.set(n,f*p*i)}const T=new ve;T.setAttribute("position",new we(y,g)),T.setAttribute("uv",new we(b,m)),T.setAttribute("faceIndex",new we(x,f)),s.push(new oe(T,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t,sigmas:r}}(t)),this._blurMaterial=function(e,t,s){const i=td(new Array(xf).fill(0)),n=Sa(new r(0,1,0)),a=Sa(0),o=yn(xf),u=Sa(0),l=Sa(1),d=Kl(),c=Sa(0),h=yn(1/t),p=yn(1/s),g=yn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:Mf,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Ff("blur");return f.fragmentNode=pf({...m,latitudinal:u.equal(1)}),Ef.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,r){const s=Kl(),i=Sa(0),n=Sa(0),a=yn(1/t),o=yn(1/r),u=yn(e),l={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:u},d=Ff("ggx");return d.fragmentNode=yf({...l,N_immutable:Mf,GGX_SAMPLES:xn(512)}),Ef.set(d,l),d}(t,e.width,e.height)}}async _compileMaterial(e){const t=new oe(new ve,e);await this._renderer.compile(t,Tf)}_sceneToCubeUV(e,t,r,s,i){const n=_f;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(vf),u.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new oe(new ae,new fe({name:"PMREM.Background",side:F,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,c=d.material;let h=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,h=!0):(c.color.copy(vf),h=!0),u.setRenderTarget(s),u.clear(),h&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;this._setViewport(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=p}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===D||e.mapping===I;s?null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(e)):null===this._equirectMaterial&&(this._equirectMaterial=Uf(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,Tf)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let t=1;tc-4?r-c+4:0),g=4*(this._cubeSize-h);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=d,o.mipInt.value=c-t,this._setViewport(i,p,g,3*h,2*h),s.setRenderTarget(i),s.render(a,Tf),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=c-r,this._setViewport(e,p,g,3*h,2*h),s.setRenderTarget(e),s.render(a,Tf)}_blur(e,t,r,s,i){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,r,s,"latitudinal",i),this._halfBlur(n,e,r,r,s,"longitudinal",i)}_halfBlur(e,t,r,s,i,n,a){const u=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&o("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[s];c.material=l;const h=Ef.get(l),p=this._sizeLods[r]-1,g=isFinite(i)?Math.PI/(2*p):2*Math.PI/39,m=i/g,f=isFinite(i)?1+Math.floor(3*m):xf;f>xf&&d(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const y=[];let b=0;for(let e=0;ex-4?s-x+4:0),v=4*(this._cubeSize-T);this._setViewport(t,_,v,3*T,2*T),u.setRenderTarget(t),u.render(c,Tf)}_setViewport(e,t,r,s,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-r,s,i),e.scissor.set(t,e.height-i-r,s,i)):(e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i))}}function Lf(e,t){const r=new ne(e,t,{magFilter:le,minFilter:le,generateMipmaps:!1,type:Te,format:Ae,colorSpace:Re});return r.texture.mapping=Ee,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Ff(e){const t=new vg;return t.depthTest=!1,t.depthWrite=!1,t.blending=re,t.name=`PMREM_${e}`,t}function Pf(e){const t=Ff("cubemap");return t.fragmentNode=$c(e,Mf),t}function Uf(e){const t=Ff("equirect");return t.fragmentNode=Kl(e,Bg(Mf),0),t}const Df=new WeakMap;function If(e,t,r){const s=function(e){let t=Df.get(e);void 0===t&&(t=new WeakMap,Df.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s0}(t))return null;i=r.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,s.set(e,i)}return i.texture}class Of extends gi{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new N;s.isRenderTargetTexture=!0,this._texture=Kl(s),this._width=Sa(0),this._height=Sa(0),this._maxMip=Sa(0),this.updateBeforeType=ri.RENDER}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,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,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 r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture?s:If(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Bf(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Uc.mul(Rn(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),df(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Vf=an(Of).setParameterLength(1,3),kf=new WeakMap;class Gf extends Op{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const s=r.isTextureNode?r.value:t[r.property],i=this._getPMREMNodeCache(e.renderer);let n=i.get(s);void 0===n&&(n=Vf(s),i.set(s,n)),r=n}const s=!0===t.useAnisotropy||t.anisotropy>0?_h:Sc,i=r.context(zf(Wn,s)).mul(Pc),n=r.context($f(Rc)).mul(Math.PI).mul(Pc),a=vl(i),o=vl(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(zf(jn,Ac)).mul(Pc),t=vl(e);u.addAssign(t)}}_getPMREMNodeCache(e){let t=kf.get(e);return void 0===t&&(t=new WeakMap,kf.set(e,t)),t}}const zf=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=gc.negate().reflect(t),r=du(e).mix(r,t).normalize(),r=r.transformDirection(Ud)),r),getTextureLevel:()=>e}},$f=e=>({getUV:()=>e,getTextureLevel:()=>yn(1)}),Wf=new Ce;class Hf extends vg{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(Wf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Gf(t):null}setupLightingModel(){return new qm}setupSpecular(){const e=gu(Rn(.04),Gn.rgb,Hn);sa.assign(Rn(.04)),ia.assign(e),na.assign(1)}setupVariants(){const e=this.metalnessNode?yn(this.metalnessNode):$h;Hn.assign(e);let t=this.roughnessNode?yn(this.roughnessNode):zh;t=em({roughness:t}),Wn.assign(t),this.setupSpecular(),zn.assign(Gn.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const qf=new Me;class jf extends Hf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(qf),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?yn(this.iorNode):sp;ca.assign(e),sa.assign(Jo(uu(ca.sub(1).div(ca.add(1))).mul(Vh),Rn(1)).mul(Oh)),ia.assign(gu(sa,Gn.rgb,Hn)),na.assign(gu(Oh,1,Hn))}setupLightingModel(){return new qm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?yn(this.clearcoatNode):Hh,t=this.clearcoatRoughnessNode?yn(this.clearcoatRoughnessNode):qh;qn.assign(e),jn.assign(em({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Rn(this.sheenNode):Kh,t=this.sheenRoughnessNode?yn(this.sheenRoughnessNode):Qh;Xn.assign(e),Kn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?yn(this.iridescenceNode):Zh,t=this.iridescenceIORNode?yn(this.iridescenceIORNode):Jh,r=this.iridescenceThicknessNode?yn(this.iridescenceThicknessNode):ep;Qn.assign(e),Yn.assign(t),Zn.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?_n(this.anisotropyNode):Yh).toVar();ea.assign(e.length()),gn(ea.equal(0),()=>{e.assign(_n(1,0))}).Else(()=>{e.divAssign(_n(ea)),ea.assign(ea.saturate())}),Jn.assign(ea.pow2().mix(Wn.pow2(),1)),ta.assign(xh[0].mul(e.x).add(xh[1].mul(e.y))),ra.assign(xh[1].mul(e.x).sub(xh[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?yn(this.transmissionNode):tp,t=this.thicknessNode?yn(this.thicknessNode):rp,r=this.attenuationDistanceNode?yn(this.attenuationDistanceNode):ip,s=this.attenuationColorNode?Rn(this.attenuationColorNode):np;if(ha.assign(e),pa.assign(t),ga.assign(r),ma.assign(s),this.useDispersion){const e=this.dispersionNode?yn(this.dispersionNode):hp;fa.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Rn(this.clearcoatNormalNode):jh}setup(e){e.context.setupClearcoatNormal=()=>Gu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}class Xf extends qm{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Sc.mul(a)).normalize(),h=yn(gc.dot(c.negate()).saturate().pow(l).mul(d)),p=Rn(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Kf extends jf{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=yn(.1),this.thicknessAmbientNode=yn(0),this.thicknessAttenuationNode=yn(.1),this.thicknessPowerNode=yn(2),this.thicknessScaleNode=yn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Xf(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}copy(e){return this.thicknessColorNode=e.thicknessColorNode,this.thicknessDistortionNode=e.thicknessDistortionNode,this.thicknessAmbientNode=e.thicknessAmbientNode,this.thicknessAttenuationNode=e.thicknessAttenuationNode,this.thicknessPowerNode=e.thicknessPowerNode,this.thicknessScaleNode=e.thicknessScaleNode,super.copy(e)}}const Qf=cn(({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=_n(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Kc("gradientMap","texture").context({getUV:()=>i});return Rn(e.r)}{const e=i.fwidth().mul(.5);return gu(Rn(.7),Rn(1),bu(yn(.7).sub(e.x),yn(.7).add(e.x),i.x))}});class Yf extends kg{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Qf({normal:xc,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Hg({diffuseColor:Gn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Zf=new Be;class Jf extends vg{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Zf),this.setValues(e)}setupLightingModel(){return new Yf}}const ey=cn(()=>{const e=Rn(gc.z,0,gc.x.negate()).normalize(),t=gc.cross(e);return _n(e.dot(Sc),t.dot(Sc)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),ty=new Le;class ry extends vg{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupVariants(e){const t=ey;let r;r=e.material.matcap?Kc("matcap","texture").context({getUV:()=>t}):Rn(gu(.2,.8,t.y)),Gn.rgb.mulAssign(r.rgb)}}class sy extends gi{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return Fn(e,s,s.negate(),e).mul(r)}{const e=t,s=Un(Cn(1,0,0,0),Cn(0,Co(e.x),Eo(e.x).negate(),0),Cn(0,Eo(e.x),Co(e.x),0),Cn(0,0,0,1)),i=Un(Cn(Co(e.y),0,Eo(e.y),0),Cn(0,1,0,0),Cn(Eo(e.y).negate(),0,Co(e.y),0),Cn(0,0,0,1)),n=Un(Cn(Co(e.z),Eo(e.z).negate(),0,0),Cn(Eo(e.z),Co(e.z),0,0),Cn(0,0,1,0),Cn(0,0,0,1));return s.mul(i).mul(n).mul(Cn(r,1)).xyz}}}const iy=an(sy).setParameterLength(2),ny=new Fe;class ay extends vg{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ny),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=sc.mul(Rn(s||0));let u=_n(Qd[0].xyz.length(),Qd[1].xyz.length());null!==n&&(u=u.mul(_n(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=uc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>new Zu(e,t,r))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=yn(i||Xh),c=iy(l,d);return Cn(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const oy=new Pe,uy=new t;class ly extends ay{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(oy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return sc.mul(Rn(e||lc)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?_n(n):cp;u=u.mul(od),r.isPerspectiveCamera&&!0===a&&(u=u.mul(dy.div(pc.z.negate()))),i&&i.isNode&&(u=u.mul(_n(i)));let l=uc.xy;if(s&&s.isNode){const e=yn(s);l=iy(l,e)}return l=l.mul(u),l=l.div(hd.div(2)),l=l.mul(o.w),o=o.add(Cn(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const dy=Sa(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(uy);this.value=.5*t.y});class cy extends kg{constructor(){super(),this.shadowNode=yn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Gn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Gn.rgb)}}const hy=new Ue;class py extends vg{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(hy),this.setValues(e)}setupLightingModel(){return new cy}}const gy=Vn("vec3"),my=Vn("vec3"),fy=Vn("vec3");class yy extends kg{constructor(){super()}start(e){const{material:t}=e,r=Vn("vec3"),s=Vn("vec3");gn(Od.sub(cc).length().greaterThan(ec.mul(2)),()=>{r.assign(Od),s.assign(cc)}).Else(()=>{r.assign(cc),s.assign(Od)});const i=s.sub(r),n=Sa("int").onRenderUpdate(({material:e})=>e.steps),a=i.length().div(n).toVar(),o=i.normalize().toVar(),u=yn(0).toVar(),l=Rn(1).toVar();t.offsetNode&&u.addAssign(t.offsetNode.mul(a)),Bp(n,()=>{const s=r.add(o.mul(u)),i=Ud.mul(Cn(s,1)).xyz;let n;null!==t.depthNode&&(my.assign(og(tg(i.z,Bd,Ld))),e.context.sceneDepthNode=og(t.depthNode).toVar()),e.context.positionWorld=s,e.context.shadowPositionWorld=s,e.context.positionView=i,gy.assign(0),t.scatteringNode&&(n=t.scatteringNode({positionRay:s})),super.start(e),n&&gy.mulAssign(n);const d=gy.mul(.01).negate().mul(a).exp();l.mulAssign(d),u.addAssign(a)}),fy.addAssign(l.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?gn(r.greaterThanEqual(my),()=>{gy.addAssign(e)}):gy.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(void 0===e.light.distance)return;const s=t.xyz.toVar();s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul(Tm({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(fy)}}class by extends vg{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=F,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new yy}}class xy{constructor(e,t,r){this.renderer=e,this.nodes=t,this.info=r,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,r),this.renderer._inspector.finish()};e()}stop(){null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Ty{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let r=this.weakMaps[t];return void 0===r&&(r=new WeakMap,this.weakMaps[t]=r),r}get(e){let t=this._getWeakMap(e);for(let r=0;r{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),i[n.name]=e.id),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e1||Array.isArray(e.morphTargetInfluences))&&(s+=e.uuid+","),s+=this.context.id+",",s+=e.receiveShadow+",",Vs(s)}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 r=this.geometry.getAttribute(t);if(void 0===r||e[t]!==r.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Gs(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Gs(e,1)),e=Gs(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Ny=[];class Sy{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);Ny[0]=e,Ny[1]=t,Ny[2]=n,Ny[3]=i;let l=u.get(Ny);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Ny,l)):(l.camera=s,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Ny[0]=null,Ny[1]=null,Ny[2]=null,Ny[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Ty)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new vy(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.deleteForRender(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Ry{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 Ay=1,Ey=2,wy=3,Cy=4,My=16;class By extends Ry{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 r=this.get(e);if(void 0===r.version)t===Ay?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ey?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===wy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Cy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version=65535?De:Ie)(t,1);return i.version=Ly(e),i.__id=Fy(e),i}class Uy extends Ry{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 r=()=>{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,wy):this.updateAttribute(e,Ay);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,Ey);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,Cy)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=Py(t),e.set(t,r)):r.version===Ly(t)&&r.__id===Fy(t)||(this.attributes.delete(r),r=Py(t),e.set(t,r)),s=r}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Dy{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,r){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=r*(t/3):e.isPoints?this.render.points+=r*t:e.isLineSegments?this.render.lines+=r*(t/2):e.isLine?this.render.lines+=r*(t-1):o("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const r=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:r,type:t}),this.memory[t]++,this.memory.total+=r,this.memory[t+"Size"]+=r}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Oe||e.type===Ve?t=1:e.type===ke||e.type===Ge||e.type===Te?t=2:e.type!==R&&e.type!==S&&e.type!==K||(t=4);let r=4;e.format===ze||e.format===$e||e.format===We||e.format===He||e.format===qe?r=1:e.format===$||e.format===je?r=2:e.format!==Xe&&e.format!==Ke||(r=3);let s=t*r;e.type===Qe||e.type===Ye?s=2:e.type!==Ze&&e.type!==Je&&e.type!==et||(s=4);const i=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=i*n*a*s;const u=e.mipmaps;if(u&&u.length>0){let e=0;for(let t=0;t>t))*(r.height||Math.max(1,n>>t))*a*s}}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 Iy{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Oy extends Iy{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Vy extends Iy{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let ky=0;class Gy{constructor(e,t,r,s=null,i=null){this.id=ky++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class zy extends Ry{constructor(e,t,r){super(),this.backend=e,this.nodes=t,this.info=r,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new Gy(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new Gy(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o),this.info.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new Gy(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u),this.info.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const r=this.backend.get(t);return void 0!==r.pipeline&&null!==r.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,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new Vy(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new Oy(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].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 $y extends Ry{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?Cy:wy;this.attributes.update(e,r)}}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,i=e.isIndirectStorageBufferAttribute?Cy:wy,n=r.get(t);this.attributes.update(e,i),n.attribute!==e&&(n.attribute=e,s=!0)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),u=t.texture,l=this.textures.get(u);o&&(this.textures.updateTexture(u),t.generation!==l.generation&&(t.generation=l.generation,s=!0),l.bindGroups.add(e));if(void 0!==r.get(u).externalTexture||l.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===u.isStorageTexture&&!0===u.mipmapsAutoUpdate){const e=this.get(u);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(u)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(u),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,s=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function Wy(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 Hy(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 qy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===P&&!1===e.forceSinglePass}class jy{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,r),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&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||Wy),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Hy),this.transparent.length>1&&this.transparent.sort(t||Hy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&d&&(l=new Z,l.format=e.stencilBuffer?qe:He,l.type=e.stencilBuffer?Ze:S,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=l),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=l.isArrayTexture?l.image.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const h={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener("dispose",r.onDispose))}updateTexture(e,t={}){const r=this.get(e);if(!0===r.initialized&&r.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(s&&!0===r.initialized&&i.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:Ve}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;"requestPaint"in t&&(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image))}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),r.generation=e.version;else if(e.version>0){const s=e.image;if(void 0===s)d("Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)d("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version;!0!==r.initialized&&(r.initialized=!0,r.generation=e.version,r.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===p.enabled&&p.getTransfer(e.colorSpace)!==g&&d("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),r.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",r.onDispose)),r.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=eb){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),e.isHTMLTexture?(t.width=r.offsetWidth||1,t.height=r.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),r=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e=2)for(let r=0;r{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===s)t.build(e);else if("analyze"===s)t.build(e,this);else if("generate"===s){const r=e.getDataFromNode(t,"any").stages,s=r&&r[e.shaderStage];if(t.isVarNode&&s&&1===s.length&&s[0]&&s[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)i(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)i(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),hn(r),e.removeActiveStack(this),o}}const nb=an(ib).setParameterLength(0,1);class ab extends ci{static get type(){return"StructTypeNode"}constructor(e,t=null){var r;super("struct"),this.membersLayout=(r=e,Object.entries(r).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,r=0;for(const s of this.membersLayout){const i=s.type,n=js(i),a=Xs(i)/e;t=Math.max(t,a);const o=r%t%a;0!==o&&(r+=a-o),r+=n}return Math.ceil(r/t)*t}getMemberType(e,t){const r=this.membersLayout.find(e=>e.name===t);return r?r.type:"void"}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class ob extends ci{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){const e=super._getChildren(),t=e.find(e=>e.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class ub extends ci{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}generateNodeType(){return"OutputType"}generate(e){const t=e.getDataFromNode(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;tnew fb(e,"uint","float"),xb={};class Tb extends no{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,r){"int"===r?t.assign(yb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return xn;case"int":return bn;case"uvec2":return Nn;case"uvec3":return En;case"uvec4":return Bn;case"ivec2":return vn;case"ivec3":return An;case"ivec4":return Mn}}_createTrailingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t);const i=yn(s.bitAnd(zo(s))),n=bb(i).shiftRight(23).sub(127);return r(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{gn(e.equal(xn(0)),()=>xn(32));const s=xn(0),i=xn(0);return this._resolveElementType(e,s,t),gn(s.shiftRight(16).equal(0),()=>{i.addAssign(16),s.shiftLeftAssign(16)}),gn(s.shiftRight(24).equal(0),()=>{i.addAssign(8),s.shiftLeftAssign(8)}),gn(s.shiftRight(28).equal(0),()=>{i.addAssign(4),s.shiftLeftAssign(4)}),gn(s.shiftRight(30).equal(0),()=>{i.addAssign(2),s.shiftLeftAssign(2)}),gn(s.shiftRight(31).equal(0),()=>{i.addAssign(1)}),r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t),s.assign(s.sub(s.shiftRight(xn(1)).bitAnd(xn(1431655765)))),s.assign(s.bitAnd(xn(858993459)).add(s.shiftRight(xn(2)).bitAnd(xn(858993459))));const i=s.add(s.shiftRight(xn(4))).bitAnd(xn(252645135)).mul(xn(16843009)).shiftRight(xn(24));return r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,r,s){const i=this._returnDataNode(t);return cn(([e])=>{if(1===r)return i(s(e));{const t=i(0),n=["x","y","z","w"];for(let i=0;id(r))()}}Tb.COUNT_TRAILING_ZEROS="countTrailingZeros",Tb.COUNT_LEADING_ZEROS="countLeadingZeros",Tb.COUNT_ONE_BITS="countOneBits";const _b=un(Tb,Tb.COUNT_TRAILING_ZEROS).setParameterLength(1),vb=un(Tb,Tb.COUNT_LEADING_ZEROS).setParameterLength(1),Nb=un(Tb,Tb.COUNT_ONE_BITS).setParameterLength(1),Sb=cn(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)}),Rb=(e,t)=>ou(Ua(4,e.mul(Pa(1,e))),t);class Ab extends gi{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}generateNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const Eb=un(Ab,"snorm").setParameterLength(1),wb=un(Ab,"unorm").setParameterLength(1),Cb=un(Ab,"float16").setParameterLength(1);class Mb extends gi{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}generateNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const Bb=un(Mb,"snorm").setParameterLength(1),Lb=un(Mb,"unorm").setParameterLength(1),Fb=un(Mb,"float16").setParameterLength(1),Pb=cn(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Ub=cn(([e])=>Rn(Pb(e.z.add(Pb(e.y.mul(1)))),Pb(e.z.add(Pb(e.x.mul(1)))),Pb(e.y.add(Pb(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Db=cn(([e,t,r])=>{const s=Rn(e).toVar(),i=yn(1.4).toVar(),n=yn(0).toVar(),a=Rn(s).toVar();return Bp({start:yn(0),end:yn(3),type:"float",condition:"<="},()=>{const e=Rn(Ub(a.mul(2))).toVar();s.addAssign(e.add(r.mul(yn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=yn(Pb(s.z.add(Pb(s.x.add(Pb(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class Ib extends ci{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let r=this._candidateFn;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;ri&&(s=r,i=n)}}this._candidateFn=r=s}return r}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const Ob=an(Ib),Vb=e=>(...t)=>Ob(e,...t),kb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.time),Gb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.deltaTime),zb=Sa(0,"uint").setGroup(_a).onRenderUpdate(e=>e.frameId);const $b=cn(([e,t,r=_n(.5)])=>iy(e.sub(r),t).add(r)),Wb=cn(([e,t,r=_n(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))}),Hb=cn(({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=Qd.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=Qd;const i=Ud.mul(s);return Zi(t)&&(i[0][0]=Qd[0].length(),i[0][1]=0,i[0][2]=0),Zi(r)&&(i[1][0]=0,i[1][1]=Qd[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,Fd.mul(i).mul(lc)}),qb=cn(([e=null])=>{const t=og();return og(Yp(e)).sub(t).lessThan(0).select(ud,e)}),jb=cn(([e,t=kl(),r=yn(0)])=>{const s=e.x,i=e.y,n=r.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=e.reciprocal(),l=_n(a,o);return t.add(l).mul(u)}),Xb=cn(([e,t=null,r=null,s=yn(1),i=lc,n=Tc])=>{let a=n.abs().normalize();a=a.div(a.dot(Rn(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=Kl(d,o).mul(a.x),g=Kl(c,u).mul(a.y),m=Kl(h,l).mul(a.z);return Fa(p,g,m)}),Kb=new ut,Qb=new r,Yb=new r,Zb=new r,Jb=new a,ex=new r(0,0,-1),tx=new s,rx=new r,sx=new r,ix=new s,nx=new t,ax=new ne,ox=ud.flipX();ax.depthTexture=new Z(1,1);let ux=!1;class lx extends jl{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||ax.texture,ox),this._reflectorBaseNode=e.reflector||new dx(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new lx({defaultTexture:ax.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class dx extends ci{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new at,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(v('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?ri.RENDER:ri.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(nx),e.setSize(Math.round(nx.width*r),Math.round(nx.height*r))}setup(e){return this._updateResolution(ax,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new ne(0,0,{type:Te,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=ot,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Z),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&ux)return!1;ux=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(nx),this._updateResolution(o,s),Yb.setFromMatrixPosition(n.matrixWorld),Zb.setFromMatrixPosition(r.matrixWorld),Jb.extractRotation(n.matrixWorld),Qb.set(0,0,1),Qb.applyMatrix4(Jb),rx.subVectors(Yb,Zb);let u=!1;if(!0===rx.dot(Qb)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(ux=!1);u=!0}rx.reflect(Qb).negate(),rx.add(Yb),Jb.extractRotation(r.matrixWorld),ex.set(0,0,-1),ex.applyMatrix4(Jb),ex.add(Zb),sx.subVectors(Yb,ex),sx.reflect(Qb).negate(),sx.add(Yb),a.coordinateSystem=r.coordinateSystem,a.position.copy(rx),a.up.set(0,1,0),a.up.applyMatrix4(Jb),a.up.reflect(Qb),a.lookAt(sx),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Kb.setFromNormalAndCoplanarPoint(Qb,Yb),Kb.applyMatrix4(a.matrixWorldInverse),tx.set(Kb.normal.x,Kb.normal.y,Kb.normal.z,Kb.constant);const l=a.projectionMatrix;ix.x=(Math.sign(tx.x)+l.elements[8])/l.elements[0],ix.y=(Math.sign(tx.y)+l.elements[9])/l.elements[5],ix.z=-1,ix.w=(1+l.elements[10])/l.elements[14],tx.multiplyScalar(1/tx.dot(ix));l.elements[2]=tx.x,l.elements[6]=tx.y,l.elements[10]=s.coordinateSystem===h?tx.z-0:tx.z+1-0,l.elements[14]=tx.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const d=s.getRenderTarget(),c=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0;const g=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),t.name=g,s.setMRT(c),s.setRenderTarget(d),s.autoClear=p,i.visible=!0,ux=!1,this.forceUpdate=!1}get resolution(){return v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const cx=new Ne(-1,1,1,-1,0,1);class hx extends ve{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lt(t,2))}}const px=new hx;class gx extends oe{constructor(e=null){super(px,e),this.camera=cx,this.isQuadMesh=!0}async renderAsync(e){v('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,cx)}render(e){e.render(this,cx)}}const mx=new t;class fx extends jl{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:Te}){const i=new ne(t,r,s);super(i.texture,kl()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.pixelRatio=1,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new gx(new vg),this.updateBeforeType=ri.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const r=e*this.pixelRatio,s=t*this.pixelRatio;this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),r=e.getSize(mx),s=Math.floor(r.width*t),i=Math.floor(r.height*t);s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const r=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(r)}clone(){const e=new jl(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const yx=(e,...t)=>new fx(tn(e),...t),bx=cn(([e,t,r],s)=>{let i;s.renderer.coordinateSystem===h?(e=_n(e.x,e.y.oneMinus()).mul(2).sub(1),i=Cn(Rn(e,t),1)):i=Cn(Rn(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Cn(r.mul(i));return n.xyz.div(n.w)}),xx=cn(([e,t])=>{const r=t.mul(Cn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return _n(s.x,s.y.oneMinus())}),Tx=cn(([e,t,r])=>{const s=zl(Ql(t)),i=vn(e.mul(s)).toVar(),n=Ql(t,i).toVar(),a=Ql(t,i.sub(vn(2,0))).toVar(),o=Ql(t,i.sub(vn(1,0))).toVar(),u=Ql(t,i.add(vn(1,0))).toVar(),l=Ql(t,i.add(vn(2,0))).toVar(),d=Ql(t,i.add(vn(0,2))).toVar(),c=Ql(t,i.add(vn(0,1))).toVar(),h=Ql(t,i.sub(vn(0,1))).toVar(),p=Ql(t,i.sub(vn(0,2))).toVar(),g=Vo(Pa(yn(2).mul(o).sub(a),n)).toVar(),m=Vo(Pa(yn(2).mul(u).sub(l),n)).toVar(),f=Vo(Pa(yn(2).mul(c).sub(d),n)).toVar(),y=Vo(Pa(yn(2).mul(h).sub(p),n)).toVar(),b=bx(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(bx(e.sub(_n(yn(1).div(s.x),0)),o,r)),b.negate().add(bx(e.add(_n(yn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(bx(e.add(_n(0,yn(1).div(s.y))),c,r)),b.negate().add(bx(e.sub(_n(0,yn(1).div(s.y))),h,r)));return Ro(au(x,T))}),_x=cn(([e])=>Ao(yn(52.9829189).mul(Ao(nu(e,_n(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),vx=cn(([e,t,r])=>{const s=yn(2.399963229728653),i=_o(yn(e).add(.5).div(yn(t))),n=yn(e).mul(s).add(r);return _n(Co(n),Eo(n)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class Nx extends ci{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(kl())}sample(e){return this.callback(e)}}class Sx extends ci{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Sx.OBJECT?this.updateType=ri.OBJECT:e===Sx.MATERIAL?this.updateType=ri.RENDER:e===Sx.FRAME?this.updateType=ri.FRAME:e===Sx.BEFORE_OBJECT?this.updateBeforeType=ri.OBJECT:e===Sx.BEFORE_MATERIAL?this.updateBeforeType=ri.RENDER:e===Sx.BEFORE_FRAME&&(this.updateBeforeType=ri.FRAME)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}Sx.OBJECT="object",Sx.MATERIAL="material",Sx.FRAME="frame",Sx.BEFORE_OBJECT="beforeObject",Sx.BEFORE_MATERIAL="beforeMaterial",Sx.BEFORE_FRAME="beforeFrame";const Rx=(e,t)=>new Sx(e,t).toStack();class Ax extends q{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Ex extends we{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class wx extends ci{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Cx=on(wx),Mx=new a,Bx=Sa(0).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Lx=Sa(1).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundIntensity),Fx=Sa(new a).setGroup(_a).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&t.mapping!==dt?Mx.makeRotationFromEuler(e.backgroundRotation).transpose():Mx.identity(),Mx});class Px extends jl{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=ii.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return null!==this.storeNode?(this.generateStore(e),""):super.generate(e,t)}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;return e.generateStorageTextureLoad(l,t,r,s,n,u)}toReadWrite(){return this.setAccess(ii.READ_WRITE)}toReadOnly(){return this.setAccess(ii.READ_ONLY)}toWriteOnly(){return this.setAccess(ii.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(this.value,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}}const Ux=an(Px).setParameterLength(1,3),Dx=cn(({texture:e,uv:t})=>{const r=1e-4,s=Rn().toVar();return gn(t.x.lessThan(r),()=>{s.assign(Rn(1,0,0))}).ElseIf(t.y.lessThan(r),()=>{s.assign(Rn(0,1,0))}).ElseIf(t.z.lessThan(r),()=>{s.assign(Rn(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{s.assign(Rn(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{s.assign(Rn(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{s.assign(Rn(0,0,-1))}).Else(()=>{const r=.01,i=e.sample(t.add(Rn(-.01,0,0))).r.sub(e.sample(t.add(Rn(r,0,0))).r),n=e.sample(t.add(Rn(0,-.01,0))).r.sub(e.sample(t.add(Rn(0,r,0))).r),a=e.sample(t.add(Rn(0,0,-.01))).r.sub(e.sample(t.add(Rn(0,0,r))).r);s.assign(Rn(i,n,a))}),s.normalize()});class Ix extends jl{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Rn(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return Dx({texture:this,uv:e})}}const Ox=an(Ix).setParameterLength(1,3);class Vx extends Hc{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const kx=new WeakMap;class Gx extends gi{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=ri.OBJECT,this.updateAfterType=ri.OBJECT,this.previousModelWorldMatrix=Sa(new a),this.previousProjectionMatrix=Sa(new a).setGroup(_a),this.previousCameraViewMatrix=Sa(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=$x(r);this.previousModelWorldMatrix.value.copy(s);const i=zx(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new a,i.previousCameraViewMatrix=new a,i.currentProjectionMatrix=new a,i.currentCameraViewMatrix=new a,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){$x(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Fd:Sa(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(sc).mul(lc),s=this.previousProjectionMatrix.mul(t).mul(dc),i=r.xy.div(r.w),n=s.xy.div(s.w);return Pa(i,n)}}function zx(e){let t=kx.get(e);return void 0===t&&(t={},kx.set(e,t)),t}function $x(e,t=0){const r=zx(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const Wx=on(Gx),Hx=cn(([e])=>Kx(e.rgb)),qx=cn(([e,t=yn(1)])=>t.mix(Kx(e.rgb),e.rgb)),jx=cn(([e,t=yn(1)])=>{const r=Fa(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return gu(e.rgb,s,i)}),Xx=cn(([e,t=yn(1)])=>{const r=Rn(.57735,.57735,.57735),s=t.cos();return Rn(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(nu(r,e.rgb).mul(s.oneMinus())))))}),Kx=(e,t=Rn(p.getLuminanceCoefficients(new r)))=>nu(e,t),Qx=cn(([e,t=Rn(1),s=Rn(0),i=Rn(1),n=yn(1),a=Rn(p.getLuminanceCoefficients(new r,Re))])=>{const o=e.rgb.dot(Rn(a)),u=eu(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return gn(u.r.greaterThan(0),()=>{u.r.assign(l.r)}),gn(u.g.greaterThan(0),()=>{u.g.assign(l.g)}),gn(u.b.greaterThan(0),()=>{u.b.assign(l.b)}),u.assign(o.add(u.sub(o).mul(n))),Cn(u.rgb,e.a)}),Yx=cn(([e,t])=>e.mul(t).floor().div(t));let Zx=null;class Jx extends Wp{static get type(){return"ViewportSharedTextureNode"}constructor(e=ud,t=null){null===Zx&&(Zx=new Q),super(e,t,Zx)}getTextureForReference(){return Zx}updateReference(){return this}}const eT=an(Jx).setParameterLength(0,2),tT=new t;class rT extends jl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class sT extends rT{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class iT extends gi{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const i=new Z;i.isRenderTargetTexture=!0,i.name="depth";const n=new ne(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Te,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Sa(0),this._cameraFar=Sa(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=ri.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return d("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return d("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new sT(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new sT(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=sg(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=Jp(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),!0===e.reversedDepthBuffer&&(this.renderTarget.depthTexture.type=K),this.scope===iT.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s,i;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(i=1,s=t.xr.getCamera(),t.xr.updateCamera(s),tT.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(tT)),this._pixelRatio=i,this.setSize(tT.width,tT.height);const a=t.getRenderTarget(),o=t.getMRT(),u=t.autoClear,l=t.transparent,d=t.opaque,c=s.layers.mask,h=t.contextNode,p=r.overrideMaterial;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(r.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Cu({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const g=r.name;r.name=this.name?this.name:r.name,t.render(r,s),r.name=g,r.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=u,t.transparent=l,t.opaque=d,t.contextNode=h,s.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const r=Math.floor(this._width*this._pixelRatio*this._resolutionScale),s=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(r,s),null!==this._scissor?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,r,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new s),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,i))}setViewport(e,t,r,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new s),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}iT.COLOR="color",iT.DEPTH="depth";class nT extends iT{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(iT.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)}),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new vg;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=F;const t=Tc.negate(),r=Fd.mul(sc),s=yn(1),i=r.mul(Cn(lc,1)),n=r.mul(Cn(lc.add(t),1)),a=Ro(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=Cn(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const aT=cn(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),oT=cn(([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"}]}),uT=cn(([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lT=cn(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)}),dT=cn(([e,t])=>{const r=Pn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Pn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=lT(e),(e=s.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),cT=Pn(Rn(1.6605,-.1246,-.0182),Rn(-.5876,1.1329,-.1006),Rn(-.0728,-.0083,1.1187)),hT=Pn(Rn(.6274,.0691,.0164),Rn(.3293,.9195,.088),Rn(.0433,.0113,.8956)),pT=cn(([e])=>{const t=Rn(e).toVar(),r=Rn(t.mul(t)).toVar(),s=Rn(r.mul(r)).toVar();return yn(15.5).mul(s.mul(r)).sub(Ua(40.14,s.mul(t))).add(Ua(31.96,s).sub(Ua(6.868,r.mul(t))).add(Ua(.4298,r).add(Ua(.1191,t).sub(.00232))))}),gT=cn(([e,t])=>{const r=Rn(e).toVar(),s=Pn(Rn(.856627153315983,.137318972929847,.11189821299995),Rn(.0951212405381588,.761241990602591,.0767994186031903),Rn(.0482516061458583,.101439036467562,.811302368396859)),i=Pn(Rn(1.1271005818144368,-.1413297634984383,-.14132976349843826),Rn(-.11060664309660323,1.157823702216272,-.11060664309660294),Rn(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=yn(-12.47393),a=yn(4.026069);return r.mulAssign(t),r.assign(hT.mul(r)),r.assign(s.mul(r)),r.assign(eu(r,1e-10)),r.assign(To(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(mu(r,0,1)),r.assign(pT(r)),r.assign(i.mul(r)),r.assign(ou(eu(Rn(0),r),Rn(2.2))),r.assign(cT.mul(r)),r.assign(mu(r,0,1)),r}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),mT=cn(([e,t])=>{const r=yn(.76),s=yn(.15);e=e.mul(t);const i=Jo(e.r,Jo(e.g,e.b)),n=Eu(i.lessThan(.08),i.sub(Ua(6.25,i.mul(i))),.04);e.subAssign(n);const a=eu(e.r,eu(e.g,e.b));gn(a.lessThan(r),()=>e);const o=Pa(1,r),u=Pa(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=Pa(1,Da(1,s.mul(a.sub(u)).add(1)));return gu(e,Rn(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class fT extends ci{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.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}}const yT=an(fT).setParameterLength(1,3);class bT extends fT{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const xT=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};function TT(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||pc.z).negate()}const _T=cn(([e,t],r)=>{const s=TT(r);return bu(e,t,s)}),vT=cn(([e],t)=>{const r=TT(t);return e.mul(e,r,r).negate().exp().oneMinus()}),NT=cn(([e,t],r)=>{const s=TT(r),i=t.sub(cc.y).max(0).toConst().mul(s).toConst();return e.mul(e,i,i).negate().exp().oneMinus()}),ST=cn(([e,t])=>Cn(t.toFloat().mix(oa.rgb,e.toVec3()),oa.a));let RT=null,AT=null;class ET extends ci{static get type(){return"RangeNode"}constructor(e=yn(),t=yn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),s=e.getTypeLength(Ks(t.value)),i=e.getTypeLength(Ks(r.value));return s>i?s:i}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Hl('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=i.value,o=n.value,u=e.getTypeLength(Ks(a)),d=e.getTypeLength(Ks(o));RT=RT||new s,AT=AT||new s,RT.setScalar(0),AT.setScalar(0),1===u?RT.setScalar(a):a.isColor?RT.set(a.r,a.g,a.b,1):RT.set(a.x,a.y,a.z||0,a.w||0),1===d?AT.setScalar(o):o.isColor?AT.set(o.r,o.g,o.b,1):AT.set(o.x,o.y,o.z||0,o.w||0);const c=4,h=c*t.count,p=new Float32Array(h);for(let e=0;enew CT(e,t),BT=MT("numWorkgroups","uvec3"),LT=MT("workgroupId","uvec3"),FT=MT("globalId","uvec3"),PT=MT("localId","uvec3"),UT=MT("subgroupSize","uint");class DT extends ci{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}const IT=an(DT);class OT extends hi{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.context.assign;if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class VT extends ci{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new OT(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class kT extends ci{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Cl(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}kT.ATOMIC_LOAD="atomicLoad",kT.ATOMIC_STORE="atomicStore",kT.ATOMIC_ADD="atomicAdd",kT.ATOMIC_SUB="atomicSub",kT.ATOMIC_MAX="atomicMax",kT.ATOMIC_MIN="atomicMin",kT.ATOMIC_AND="atomicAnd",kT.ATOMIC_OR="atomicOr",kT.ATOMIC_XOR="atomicXor";const GT=an(kT),zT=(e,t,r)=>GT(e,t,r).toStack();class $T extends gi{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}generateNodeType(e){const t=this.method;return t===$T.SUBGROUP_ELECT?"bool":t===$T.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===$T.SUBGROUP_BROADCAST||r===$T.SUBGROUP_SHUFFLE||r===$T.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===$T.SUBGROUP_SHUFFLE_XOR||r===$T.SUBGROUP_SHUFFLE_DOWN||r===$T.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}$T.SUBGROUP_ELECT="subgroupElect",$T.SUBGROUP_BALLOT="subgroupBallot",$T.SUBGROUP_ADD="subgroupAdd",$T.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",$T.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",$T.SUBGROUP_MUL="subgroupMul",$T.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",$T.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",$T.SUBGROUP_AND="subgroupAnd",$T.SUBGROUP_OR="subgroupOr",$T.SUBGROUP_XOR="subgroupXor",$T.SUBGROUP_MIN="subgroupMin",$T.SUBGROUP_MAX="subgroupMax",$T.SUBGROUP_ALL="subgroupAll",$T.SUBGROUP_ANY="subgroupAny",$T.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",$T.QUAD_SWAP_X="quadSwapX",$T.QUAD_SWAP_Y="quadSwapY",$T.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",$T.SUBGROUP_BROADCAST="subgroupBroadcast",$T.SUBGROUP_SHUFFLE="subgroupShuffle",$T.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",$T.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",$T.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",$T.QUAD_BROADCAST="quadBroadcast";const WT=un($T,$T.SUBGROUP_ELECT).setParameterLength(0),HT=un($T,$T.SUBGROUP_BALLOT).setParameterLength(1),qT=un($T,$T.SUBGROUP_ADD).setParameterLength(1),jT=un($T,$T.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),XT=un($T,$T.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),KT=un($T,$T.SUBGROUP_MUL).setParameterLength(1),QT=un($T,$T.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),YT=un($T,$T.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),ZT=un($T,$T.SUBGROUP_AND).setParameterLength(1),JT=un($T,$T.SUBGROUP_OR).setParameterLength(1),e_=un($T,$T.SUBGROUP_XOR).setParameterLength(1),t_=un($T,$T.SUBGROUP_MIN).setParameterLength(1),r_=un($T,$T.SUBGROUP_MAX).setParameterLength(1),s_=un($T,$T.SUBGROUP_ALL).setParameterLength(0),i_=un($T,$T.SUBGROUP_ANY).setParameterLength(0),n_=un($T,$T.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),a_=un($T,$T.QUAD_SWAP_X).setParameterLength(1),o_=un($T,$T.QUAD_SWAP_Y).setParameterLength(1),u_=un($T,$T.QUAD_SWAP_DIAGONAL).setParameterLength(1),l_=un($T,$T.SUBGROUP_BROADCAST).setParameterLength(2),d_=un($T,$T.SUBGROUP_SHUFFLE).setParameterLength(2),c_=un($T,$T.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),h_=un($T,$T.SUBGROUP_SHUFFLE_UP).setParameterLength(2),p_=un($T,$T.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),g_=un($T,$T.QUAD_BROADCAST).setParameterLength(1);let m_;function f_(e){m_=m_||new WeakMap;let t=m_.get(e);return void 0===t&&m_.set(e,t={}),t}function y_(e){const t=f_(e);return t.shadowMatrix||(t.shadowMatrix=Sa("mat4").setGroup(_a).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 b_(e,t=cc){const r=y_(e).mul(t);return r.xyz.div(r.w)}function x_(e){const t=f_(e);return t.position||(t.position=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld)))}function T_(e){const t=f_(e);return t.targetPosition||(t.targetPosition=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld)))}function __(e){const t=f_(e);return t.viewPosition||(t.viewPosition=Sa(new r).setGroup(_a).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const v_=e=>Ud.transformDirection(x_(e).sub(T_(e))),N_=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},S_=new WeakMap,R_=[];class A_ extends ci{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Vn("vec3","totalDiffuse"),this.totalSpecularNode=Vn("vec3","totalSpecular"),this.outgoingLightNode=Vn("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(tn(e));else{let s=null;if(null!==r&&(s=N_(e.id,r)),null===s){const t=i.getLightNodeClass(e.constructor);if(null===t){d(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===S_.has(e)&&S_.set(e,new t(e)),s=S_.get(e)}t.push(s)}this._lightNodes=t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=Rn(null!==l?l.mix(g,u):u)),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class E_ extends ci{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ri.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){w_.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||cc)}}const w_=Vn("vec3","shadowPositionWorld");function C_(t,r={}){return r.toneMapping=t.toneMapping,r.toneMappingExposure=t.toneMappingExposure,r.outputColorSpace=t.outputColorSpace,r.renderTarget=t.getRenderTarget(),r.activeCubeFace=t.getActiveCubeFace(),r.activeMipmapLevel=t.getActiveMipmapLevel(),r.renderObjectFunction=t.getRenderObjectFunction(),r.pixelRatio=t.getPixelRatio(),r.mrt=t.getMRT(),r.clearColor=t.getClearColor(r.clearColor||new e),r.clearAlpha=t.getClearAlpha(),r.autoClear=t.autoClear,r.scissorTest=t.getScissorTest(),r}function M_(e,t){return t=C_(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function B_(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)}function L_(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function F_(e,t){return t=L_(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function P_(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function U_(e,t,r){return r=F_(t,r=M_(e,r))}function D_(e,t,r){B_(e,r),P_(t,r)}var I_=Object.freeze({__proto__:null,resetRendererAndSceneState:U_,resetRendererState:M_,resetSceneState:F_,restoreRendererAndSceneState:D_,restoreRendererState:B_,restoreSceneState:P_,saveRendererAndSceneState:function(e,t,r={}){return r=L_(t,r=C_(e,r))},saveRendererState:C_,saveSceneState:L_});const O_=new WeakMap,V_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Kl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)}),k_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=qc("radius","float",r).setGroup(_a),o=_n(1).div(n),u=a.mul(o.x),l=_x(dd.xy).mul(6.28318530718);return Fa(i(t.xy.add(vx(0,5,l).mul(u)),t.z),i(t.xy.add(vx(1,5,l).mul(u)),t.z),i(t.xy.add(vx(2,5,l).mul(u)),t.z),i(t.xy.add(vx(3,5,l).mul(u)),t.z),i(t.xy.add(vx(4,5,l).mul(u)),t.z)).mul(.2)}),G_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=_n(1).div(n),o=a.x,u=a.y,l=t.xy,d=Ao(l.mul(n).add(.5));return l.subAssign(d.mul(a)),Fa(i(l,t.z),i(l.add(_n(o,0)),t.z),i(l.add(_n(0,u)),t.z),i(l.add(a),t.z),gu(i(l.add(_n(o.negate(),0)),t.z),i(l.add(_n(o.mul(2),0)),t.z),d.x),gu(i(l.add(_n(o.negate(),u)),t.z),i(l.add(_n(o.mul(2),u)),t.z),d.x),gu(i(l.add(_n(0,u.negate())),t.z),i(l.add(_n(0,u.mul(2))),t.z),d.y),gu(i(l.add(_n(o,u.negate())),t.z),i(l.add(_n(o,u.mul(2))),t.z),d.y),gu(gu(i(l.add(_n(o.negate(),u.negate())),t.z),i(l.add(_n(o.mul(2),u.negate())),t.z),d.x),gu(i(l.add(_n(o.negate(),u.mul(2))),t.z),i(l.add(_n(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)}),z_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r},s)=>{let i=Kl(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=i.x,a=eu(1e-7,i.y.mul(i.y)),o=s.renderer.reversedDepthBuffer?tu(n,t.z):tu(t.z,n),u=yn(1).toVar();return gn(o.notEqual(1),()=>{const e=t.z.sub(n);let r=a.div(a.add(e.mul(e)));r=mu(Pa(r,.3).div(.65)),u.assign(eu(o,r))}),u}),$_=e=>{let t=O_.get(e);return void 0===t&&(t=new vg,t.colorNode=Cn(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=re,t.fog=!1,O_.set(e,t)),t},W_=e=>{const t=O_.get(e);void 0!==t&&(t.dispose(),O_.delete(e))},H_=new Ty,q_=[],j_=(e,t,r,s)=>{q_[0]=e,q_[1]=t;let i=H_.get(q_);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===pt)&&(s&&(Ys(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,...d),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,H_.set(q_,i)),q_[0]=null,q_[1]=null,i},X_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanVertical"),a=yn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(Fa(dd.xy,_n(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),K_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanHorizontal"),a=yn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(Fa(dd.xy,_n(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(Fa(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),Q_=[V_,k_,G_,z_];let Y_;const Z_=new gx;class J_ extends E_{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:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,yn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=r.biasNode||qc("bias","float",r).setGroup(_a);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=qc("near","float",r.camera).setGroup(_a),s=qc("far","float",r.camera).setGroup(_a);n=ig(e.negate(),t,s)}return a=Rn(a.x,a.y.oneMinus(),s.reversedDepthBuffer?n.sub(i):n.add(i)),a}getShadowFilterFn(e){return Q_[e]}setupRenderTarget(e,t){const r=new Z(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t,camera:r}=e,{light:s,shadow:i}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(i,e),o=t.shadowMap.type,u=t.hasCompatibility(A.TEXTURE_COMPARE);if(o!==ct&&o!==ht||!u?(n.minFilter=B,n.magFilter=B):(n.minFilter=le,n.magFilter=le),i.camera.coordinateSystem=r.coordinateSystem,i.camera.updateProjectionMatrix(),o===pt&&!0!==i.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}));let t=Kl(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Kl(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const s=qc("blurSamples","float",i).setGroup(_a),o=qc("radius","float",i).setGroup(_a),u=qc("mapSize","vec2",i).setGroup(_a);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new vg);l.fragmentNode=X_({samples:s,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new vg),l.fragmentNode=K_({samples:s,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=qc("intensity","float",i).setGroup(_a),d=qc("normalBias","float",i).setGroup(_a),c=y_(s),h=Rc.mul(d);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(w_.add(h));else{p=Sa("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(lc).add(c.mul(Cn(h,0)))}const g=this.setupShadowCoord(e,p),m=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=o===pt&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:f,shadowCoord:g,shadow:i,depthLayer:this.depthLayer});let b,x;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=$c(a.texture,g.xyz):(b=Kl(a.texture,g),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),x=b?gu(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():gu(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const T=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&x.toInspector(`${T} / Color`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture):Kl(this.shadowMap.texture)),x.toInspector(`${T} / Depth`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture).r.oneMinus():Ql(this.shadowMap.depthTexture,kl().mul(zl(Kl(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return cn(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let r=this._node;return this.setupShadowPosition(e),null===r&&(this._node=r=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(r=e.material.receivedShadowNode(r)),r})()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth);const a=n.name;n.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,i.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");Y_=U_(i,n,Y_),n.overrideMaterial=$_(r),i.setRenderObjectFunction(j_(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===pt&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,D_(i,n,Y_)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),Z_.material=this.vsmMaterialVertical,Z_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Z_.material=this.vsmMaterialHorizontal,Z_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,W_(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const ev=(e,t)=>new J_(e,t),tv=new e,rv=new a,sv=new r,iv=new r,nv=[new r(1,0,0),new r(-1,0,0),new r(0,-1,0),new r(0,1,0),new r(0,0,1),new r(0,0,-1)],av=[new r(0,-1,0),new r(0,-1,0),new r(0,0,-1),new r(0,0,1),new r(0,-1,0),new r(0,-1,0)],ov=[new r(1,0,0),new r(-1,0,0),new r(0,1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1)],uv=[new r(0,-1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1),new r(0,-1,0),new r(0,-1,0)],lv=cn(({depthTexture:e,bd3D:t,dp:r})=>$c(e,t).compare(r)),dv=cn(({depthTexture:e,bd3D:t,dp:r,shadow:s})=>{const i=qc("radius","float",s).setGroup(_a),n=qc("mapSize","vec2",s).setGroup(_a),a=i.div(n.x),o=Vo(t),u=Ro(au(t,o.x.greaterThan(o.z).select(Rn(0,1,0),Rn(1,0,0)))),l=au(t,u),d=_x(dd.xy).mul(6.28318530718),c=vx(0,5,d),h=vx(1,5,d),p=vx(2,5,d),g=vx(3,5,d),m=vx(4,5,d);return $c(e,t.add(u.mul(c.x).add(l.mul(c.y)).mul(a))).compare(r).add($c(e,t.add(u.mul(h.x).add(l.mul(h.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(p.x).add(l.mul(p.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(g.x).add(l.mul(g.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(m.x).add(l.mul(m.y)).mul(a))).compare(r)).mul(.2)}),cv=cn(({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s},i)=>{const n=r.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),u=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.near),l=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.far),d=qc("bias","float",s).setGroup(_a),c=yn(1).toVar();return gn(o.sub(l).lessThanEqual(0).and(o.sub(u).greaterThanEqual(0)),()=>{let r;i.renderer.reversedDepthBuffer?(r=rg(o.negate(),u,l),r.subAssign(d)):(r=tg(o.negate(),u,l),r.addAssign(d));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:r,shadow:s}))}),c});class hv extends J_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===gt?lv:dv}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i}){return cv({filterFn:t,depthTexture:r,shadowCoord:s,shadow:i})}setupRenderTarget(e,t){const r=new mt(e.mapSize.width);r.name="PointShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createCubeRenderTarget(e.mapSize.width);return s.texture.name="PointShadowMap",s.depthTexture=r,{shadowMap:s,depthTexture:r}}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.camera,o=t.matrix,u=i.coordinateSystem===h,l=u?nv:ov,d=u?av:uv;r.setSize(t.mapSize.width,t.mapSize.width);const c=i.autoClear,p=i.getClearColor(tv),g=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(r,e),i.clear();const u=s.distance||a.far;u!==a.far&&(a.far=u,a.updateProjectionMatrix()),sv.setFromMatrixPosition(s.matrixWorld),a.position.copy(sv),iv.copy(a.position),iv.add(l[e]),a.up.copy(d[e]),a.lookAt(iv),a.updateMatrixWorld(),o.makeTranslation(-sv.x,-sv.y,-sv.z),rv.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(rv,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${e+1}`,i.render(n,a),n.name=c}i.autoClear=c,i.setClearColor(p,g)}}const pv=(e,t)=>new hv(e,t);class gv extends Op{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Sa(this.color).setGroup(_a),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ri.FRAME,t&&t.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},t.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 __(this.light).sub(e.context.positionView||pc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return ev(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?tn(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(r=e.context.getShadow(this,e)),this.colorNode=r}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),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const mv=cn(({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)}),fv=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=mv({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class yv extends gv{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(2).setGroup(_a)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return pv(this.light)}setupDirect(e){return fv({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const bv=cn(([e=kl()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()}),xv=cn(([e=kl()],{renderer:t,material:r})=>{const s=pu(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.currentSamples>0){const e=yn(s.fwidth()).toVar();i=bu(e.oneMinus(),e.add(1),s).oneMinus()}else i=Eu(s.greaterThan(1),0,1);return i}),Tv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=Tn(e).toVar();return Eu(n,i,s)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),_v=cn(([e,t])=>{const r=Tn(t).toVar(),s=yn(e).toVar();return Eu(r,s.negate(),s)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),vv=cn(([e])=>{const t=yn(e).toVar();return bn(No(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Nv=cn(([e,t])=>{const r=yn(e).toVar();return t.assign(vv(r)),r.sub(yn(t))}),Sv=Vb([cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=yn(s).toVar(),l=yn(r).toVar(),d=yn(t).toVar(),c=yn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=Rn(s).toVar(),l=Rn(r).toVar(),d=Rn(t).toVar(),c=Rn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),Rv=Vb([cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=yn(o).toVar(),m=yn(a).toVar(),f=yn(n).toVar(),y=yn(i).toVar(),b=yn(s).toVar(),x=yn(r).toVar(),T=yn(t).toVar(),_=yn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=Rn(o).toVar(),m=Rn(a).toVar(),f=Rn(n).toVar(),y=Rn(i).toVar(),b=Rn(s).toVar(),x=Rn(r).toVar(),T=Rn(t).toVar(),_=Rn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),Av=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=xn(e).toVar(),a=xn(n.bitAnd(xn(7))).toVar(),o=yn(Tv(a.lessThan(xn(4)),i,s)).toVar(),u=yn(Ua(2,Tv(a.lessThan(xn(4)),s,i))).toVar();return _v(o,Tn(a.bitAnd(xn(1)))).add(_v(u,Tn(a.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Ev=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=xn(e).toVar(),u=xn(o.bitAnd(xn(15))).toVar(),l=yn(Tv(u.lessThan(xn(8)),a,n)).toVar(),d=yn(Tv(u.lessThan(xn(4)),n,Tv(u.equal(xn(12)).or(u.equal(xn(14))),a,i))).toVar();return _v(l,Tn(u.bitAnd(xn(1)))).add(_v(d,Tn(u.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),wv=Vb([Av,Ev]),Cv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=En(e).toVar();return Rn(wv(n.x,i,s),wv(n.y,i,s),wv(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Mv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=En(e).toVar();return Rn(wv(o.x,a,n,i),wv(o.y,a,n,i),wv(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),Bv=Vb([Cv,Mv]),Lv=cn(([e])=>{const t=yn(e).toVar();return Ua(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Fv=cn(([e])=>{const t=yn(e).toVar();return Ua(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Pv=Vb([Lv,cn(([e])=>{const t=Rn(e).toVar();return Ua(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Uv=Vb([Fv,cn(([e])=>{const t=Rn(e).toVar();return Ua(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Dv=cn(([e,t])=>{const r=bn(t).toVar(),s=xn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(bn(32).sub(r)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),Iv=cn(([e,t,r])=>{e.subAssign(r),e.bitXorAssign(Dv(r,bn(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Dv(e,bn(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Dv(t,bn(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(Dv(r,bn(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Dv(e,bn(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Dv(t,bn(4))),t.addAssign(e)}),Ov=cn(([e,t,r])=>{const s=xn(r).toVar(),i=xn(t).toVar(),n=xn(e).toVar();return s.bitXorAssign(i),s.subAssign(Dv(i,bn(14))),n.bitXorAssign(s),n.subAssign(Dv(s,bn(11))),i.bitXorAssign(n),i.subAssign(Dv(n,bn(25))),s.bitXorAssign(i),s.subAssign(Dv(i,bn(16))),n.bitXorAssign(s),n.subAssign(Dv(s,bn(4))),i.bitXorAssign(n),i.subAssign(Dv(n,bn(14))),s.bitXorAssign(i),s.subAssign(Dv(i,bn(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Vv=cn(([e])=>{const t=xn(e).toVar();return yn(t).div(yn(xn(bn(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),kv=cn(([e])=>{const t=yn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),Gv=Vb([cn(([e])=>{const t=bn(e).toVar(),r=xn(xn(1)).toVar(),s=xn(xn(bn(3735928559)).add(r.shiftLeft(xn(2))).add(xn(13))).toVar();return Ov(s.add(xn(t)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(xn(2)).toVar(),n=xn().toVar(),a=xn().toVar(),o=xn().toVar();return n.assign(a.assign(o.assign(xn(bn(3735928559)).add(i.shiftLeft(xn(2))).add(xn(13))))),n.addAssign(xn(s)),a.addAssign(xn(r)),Ov(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(xn(3)).toVar(),o=xn().toVar(),u=xn().toVar(),l=xn().toVar();return o.assign(u.assign(l.assign(xn(bn(3735928559)).add(a.shiftLeft(xn(2))).add(xn(13))))),o.addAssign(xn(n)),u.addAssign(xn(i)),l.addAssign(xn(s)),Ov(o,u,l)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),cn(([e,t,r,s])=>{const i=bn(s).toVar(),n=bn(r).toVar(),a=bn(t).toVar(),o=bn(e).toVar(),u=xn(xn(4)).toVar(),l=xn().toVar(),d=xn().toVar(),c=xn().toVar();return l.assign(d.assign(c.assign(xn(bn(3735928559)).add(u.shiftLeft(xn(2))).add(xn(13))))),l.addAssign(xn(o)),d.addAssign(xn(a)),c.addAssign(xn(n)),Iv(l,d,c),l.addAssign(xn(i)),Ov(l,d,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),cn(([e,t,r,s,i])=>{const n=bn(i).toVar(),a=bn(s).toVar(),o=bn(r).toVar(),u=bn(t).toVar(),l=bn(e).toVar(),d=xn(xn(5)).toVar(),c=xn().toVar(),h=xn().toVar(),p=xn().toVar();return c.assign(h.assign(p.assign(xn(bn(3735928559)).add(d.shiftLeft(xn(2))).add(xn(13))))),c.addAssign(xn(l)),h.addAssign(xn(u)),p.addAssign(xn(o)),Iv(c,h,p),c.addAssign(xn(a)),h.addAssign(xn(n)),Ov(c,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),zv=Vb([cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(Gv(s,r)).toVar(),n=En().toVar();return n.x.assign(i.bitAnd(bn(255))),n.y.assign(i.shiftRight(bn(8)).bitAnd(bn(255))),n.z.assign(i.shiftRight(bn(16)).bitAnd(bn(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(Gv(n,i,s)).toVar(),o=En().toVar();return o.x.assign(a.bitAnd(bn(255))),o.y.assign(a.shiftRight(bn(8)).bitAnd(bn(255))),o.z.assign(a.shiftRight(bn(16)).bitAnd(bn(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),$v=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=yn(Sv(wv(Gv(r,s),i,n),wv(Gv(r.add(bn(1)),s),i.sub(1),n),wv(Gv(r,s.add(bn(1))),i,n.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=yn(Rv(wv(Gv(r,s,i),n,a,o),wv(Gv(r.add(bn(1)),s,i),n.sub(1),a,o),wv(Gv(r,s.add(bn(1)),i),n,a.sub(1),o),wv(Gv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),wv(Gv(r,s,i.add(bn(1))),n,a,o.sub(1)),wv(Gv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),wv(Gv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Uv(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),Wv=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=Rn(Sv(Bv(zv(r,s),i,n),Bv(zv(r.add(bn(1)),s),i.sub(1),n),Bv(zv(r,s.add(bn(1))),i,n.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=Rn(Rv(Bv(zv(r,s,i),n,a,o),Bv(zv(r.add(bn(1)),s,i),n.sub(1),a,o),Bv(zv(r,s.add(bn(1)),i),n,a.sub(1),o),Bv(zv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),Bv(zv(r,s,i.add(bn(1))),n,a,o.sub(1)),Bv(zv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),Bv(zv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Uv(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),Hv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Vv(Gv(r))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Vv(Gv(r,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Vv(Gv(r,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Vv(Gv(r,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),qv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Rn(Vv(Gv(r,bn(0))),Vv(Gv(r,bn(1))),Vv(Gv(r,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Rn(Vv(Gv(r,s,bn(0))),Vv(Gv(r,s,bn(1))),Vv(Gv(r,s,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Rn(Vv(Gv(r,s,i,bn(0))),Vv(Gv(r,s,i,bn(1))),Vv(Gv(r,s,i,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Rn(Vv(Gv(r,s,i,n,bn(0))),Vv(Gv(r,s,i,n,bn(1))),Vv(Gv(r,s,i,n,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),jv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=yn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul($v(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Xv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul(Wv(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Kv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar();return _n(jv(o,a,n,i),jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Qv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(Xv(o,a,n,i)).toVar(),l=yn(jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i)).toVar();return Cn(u,l)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Yv=Vb([cn(([e,t,r,s,i,n,a])=>{const o=bn(a).toVar(),u=yn(n).toVar(),l=bn(i).toVar(),d=bn(s).toVar(),c=bn(r).toVar(),h=bn(t).toVar(),p=_n(e).toVar(),g=Rn(qv(_n(h.add(d),c.add(l)))).toVar(),m=_n(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=_n(_n(yn(h),yn(c)).add(m)).toVar(),y=_n(f.sub(p)).toVar();return gn(o.equal(bn(2)),()=>Vo(y.x).add(Vo(y.y))),gn(o.equal(bn(3)),()=>eu(Vo(y.x),Vo(y.y))),nu(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),cn(([e,t,r,s,i,n,a,o,u])=>{const l=bn(u).toVar(),d=yn(o).toVar(),c=bn(a).toVar(),h=bn(n).toVar(),p=bn(i).toVar(),g=bn(s).toVar(),m=bn(r).toVar(),f=bn(t).toVar(),y=Rn(e).toVar(),b=Rn(qv(Rn(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=Rn(Rn(yn(f),yn(m),yn(g)).add(b)).toVar(),T=Rn(x.sub(y)).toVar();return gn(l.equal(bn(2)),()=>Vo(T.x).add(Vo(T.y)).add(Vo(T.z))),gn(l.equal(bn(3)),()=>eu(Vo(T.x),Vo(T.y),Vo(T.z))),nu(T,T)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),Zv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();l.assign(Jo(l,r))})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Jv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.y.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),eN=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(r)}).ElseIf(r.lessThan(l.z),()=>{l.z.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),tN=Vb([Zv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();d.assign(Jo(d,n))})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),rN=Vb([Jv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.y.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),sN=Vb([eN,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.z.assign(d.y),d.y.assign(n)}).ElseIf(n.lessThan(d.z),()=>{d.z.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),iN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=_n(t).toVar(),p=_n(r).toVar(),g=_n(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(Rn(v,0),x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),nN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=Rn(t).toVar(),p=Rn(r).toVar(),g=Rn(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(v,x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),aN=cn(([e])=>{const t=e.y,r=e.z,s=Rn().toVar();return gn(t.lessThan(1e-4),()=>{s.assign(Rn(r,r,r))}).Else(()=>{let i=e.x;i=i.sub(No(i)).mul(6).toVar();const n=bn(Xo(i)),a=i.sub(yn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());gn(n.equal(bn(0)),()=>{s.assign(Rn(r,l,o))}).ElseIf(n.equal(bn(1)),()=>{s.assign(Rn(u,r,o))}).ElseIf(n.equal(bn(2)),()=>{s.assign(Rn(o,r,l))}).ElseIf(n.equal(bn(3)),()=>{s.assign(Rn(o,u,r))}).ElseIf(n.equal(bn(4)),()=>{s.assign(Rn(l,o,r))}).Else(()=>{s.assign(Rn(r,o,u))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),oN=cn(([e])=>{const t=Rn(e).toVar(),r=yn(t.x).toVar(),s=yn(t.y).toVar(),i=yn(t.z).toVar(),n=yn(Jo(r,Jo(s,i))).toVar(),a=yn(eu(r,eu(s,i))).toVar(),o=yn(a.sub(n)).toVar(),u=yn().toVar(),l=yn().toVar(),d=yn().toVar();return d.assign(a),gn(a.greaterThan(0),()=>{l.assign(o.div(a))}).Else(()=>{l.assign(0)}),gn(l.lessThanEqual(0),()=>{u.assign(0)}).Else(()=>{gn(r.greaterThanEqual(a),()=>{u.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{u.assign(Fa(2,i.sub(r).div(o)))}).Else(()=>{u.assign(Fa(4,r.sub(s).div(o)))}),u.mulAssign(1/6),gn(u.lessThan(0),()=>{u.addAssign(1)})}),Rn(u,l,d)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),uN=cn(([e])=>{const t=Rn(e).toVar(),r=wn(Ga(t,Rn(.04045))).toVar(),s=Rn(t.div(12.92)).toVar(),i=Rn(ou(eu(t.add(Rn(.055)),Rn(0)).div(1.055),Rn(2.4))).toVar();return gu(s,i,r)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lN=(e,t)=>{e=yn(e),t=yn(t);const r=_n(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return bu(e.sub(r),e.add(r),t)},dN=(e,t,r,s)=>gu(e,t,r[s].clamp()),cN=(e,t,r,s,i)=>gu(e,t,lN(r,s[i])),hN=cn(([e,t,r])=>{const s=Ro(e).toVar(),i=Pa(yn(.5).mul(t.sub(r)),cc).div(s).toVar(),n=Pa(yn(-.5).mul(t.sub(r)),cc).div(s).toVar(),a=Rn().toVar();a.x=s.x.greaterThan(yn(0)).select(i.x,n.x),a.y=s.y.greaterThan(yn(0)).select(i.y,n.y),a.z=s.z.greaterThan(yn(0)).select(i.z,n.z);const o=Jo(a.x,a.y,a.z).toVar();return cc.add(s.mul(o)).toVar().sub(r)}),pN=cn(([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(Ua(r,r).sub(Ua(s,s)))),n});var gN=Object.freeze({__proto__:null,BRDF_GGX:am,BRDF_Lambert:Hg,BasicPointShadowFilter:lv,BasicShadowFilter:V_,Break:Lp,Const:Ou,Continue:()=>Cl("continue").toStack(),DFGLUT:lm,D_GGX:sm,Discard:Ml,EPSILON:ao,F_Schlick:Wg,Fn:cn,HALF_PI:ho,INFINITY:oo,If:gn,Loop:Bp,NodeAccess:ii,NodeShaderStage:ti,NodeType:si,NodeUpdateType:ri,OnBeforeFrameUpdate:e=>Rx(Sx.BEFORE_FRAME,e),OnBeforeMaterialUpdate:e=>Rx(Sx.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>Rx(Sx.BEFORE_OBJECT,e),OnFrameUpdate:e=>Rx(Sx.FRAME,e),OnMaterialUpdate:e=>Rx(Sx.MATERIAL,e),OnObjectUpdate:e=>Rx(Sx.OBJECT,e),PCFShadowFilter:k_,PCFSoftShadowFilter:G_,PI:uo,PI2:lo,PointShadowFilter:dv,Return:()=>Cl("return").toStack(),Schlick_to_F0:hm,ShaderNode:en,Stack:mn,Switch:(...e)=>Si.Switch(...e),TBNViewMatrix:xh,TWO_PI:co,VSMShadowFilter:z_,V_GGX_SmithCorrelated:tm,Var:Iu,VarIntent:Vu,abs:Vo,acesFilmicToneMapping:dT,acos:Uo,acosh:Do,add:Fa,addMethodChaining:Ai,addNodeElement:function(e){d("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:gT,all:po,alphaT:Jn,and:Wa,anisotropy:ea,anisotropyB:ra,anisotropyT:ta,any:go,append:e=>(d("TSL: append() has been renamed to Stack().",new Is),mn(e)),array:Aa,arrayBuffer:e=>new vi(e,"ArrayBuffer"),asin:Fo,asinh:Po,assign:wa,atan:Io,atanh:Oo,atomicAdd:(e,t)=>zT(kT.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>zT(kT.ATOMIC_AND,e,t),atomicFunc:zT,atomicLoad:e=>zT(kT.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>zT(kT.ATOMIC_MAX,e,t),atomicMin:(e,t)=>zT(kT.ATOMIC_MIN,e,t),atomicOr:(e,t)=>zT(kT.ATOMIC_OR,e,t),atomicStore:(e,t)=>zT(kT.ATOMIC_STORE,e,t),atomicSub:(e,t)=>zT(kT.ATOMIC_SUB,e,t),atomicXor:(e,t)=>zT(kT.ATOMIC_XOR,e,t),attenuationColor:ma,attenuationDistance:ga,attribute:Vl,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ex(e,r,s);return Tp(i,t,e)},backgroundBlurriness:Bx,backgroundIntensity:Lx,backgroundRotation:Fx,batch:Ap,bentNormalView:_h,billboarding:Hb,bitAnd:Xa,bitNot:Ka,bitOr:Qa,bitXor:Ya,bitangentGeometry:mh,bitangentLocal:fh,bitangentView:yh,bitangentWorld:bh,bitcast:yb,blendBurn:mg,blendColor:xg,blendDodge:fg,blendOverlay:bg,blendScreen:yg,blur:pf,bool:Tn,buffer:Zl,bufferAttribute:ul,builtin:sd,builtinAOContext:Fu,builtinShadowContext:Lu,bumpMap:Ch,bvec2:Sn,bvec3:wn,bvec4:Ln,bypass:Rl,cache:Nl,call:Ma,cameraFar:Ld,cameraIndex:Md,cameraNear:Bd,cameraNormalMatrix:Id,cameraPosition:Od,cameraProjectionMatrix:Fd,cameraProjectionMatrixInverse:Pd,cameraViewMatrix:Ud,cameraViewport:Vd,cameraWorldMatrix:Dd,cbrt:hu,cdl:Qx,ceil:So,checker:bv,cineonToneMapping:uT,clamp:mu,clearcoat:qn,clearcoatNormalView:Ac,clearcoatRoughness:jn,clipSpace:oc,code:yT,color:fn,colorSpaceToWorking:Qu,colorToDirection:e=>tn(e).mul(2).sub(1),compute:Tl,computeKernel:xl,computeSkinning:(e,t=null)=>{const r=new wp(e);return r.positionNode=Tp(new q(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinIndexNode=Tp(new q(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinWeightNode=Tp(new q(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.bindMatrixNode=Sa(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Sa(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=Zl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,tn(r)},context:Cu,convert:In,convertColorSpace:(e,t,r)=>new Xu(tn(e),t,r),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():yx(e,...t),cos:Co,cosh:Mo,countLeadingZeros:vb,countOneBits:Nb,countTrailingZeros:_b,cross:au,cubeTexture:$c,cubeTextureBase:zc,dFdx:Wo,dFdy:Ho,dashSize:ua,debug:Pl,decrement:so,decrementBefore:to,defaultBuildStages:ai,defaultShaderStages:ni,defined:Zi,degrees:fo,deltaTime:Gb,densityFogFactor:vT,depth:ag,depthPass:(e,t,r)=>new iT(iT.DEPTH,e,t,r),determinant:Yo,difference:iu,diffuseColor:Gn,diffuseContribution:zn,directPointLight:fv,directionToColor:vh,directionToFaceDirection:bc,dispersion:fa,disposeShadowMaterial:W_,distance:su,div:Da,dot:nu,drawIndex:yl,dynamicBufferAttribute:(e,t=null,r=0,s=0)=>ol(e,t,r,s,x),element:Dn,emissive:$n,equal:Oa,equirectUV:Bg,exp:yo,exp2:bo,exponentialHeightFogFactor:NT,expression:Cl,faceDirection:yc,faceForward:xu,faceforward:Su,float:yn,floatBitsToInt:e=>new fb(e,"int","float"),floatBitsToUint:bb,floor:No,fog:ST,fract:Ao,frameGroup:Ta,frameId:zb,frontFacing:fc,fwidth:Ko,gain:(e,t)=>e.lessThan(.5)?Rb(e.mul(2),t).div(2):Pa(1,Rb(Ua(Pa(1,e),2),t).div(2)),gapSize:la,getConstNodeType:Ji,getCurrentStack:pn,getDirection:lf,getDistanceAttenuation:mv,getGeometryRoughness:Jg,getNormalFromDepth:Tx,getParallaxCorrectNormal:hN,getRoughness:em,getScreenPosition:xx,getShIrradianceAt:pN,getShadowMaterial:$_,getShadowRenderObjectFunction:j_,getTextureIndex:pb,getViewPosition:bx,ggxConvolution:yf,globalId:FT,glsl:(e,t)=>yT(e,t,"glsl"),glslFn:(e,t)=>xT(e,t,"glsl"),grayscale:Hx,greaterThan:Ga,greaterThanEqual:$a,hash:Sb,highpModelNormalViewMatrix:ac,highpModelViewMatrix:nc,hue:Xx,increment:ro,incrementBefore:eo,inspector:Il,instance:vp,instanceIndex:pl,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ax(e,r,s);return Tp(i,t,i.count)},instancedBufferAttribute:ll,instancedDynamicBufferAttribute:dl,instancedMesh:Sp,int:bn,intBitsToFloat:e=>new fb(e,"float","int"),interleavedGradientNoise:_x,inverse:Zo,inverseSqrt:vo,inversesqrt:Ru,invocationLocalIndex:fl,invocationSubgroupIndex:ml,ior:ca,iridescence:Qn,iridescenceIOR:Yn,iridescenceThickness:Zn,isolate:vl,ivec2:vn,ivec3:An,ivec4:Mn,js:(e,t)=>yT(e,t,"js"),label:Pu,length:Go,lengthSq:pu,lessThan:ka,lessThanEqual:za,lightPosition:x_,lightProjectionUV:b_,lightShadowMatrix:y_,lightTargetDirection:v_,lightTargetPosition:T_,lightViewPosition:__,lightingContext:Gp,lights:(e=[])=>(new A_).setLights(e),linearDepth:og,linearToneMapping:aT,localId:PT,log:xo,log2:To,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(xo(r.div(t)));return yn(Math.E).pow(s).mul(t).negate()},luminance:Kx,mat2:Fn,mat3:Pn,mat4:Un,matcapUV:ey,materialAO:gp,materialAlphaTest:Lh,materialAnisotropy:Yh,materialAnisotropyVector:mp,materialAttenuationColor:np,materialAttenuationDistance:ip,materialClearcoat:Hh,materialClearcoatNormal:jh,materialClearcoatRoughness:qh,materialColor:Fh,materialDispersion:hp,materialEmissive:Uh,materialEnvIntensity:Pc,materialEnvRotation:Uc,materialIOR:sp,materialIridescence:Zh,materialIridescenceIOR:Jh,materialIridescenceThickness:ep,materialLightMap:pp,materialLineDashOffset:dp,materialLineDashSize:op,materialLineGapSize:up,materialLineScale:ap,materialLineWidth:lp,materialMetalness:$h,materialNormal:Wh,materialOpacity:Dh,materialPointSize:cp,materialReference:Kc,materialReflectivity:Gh,materialRefractionRatio:Fc,materialRotation:Xh,materialRoughness:zh,materialSheen:Kh,materialSheenRoughness:Qh,materialShininess:Ph,materialSpecular:Ih,materialSpecularColor:Vh,materialSpecularIntensity:Oh,materialSpecularStrength:kh,materialThickness:rp,materialTransmission:tp,max:eu,maxMipLevel:Wl,mediumpModelViewMatrix:ic,metalness:Hn,min:Jo,mix:gu,mixElement:_u,mod:Ia,modInt:io,modelDirection:Kd,modelNormalMatrix:tc,modelPosition:Yd,modelRadius:ec,modelScale:Zd,modelViewMatrix:sc,modelViewPosition:Jd,modelViewProjection:fp,modelWorldMatrix:Qd,modelWorldMatrixInverse:rc,morphReference:Ip,mrt:mb,mul:Ua,mx_aastep:lN,mx_add:(e,t=yn(0))=>Fa(e,t),mx_atan2:(e=yn(0),t=yn(1))=>Io(e,t),mx_cell_noise_float:(e=kl())=>Hv(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>yn(e).sub(r).mul(t).add(r),mx_divide:(e,t=yn(1))=>Da(e,t),mx_fractal_noise_float:(e=kl(),t=3,r=2,s=.5,i=1)=>jv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec2:(e=kl(),t=3,r=2,s=.5,i=1)=>Kv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec3:(e=kl(),t=3,r=2,s=.5,i=1)=>Xv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec4:(e=kl(),t=3,r=2,s=.5,i=1)=>Qv(e,bn(t),r,s).mul(i),mx_frame:()=>zb,mx_heighttonormal:(e,t)=>(e=Rn(e),t=yn(t),Ch(e,t)),mx_hsvtorgb:aN,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=yn(1))=>Pa(t,e),mx_modulo:(e,t=yn(1))=>Ia(e,t),mx_multiply:(e,t=yn(1))=>Ua(e,t),mx_noise_float:(e=kl(),t=1,r=0)=>$v(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=kl(),t=1,r=0)=>Wv(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=kl(),t=1,r=0)=>{e=e.convert("vec2|vec3");return Cn(Wv(e),$v(e.add(_n(19,73)))).mul(t).add(r)},mx_place2d:(e,t=_n(.5,.5),r=_n(1,1),s=yn(0),i=_n(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=_n(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=yn(1))=>ou(e,t),mx_ramp4:(e,t,r,s,i=kl())=>{const n=i.x.clamp(),a=i.y.clamp(),o=gu(e,t,n),u=gu(r,s,n);return gu(o,u,a)},mx_ramplr:(e,t,r=kl())=>dN(e,t,r,"x"),mx_ramptb:(e,t,r=kl())=>dN(e,t,r,"y"),mx_rgbtohsv:oN,mx_rotate2d:(e,t)=>{e=_n(e);const r=(t=yn(t)).mul(Math.PI/180);return iy(e,r)},mx_rotate3d:(e,t,r)=>{e=Rn(e),t=yn(t),r=Rn(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=yn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=yn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=kl())=>cN(e,t,r,s,"x"),mx_splittb:(e,t,r,s=kl())=>cN(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:uN,mx_subtract:(e,t=yn(0))=>Pa(e,t),mx_timer:()=>kb,mx_transform_uv:(e=1,t=0,r=kl())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>iN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>nN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=kl(),t=1)=>tN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec2:(e=kl(),t=1)=>rN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec3:(e=kl(),t=1)=>sN(e.convert("vec2|vec3"),t,bn(1)),negate:zo,neutralToneMapping:mT,nodeArray:nn,nodeImmutable:on,nodeObject:tn,nodeObjectIntent:rn,nodeObjects:sn,nodeProxy:an,nodeProxyIntent:un,normalFlat:_c,normalGeometry:xc,normalLocal:Tc,normalMap:Rh,normalView:Sc,normalViewGeometry:vc,normalWorld:Rc,normalWorldGeometry:Nc,normalize:Ro,not:qa,notEqual:Va,numWorkgroups:BT,objectDirection:zd,objectGroup:va,objectPosition:Wd,objectRadius:jd,objectScale:Hd,objectViewPosition:qd,objectWorldMatrix:$d,oneMinus:$o,or:Ha,orthographicDepthToViewZ:eg,oscSawtooth:(e=kb)=>e.fract(),oscSine:(e=kb)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=kb)=>e.fract().round(),oscTriangle:(e=kb)=>e.add(.5).fract().mul(2).sub(1).abs(),output:oa,outputStruct:lb,overloadingFn:Vb,packHalf2x16:Cb,packSnorm2x16:Eb,packUnorm2x16:wb,parabola:Rb,parallaxDirection:Th,parallaxUV:(e,t)=>e.sub(Th.mul(t)),parameter:(e,t)=>new sb(e,t),pass:(e,t,r)=>new iT(iT.COLOR,e,t,r),passTexture:(e,t)=>new rT(e,t),pcurve:(e,t,r)=>ou(Da(ou(e,t),Fa(ou(e,t),ou(Pa(1,e),r))),1/t),perspectiveDepthToViewZ:sg,pmremTexture:Vf,pointShadow:pv,pointUV:Cx,pointWidth:da,positionGeometry:uc,positionLocal:lc,positionPrevious:dc,positionView:pc,positionViewDirection:gc,positionWorld:cc,positionWorldDirection:hc,posterize:Yx,pow:ou,pow2:uu,pow3:lu,pow4:du,premultiplyAlpha:Tg,property:Vn,quadBroadcast:g_,quadSwapDiagonal:u_,quadSwapX:a_,quadSwapY:o_,radians:mo,rand:Tu,range:wT,rangeFogFactor:_T,reciprocal:jo,reference:qc,referenceBuffer:jc,reflect:ru,reflectVector:Oc,reflectView:Dc,reflector:e=>new lx(e),refract:yu,refractVector:Vc,refractView:Ic,reinhardToneMapping:oT,remap:Al,remapClamp:El,renderGroup:_a,renderOutput:Ll,rendererReference:el,replaceDefaultUV:function(e,t=null){return Cu(t,{getUV:"function"==typeof e?e:()=>e})},rotate:iy,rotateUV:$b,roughness:Wn,round:qo,rtt:yx,sRGBTransferEOTF:Hu,sRGBTransferOETF:qu,sample:(e,t=null)=>new Nx(e,tn(t)),sampler:e=>(!0===e.isNode?e:Kl(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Kl(e)).convert("samplerComparison"),saturate:fu,saturation:qx,screenCoordinate:dd,screenDPR:od,screenSize:ld,screenUV:ud,select:Eu,setCurrentStack:hn,setName:Bu,shaderStages:oi,shadow:ev,shadowPositionWorld:w_,shapeCircle:xv,sharedUniformGroup:xa,sheen:Xn,sheenRoughness:Kn,shiftLeft:Za,shiftRight:Ja,shininess:aa,sign:ko,sin:Eo,sinc:(e,t)=>Eo(uo.mul(t.mul(e).sub(1))).div(uo.mul(t.mul(e).sub(1))),sinh:wo,skinning:Cp,smoothstep:bu,smoothstepElement:vu,specularColor:sa,specularColorBlended:ia,specularF90:na,spherizeUV:Wb,split:(e,t)=>new yi(tn(e),t),spritesheetUV:jb,sqrt:_o,stack:nb,step:tu,stepElement:Nu,storage:Tp,storageBarrier:()=>IT("storage").toStack(),storageTexture:Ux,string:(e="")=>new vi(e,"string"),struct:(e,t=null)=>{const r=new ab(e,t),s=(...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;eOx(e,t).level(r),texture3DLoad:(...e)=>Ox(...e).setSampler(!1),textureBarrier:()=>IT("texture").toStack(),textureBicubic:Lm,textureBicubicLevel:Bm,textureCubeUV:df,textureLevel:(e,t,r)=>Kl(e,t).level(r),textureLoad:Ql,textureSize:zl,textureStore:(e,t,r)=>{let s;return!0===e.isStorageTextureNode?(s=e.clone(),s.uvNode=t,s.storeNode=r):s=Ux(e,t,r),null!==r&&s.toStack(),s},thickness:pa,time:kb,toneMapping:rl,toneMappingExposure:sl,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>new nT(t,r,tn(s),tn(i),tn(n)),transformDirection:cu,transformNormal:Ec,transformNormalToView:wc,transformedClearcoatNormalView:Bc,transformedNormalView:Cc,transformedNormalWorld:Mc,transmission:ha,transpose:Qo,triNoise3D:Db,triplanarTexture:(...e)=>Xb(...e),triplanarTextures:Xb,trunc:Xo,uint:xn,uintBitsToFloat:e=>new fb(e,"float","uint"),uniform:Sa,uniformArray:td,uniformCubeTexture:(e=kc)=>zc(e),uniformFlow:Mu,uniformGroup:ba,uniformTexture:(e=ql)=>Kl(e),unpackHalf2x16:Fb,unpackNormal:Nh,unpackSnorm2x16:Bb,unpackUnorm2x16:Lb,unpremultiplyAlpha:_g,userData:(e,t,r)=>new Vx(e,t,r),uv:kl,uvec2:Nn,uvec3:En,uvec4:Bn,varying:$u,varyingProperty:kn,vec2:_n,vec3:Rn,vec4:Cn,vectorComponents:ui,velocity:Wx,vertexColor:gg,vertexIndex:hl,vertexStage:Wu,vibrance:jx,viewZToLogarithmicDepth:ig,viewZToOrthographicDepth:Jp,viewZToPerspectiveDepth:tg,viewZToReversedOrthographicDepth:(e,t,r)=>e.add(r).div(r.sub(t)),viewZToReversedPerspectiveDepth:rg,viewport:cd,viewportCoordinate:pd,viewportDepthTexture:Yp,viewportLinearDepth:ug,viewportMipTexture:qp,viewportOpaqueMipTexture:Xp,viewportResolution:md,viewportSafeUV:qb,viewportSharedTexture:eT,viewportSize:hd,viewportTexture:Hp,viewportUV:gd,vogelDiskSample:vx,wgsl:(e,t)=>yT(e,t,"wgsl"),wgslFn:(e,t)=>xT(e,t,"wgsl"),workgroupArray:(e,t)=>new VT("Workgroup",e,t),workgroupBarrier:()=>IT("workgroup").toStack(),workgroupId:LT,workingToColorSpace:Ku,xor:ja});const mN=new rb;class fN extends Ry{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,r){const s=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)s._clearColor.getRGB(mN),mN.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(mN),mN.a=1,n=!0;else if(!0===i.isNode){const u=this.get(e),l=i;mN.copy(s._clearColor);let d=u.backgroundMesh;if(void 0===d){const h=Cn(l).mul(Lx).context({getUV:()=>Fx.mul(Nc),getTextureLevel:()=>Bx}),p=Fd.element(3).element(3).equal(1),g=Da(1,Fd.element(1).element(1)).mul(3),m=p.select(lc.mul(g),lc),f=sc.mul(Cn(m,0));let y=Fd.mul(Cn(f.xyz,1));y=y.setZ(y.w);const b=new vg;function x(){i.removeEventListener("dispose",x),d.material.dispose(),d.geometry.dispose()}b.name="Background.material",b.side=F,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=y,b.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=d=new oe(new ft(1,32,32),b),d.frustumCulled=!1,d.name="Background.mesh",i.addEventListener("dispose",x)}const c=l.getCacheKey();u.backgroundCacheKey!==c&&(u.backgroundMeshNode.node=Cn(l).mul(Lx),u.backgroundMeshNode.needsUpdate=!0,d.material.needsUpdate=!0,u.backgroundCacheKey=c),t.unshift(d,d.geometry,d.material,0,0,null,null)}else o("Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?mN.set(0,0,0,1):"alpha-blend"===a&&mN.set(0,0,0,0),!0===s.autoClear||!0===n){const T=r.clearColorValue;T.r=mN.r,T.g=mN.g,T.b=mN.b,T.a=mN.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(T.r*=T.a,T.g*=T.a,T.b*=T.a),r.depthClearValue=s.getClearDepth(),r.stencilClearValue=s.getClearStencil(),r.clearColor=!0===s.autoClearColor,r.clearDepth=!0===s.autoClearDepth,r.clearStencil=!0===s.autoClearStencil}else r.clearColor=!1,r.clearDepth=!1,r.clearStencil=!1}}let yN=0;class bN{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=yN++}}class xN{constructor(e,t,r,s,i,n,a,o,u,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=l,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new bN(t.name,[]);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class TN{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class _N{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}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 vN{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class NN extends vN{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class SN{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let RN=0;class AN{constructor(e=null){this.id=RN++,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 EN{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class wN{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 CN extends wN{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class MN extends wN{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class BN extends wN{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class LN extends wN{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class FN extends wN{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class PN extends wN{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class UN extends wN{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class DN extends wN{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class IN extends CN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ON extends MN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class VN extends BN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kN extends LN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GN extends FN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zN extends PN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $N extends UN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class WN extends DN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let HN=0;const qN=new WeakMap,jN=new WeakMap,XN=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),KN=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class QN{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=nb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new AN,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:HN++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&e.blending===tt&&!1===e.alphaToCoverage}createRenderTarget(e,t,r){return new ne(e,t,r)}createCubeRenderTarget(e,t){return new Lg(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=t[0].groupNode;let s,i=r.shared;if(i)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)r+=t.nodeUniform.node.id}else r+=e.nodeUniform.id;const i=this.renderer._currentRenderContext||this.renderer;let n=qN.get(i);void 0===n&&(n=new Map,qN.set(i,n));const a=Vs(r);s=n.get(a),void 0===s&&(s=new bN(e,t),n.set(a,s))}else s=new bN(e,t);return s}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of oi)for(const s in r[e]){const i=r[e][s],n=t[s]||(t[s]=[]);for(const e of i)!1===n.includes(e)&&n.push(e)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(n)}u`:"0u";if("bool"===i)return n?"true":"false";if("color"===i)return`${this.getType("vec3")}( ${KN(n.r)}, ${KN(n.g)}, ${KN(n.b)} )`;const a=this.getTypeLength(i),o=this.getComponentType(i),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==i)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(i)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(i)}()`;throw new Error(`NodeBuilder: Type '${i}' 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 r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new TN(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===R)return"int";if(t===S)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=Ws(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return XN.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof xt||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=nb(this.stack);const e=pn();return this.stacks.push(e),hn(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,hn(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const r=this.getDataFromNode(e,"vertex");let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new TN("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new EN(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new _N(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new vN(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new NN(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let i=1,n=s;for(;void 0!==r[n];)n=s+"_"+i++;i>1&&(e.name=n,d(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${n}'.`)),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new SN("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!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),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new bT,r=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=r,t}flowShaderNode(e){const t=e.layout,r={[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)r[e.name]=new sb(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new AN,this.stack=nb();for(const r of ai)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){d("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){d("Abstract function.")}getVaryings(){d("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e,t=!1){const r=[],s=this.vars[e];if(void 0!==s)for(const e of s)r.push(`${this.getVar(e.type,e.name,e.count)};`);return r.join(t?"\n":"\n\t")}getUniforms(){d("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}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(){d("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 r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}prebuild(){const{object:e,renderer:t,material:r}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:o('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),r&&r.contextNode&&(!0===r.contextNode.isContextNode?this.context={...this.context,...r.contextNode.getFlowContextData()}:o('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==r){let e=t.library.fromMaterial(r);null===e&&(o(`NodeBuilder: Material "${r.type}" is not compatible.`),e=new vg),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"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 ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this);await Tt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=jN.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const r=this.getSharedDataFromNode(e);let s=r.cache;if(void 0===s){if("float"===t||"int"===t||"uint"===t)s=new IN(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)s=new ON(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)s=new VN(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)s=new kN(e);else if("color"===t)s=new GN(e);else if("mat2"===t)s=new zN(e);else if("mat3"===t)s=new $N(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);s=new WN(e)}r.cache=s}return s}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${_t} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Ys(this.object).useVelocity}}class YN{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderId:0,frameId:0},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateBeforeMap,r);if(t.frameId!==this.frameId){const r=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=r)}}else if(t===ri.RENDER){const t=this._getMaps(this.updateBeforeMap,r);if(t.renderId!==this.renderId){const r=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=r)}}else t===ri.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateAfterMap,r);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateAfterMap,r);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateMap,r);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateMap,r);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&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 ZN{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}ZN.isNodeFunctionInput=!0;class JN extends gv{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class eS extends gv{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:v_(this.light),lightColor:e}}}class tS extends gv{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=x_(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Sa(new e).setGroup(_a)}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:r,lightDirectionNode:s}=this,i=Rc.dot(s).mul(.5).add(.5),n=gu(r,t,i);e.context.irradiance.addAssign(n)}}class rS extends gv{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Sa(0).setGroup(_a),this.penumbraCosNode=Sa(0).setGroup(_a),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(0).setGroup(_a),this.colorNode=Sa(this.color).setGroup(_a)}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:r,penumbraCosNode:s}=this;return bu(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=b_(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(v_(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=mv({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=Kl(i.map,h.xy).onRenderUpdate(()=>i.map)),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class sS extends rS{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);s=Kl(r,_n(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}class iS extends gv{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new r);this.lightProbe=td(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=pN(Rc,this.lightProbe);e.context.irradiance.addAssign(t)}}const nS=cn(([e,t])=>{const r=e.abs().sub(t);return Go(eu(r,0)).add(Jo(eu(r.x,r.y),0))});class aS extends rS{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=yn(0),r=this.penumbraCosNode,s=y_(this.light).mul(e.context.positionWorld||cc);return gn(s.w.greaterThan(0),()=>{const e=s.xyz.div(s.w),i=nS(e.xy.sub(_n(.5)),_n(.5)),n=Da(-1,Pa(1,Uo(r)).sub(1));t.assign(fu(i.mul(-2).mul(n)))}),t}}const oS=new a,uS=new a;let lS=null;class dS extends gv{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Sa(new r).setGroup(_a),this.halfWidth=Sa(new r).setGroup(_a),this.updateType=ri.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;uS.identity(),oS.copy(t.matrixWorld),oS.premultiply(r),uS.extractRotation(oS),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(uS),this.halfHeight.value.applyMatrix4(uS)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Kl(lS.LTC_FLOAT_1),r=Kl(lS.LTC_FLOAT_2)):(t=Kl(lS.LTC_HALF_1),r=Kl(lS.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:__(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){lS=e}}class cS{parseFunction(){d("Abstract function.")}}class hS{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){d("Abstract function.")}}hS.isNodeFunction=!0;const pS=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,gS=/[a-z_0-9]+/gi,mS="#pragma main";class fS extends hS{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(mS),r=-1!==t?e.slice(t+12):e,s=r.match(pS);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=gS.exec(i));)n.push(a);const o=[];let u=0;for(;u{let r=this._createNodeBuilder(e,e.material);try{t?await r.buildAsync():r.build()}catch(s){r=this._createNodeBuilder(e,new vg),t?await r.buildAsync():r.build(),o("TSL: "+s)}return r})().then(e=>(s=this._createNodeBuilderState(e),i.set(n,s),s.usedTimes++,r.nodeBuilderState=s,s));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(r){t=this._createNodeBuilder(e,new vg),t.build();let s=r.stackTrace;!s&&r.stack&&(s=new Is(r.stack)),o("TSL: "+r,s)}s=this._createNodeBuilderState(t),i.set(n,s)}}s.usedTimes++,r.nodeBuilderState=s}return s}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 r=this.getForRenderCacheKey(e),s=this.nodeBuilderCache.get(r);return void 0!==s?(s.usedTimes++,t.nodeBuilderState=s,s):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let r=t.nodeBuilderState;if(void 0===r){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),r=this._createNodeBuilderState(s),t.nodeBuilderState=r}return r}_createNodeBuilderState(e){return new xN(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const r=this.get(e);r.environmentNode&&(t=r.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const r=this.get(e);r.backgroundNode&&(t=r.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){bS[0]=e,bS[1]=t;const r=this.renderer.info.calls,s=this.callHashCache.get(bS)||{};if(s.callId!==r){const i=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&xS.push(t.getCacheKey(!0)),i&&xS.push(i.getCacheKey()),n&&xS.push(n.getCacheKey()),xS.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),xS.push(this.renderer.shadowMap.enabled?1:0),xS.push(this.renderer.shadowMap.type),s.callId=r,s.cacheKey=ks(xS),this.callHashCache.set(bS,s),xS.length=0}return bS[0]=null,bS[1]=null,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),r=e.background;if(r){const s=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,()=>{if(!0===r.isCubeTexture||r.mapping===ce||r.mapping===he||r.mapping===Ee){if(e.backgroundBlurriness>0||r.mapping===Ee)return Vf(r);{let e;return e=!0===r.isCubeTexture?$c(r):Kl(r),Ig(e)}}if(!0===r.isTexture)return Kl(r,ud.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&o("WebGPUNodes: Unsupported background configuration.",r)},s);t.backgroundNode=i,t.background=r,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(e){const t=this.get(e),r=e.fog;if(r){if(t.fog!==r){const e=this.getCacheNode("fog",r,()=>{if(r.isFogExp2){const e=qc("color","color",r).setGroup(_a),t=qc("density","float",r).setGroup(_a);return ST(e,vT(t))}if(r.isFog){const e=qc("color","color",r).setGroup(_a),t=qc("near","float",r).setGroup(_a),s=qc("far","float",r).setGroup(_a);return ST(e,_T(t,s))}o("Renderer: Unsupported fog configuration.",r)});t.fogNode=e,t.fog=r}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),r=e.environment;if(r){if(t.environment!==r){const e=this.getCacheNode("environment",r,()=>!0===r.isCubeTexture?$c(r):!0===r.isTexture?Kl(r):void o("Nodes: Unsupported environment configuration.",r));t.environmentNode=e,t.environment=r}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Kl(e,ud).depth(sd("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Kl(e,ud).renderOutput(t.toneMapping,t.currentColorSpace)}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new YN,this.nodeBuilderCache=new Map,this.cacheLib={}}}const _S=new ut;class vS{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,r){const s=e.length;for(let i=0;iLl(e,i.toneMapping,i.outputColorSpace)}),FS.set(r,n))}else n=r;i.contextNode=n,i.setRenderTarget(t.renderTarget),t.rendercall(),i.contextNode=r}i.setRenderTarget(o),i._setXRLayerSize(a.x,a.y),this.isPresenting=n}getSession(){return this._session}async setSession(e){const t=this._renderer,r=t.backend;this._gl=t.getContext();const s=this._gl,i=s.getContextAttributes();if(this._session=e,null!==e){if(!0===r.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await r.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let r=null,n=null,a=null;t.depth&&(a=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,r=t.stencil?qe:He,n=t.stencil?Ze:S);const o={colorFormat:s.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(o),l=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,c=new Z(u.textureWidth,u.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,r,d);if(this._xrRenderTarget=new MS(u.textureWidth,u.textureHeight,{format:Ae,type:Ve,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.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 fe({color:16777215,side:"cylinder"===e.type?F:St}),e.plane.material.blending=Rt,e.plane.material.blendEquation=it,e.plane.material.blendSrc=At,e.plane.material.blendDst=At,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{const r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,s,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new MS(i.framebufferWidth,i.framebufferHeight,{format:Ae,type:Ve,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=-5&i.layers.mask,a.layers.mask=-3&i.layers.mask;const o=e.parent,u=i.cameras;US(i,o);for(let e=0;e=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function VS(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 kS(e,t){if(void 0===t)return;const r=this._cameraXR,i=this._renderer,n=i.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views;null!==this._glBaseLayer&&n.setXRTarget(a.framebuffer);let t=!1;e.length!==r.cameras.length&&(r.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const s=this._renderLists.get(e,t),i=this._renderContexts.get(this._renderTarget,this._mrt),n=e.overrideMaterial||r.material,a=this._objects.get(r,n,e,t,s.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:u}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:u}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new TS(this,r),this._animation=new xy(this,this._nodes,this.info),this._attributes=new By(r,this.info),this._background=new fN(this,this._nodes),this._geometries=new Uy(this._attributes,this.info),this._textures=new tb(this,r,this.info),this._pipelines=new zy(r,this._nodes,this.info),this._bindings=new $y(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Sy(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Ky(this.lighting),this._bundles=new RS,this._renderContexts=new Jy(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,u=this._compilationPromises;null===r&&(r=e);const l=!0===e.isScene?e:!0===r.isScene?r:zS,d=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(d,this._mrt),h=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,s.renderId++,s.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new vS),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const g=this._renderLists.get(l,t);if(g.begin(),this._projectObject(e,t,0,g,c.clippingContext),r!==e&&r.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&g.pushLight(e)}),g.finish(),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;r!==e?this._background.update(r,g,c):this._background.update(l,g,c);const m=g.opaque,f=g.transparent,y=g.transparentDoublePass,b=g.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,l,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,l,b),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=u;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,this._geometries.updateForRender(t),await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const r=[];this._pipelines.getForRender(t,r),r.length>0&&await Promise.all(r),this._nodes.updateAfter(t),await Tt()}}async renderAsync(e,t){v('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){o("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=nc,t.modelNormalViewMatrix=ac):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===nc&&e.modelNormalViewMatrix===ac}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return v('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}`),o(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i,a),u=this.backend.get(o),l=s.version!==u.version;if(l||void 0===u.bundleGPU){this.backend.beginBundle(a),(void 0===u.renderObjects||l)&&(u.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:d,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,i,t,r),!0===this.transparent&&d.length>0&&this._renderTransparents(d,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t{u.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(u)};u.addEventListener("dispose",e),this._frameBufferTargets.set(u,l)}const d=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==d?l.setSize(d.width,d.height,d.depth):l.setSize(i,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:u._viewport,h=this._outputRenderTarget?this._outputRenderTarget.scissor:u._scissor,g=this._outputRenderTarget?1:u._pixelRatio,f=this._outputRenderTarget?this._outputRenderTarget.scissorTest:u._scissorTest;return l.viewport.copy(c),l.scissor.copy(h),l.viewport.multiplyScalar(g),l.scissor.multiplyScalar(g),l.scissorTest=f,l.multiview=null!==d&&d.multiview,l.resolveDepthBuffer=null===d||d.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==d&&d._autoAllocateDepthBuffer,l}_renderScene(e,t,r=!0){if(!0===this._isDeviceLost)return;const s=r?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,u=this._handleObjectFunction;this._callDepth++;const l=!0===e.isScene?e:zS,d=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let p;if(null!==s?(p=s,this.setRenderTarget(p)):p=d,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p);const m=this.xr;if(!1===m.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const r=this.coordinateSystem;if(t.coordinateSystem!==r){if(t.coordinateSystem=r,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=r;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,x=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,x=1),this.getDrawingBufferSize($S),WS.set(0,0,$S.width,$S.height);const T=void 0===y.minDepth?0:y.minDepth,_=void 0===y.maxDepth?1:y.maxDepth;g.viewportValue.copy(y).multiplyScalar(x).floor(),g.viewportValue.width>>=h,g.viewportValue.height>>=h,g.viewportValue.minDepth=T,g.viewportValue.maxDepth=_,g.viewport=!1===g.viewportValue.equals(WS),g.scissorValue.copy(b).multiplyScalar(x).floor(),g.scissor=f._scissorTest&&!1===g.scissorValue.equals(WS),g.scissorValue.width>>=h,g.scissorValue.height>>=h,g.clippingContext||(g.clippingContext=new vS),g.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const v=t.isArrayCamera?qS:HS;t.isArrayCamera||(jS.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(jS,t.coordinateSystem,t.reversedDepth));const N=this._renderLists.get(e,t);if(N.begin(),this._projectObject(e,t,0,N,g.clippingContext),N.finish(),!0===this.sortObjects&&N.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,h);const e=this._textures.get(p);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=$S.width,g.height=$S.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=h,g.height>>=h,g.activeCubeFace=c,g.activeMipmapLevel=h,g.occlusionQueryCount=N.occlusionQueryCount,g.scissorValue.max(XS.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(l,N,g),g.camera=t,this.backend.beginRender(g);const{bundles:S,lightsNode:R,transparentDoublePass:A,transparent:E,opaque:w}=N;return S.length>0&&this._renderBundles(S,l,R),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,R),!0===this.transparent&&E.length>0&&this._renderTransparents(E,A,t,l,R),this.backend.finishRender(g),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=u,this._callDepth--,null!==s&&(this.setRenderTarget(d,c,h),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_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 r,s=this._quadCache.get(e.texture);if(void 0===s){r=new gx(new vg),r.name="Output Color Transform",r.material.name="outputColorTransform",r.material.fragmentNode=this._nodes.getOutputNode(e.texture),s={quad:r,cacheKey:t},this._quadCache.set(e.texture,s);const i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",i)};e.texture.addEventListener("dispose",i)}else r=s.quad,s.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,s.cacheKey=t);const i=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(r,r.camera,!1),this.autoClear=i,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,r=0,s=-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(r%4!=0||s>0&&s%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,r,s)}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,r){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,r)}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,r)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,r,s){this._canvasTarget.setScissor(e,t,r,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,r,s,i=0,n=1){this._canvasTarget.setViewport(e,t,r,s,i,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.get(s,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer;const t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),!0===s.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){v('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,r)}async clearColorAsync(){v('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){v('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){v('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==m,t=this.currentColorSpace!==p.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:m}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:p.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!0===this._initialized){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}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 d("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.deleteForCompute(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s,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 v('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){v('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),r=this._renderContexts.get(e);r.textures=t.textures,r.depthTexture=t.depthTexture,r.width=t.width,r.height=t.height,r.renderTarget=e,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,this.backend.initRenderTarget(r)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=XS.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void o("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=XS.copy(t).floor()}else t=XS.set(0,0,e.image.width,e.image.height);let r,s=this._currentRenderContext;null!==s?r=s.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),null!==r&&(this._textures.updateRenderTarget(r),s=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,s,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(e,t,r,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)r=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?qS:HS;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&XS.setFromMatrixPosition(e.matrixWorld).applyMatrix4(jS);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,XS.z,null,i)}}else if(e.isLineLoop)o("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?qS:HS;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),XS.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(jS)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=F;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=St;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=P}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n(t.not().discard(),e))(u)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),r={version:t,colorNode:u,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,r)}return r}renderObject(e,t,r,s,i,n,a,o=null,u=null){let l,d,c,h,p=!1;if(e.onBeforeRender(this,t,r,s,i,n),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,l=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,h=t.overrideMaterial.side,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:r,positionNode:s}=this._getShadowNodes(i);this.shadowMap.type===pt?e.side=null!==i.shadowSide?i.shadowSide:i.side:e.side=null!==i.shadowSide?i.shadowSide:KS[i.side],null!==t&&(e.colorNode=t),null!==r&&(e.depthNode=r),null!==s&&(e.positionNode=s)}i=e}!0===i.transparent&&i.side===P&&!1===i.forceSinglePass?(i.side=F,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=St,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=P):this._handleObjectFunction(e,i,t,r,a,n,o,u),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=h),e.onAfterRender(this,t,r,s,i,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);if(u.drawRange=e.geometry.drawRange,u.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(u);l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),this._pipelines.isReady(u)&&(this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u))}_createObjectPipeline(e,t,r,s,i,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:r,camera:s,lightsNode:i,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class YS{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class ZS extends YS{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(My-e%My)%My;var e}get buffer(){return this._buffer}update(){return!0}}class JS extends ZS{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let eR=0;class tR extends JS{constructor(e,t){super("UniformBuffer_"+eR++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class rR extends JS{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const r=this.updateRanges,s={start:e.offset,count:e.itemSize};r.push(s),this._updateRangeCache.set(t,s)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let aR=0;class oR extends nR{constructor(e,t){super(e,t),this.id=aR++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class uR extends oR{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class lR extends uR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class dR extends uR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const cR={bitcast_int_uint:new fT("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new fT("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},hR={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},pR={low:"lowp",medium:"mediump",high:"highp"},gR={swizzleAssign:!0,storageBuffer:!1},mR={perspective:"smooth",linear:"noperspective"},fR={centroid:"centroid"},yR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class bR extends QN{constructor(e,t){super(e,t,new yS),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==T}_include(e){const t=cR[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==cR[e]&&this._include(e),hR[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?We:$e;2===s?n=i?je:$:3===s?n=i?Ke:Xe:4===s&&(n=i?Ft:Ae);const a={Float32Array:K,Uint8Array:Ve,Uint16Array:Ge,Uint32Array:S,Int8Array:Oe,Int16Array:ke,Int32Array:R,Uint8ClampedArray:Ve},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s0?i:"";t=`${r.name} {\n\t${s} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===s[t]){const e=this.uniformGroups[t];if(void 0!==e){const r=[];for(const t of e.uniforms){const e=t.getType(),s=this.getVectorType(e),i=t.nodeUniform.node.precision;let n=`${s} ${t.name};`;null!==i&&(n=pR[i]+" "+n),r.push("\t"+n)}s[t]=r}}i=!0}if(!i){const s=e.node.precision;null!==s&&(t=pR[s]+" "+t),t="uniform "+t,r.push(t)}}let i="";for(const e in s){const t=s[e];i+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==R){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return 0===s.length&&s.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${mR[s.interpolationType]||s.interpolationType} ${fR[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${mR[e.interpolationType]||e.interpolationType} ${fR[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){o("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){o("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){o("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,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.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 r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=gR[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}gR[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 r=0;r0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${s.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${s.result};`)))}const n=e[t];if(n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new uR(i.name,i.node,s),u.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new lR(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new dR(i.name,i.node,s),u.push(a);else if("buffer"===t){i.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let r=t.buffer;void 0===r&&(e.name=`NodeBuffer_${e.id}`,r=new tR(e,s),r.name=e.name,t.buffer=r),u.push(r),a=r}else{let e=this.uniformGroups[o];void 0===e?(e=new iR(o,s),this.uniformGroups[o]=e,u.push(e)):-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}}let xR=null,TR=null;class _R{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Pt.RENDER]:null,[Pt.COMPUTE]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),r=this.renderer.info.frame;let s;s=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+r}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:")?Pt.COMPUTE:Pt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void v("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return xR=xR||new t,this.renderer.getDrawingBufferSize(xR)}setScissorTest(){}getClearColor(){const e=this.renderer;return TR=TR||new rb,e.getClearColor(TR),TR.getRGB(TR),TR}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Ut(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${_t} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let vR,NR,SR=0;class RR{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 AR{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===R,id:SR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new RR(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),d=new Uint8Array(new ArrayBuffer(l)),t.buffer=d.buffer}else d=new Uint8Array(t);return n.bindBuffer(n.COPY_READ_BUFFER,u),n.getBufferSubData(n.COPY_READ_BUFFER,r,d),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:d.buffer}_createBuffer(e,t,r,s){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,r,s),e.bindBuffer(t,null),i}}class ER{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;vR={[it]:e.FUNC_ADD,[It]:e.FUNC_SUBTRACT,[Dt]:e.FUNC_REVERSE_SUBTRACT},NR={[At]:e.ZERO,[Ht]:e.ONE,[Wt]:e.SRC_COLOR,[rt]:e.SRC_ALPHA,[$t]:e.SRC_ALPHA_SATURATE,[zt]:e.DST_COLOR,[Gt]:e.DST_ALPHA,[kt]:e.ONE_MINUS_SRC_COLOR,[st]:e.ONE_MINUS_SRC_ALPHA,[Vt]:e.ONE_MINUS_DST_COLOR,[Ot]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),r=e.getParameter(e.VIEWPORT);this.currentScissor=(new s).fromArray(t),this.currentViewport=(new s).fromArray(r),this._tempVec4=new s}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;e!==qt?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===jt?t.cullFace(t.BACK):e===Xt?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:r}=this;e!==t&&(r.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,r){const s=this.gl,i=this.backend.drawBuffersIndexedExt;if(i)for(let n=0;n0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()})}}let CR,MR,BR,LR=!1;class FR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===LR&&(this._init(),LR=!0)}_init(){const e=this.gl;CR={[kr]:e.REPEAT,[_e]:e.CLAMP_TO_EDGE,[Vr]:e.MIRRORED_REPEAT},MR={[B]:e.NEAREST,[Gr]:e.NEAREST_MIPMAP_NEAREST,[bt]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[yt]:e.LINEAR_MIPMAP_NEAREST,[Y]:e.LINEAR_MIPMAP_LINEAR},BR={[Hr]:e.NEVER,[Wr]:e.ALWAYS,[E]:e.LESS,[w]:e.LEQUAL,[$r]:e.EQUAL,[M]:e.GEQUAL,[C]:e.GREATER,[zr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!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,r}getInternalFormat(e,t,r,s,i,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];d("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let u=null;s&&(u=o.get("EXT_texture_norm16"),u||d("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(r===a.FLOAT&&(l=a.R32F),r===a.HALF_FLOAT&&(l=a.R16F),r===a.UNSIGNED_BYTE&&(l=a.R8),r===a.BYTE&&(l=a.R8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.R16_EXT),r===a.SHORT&&u&&(l=u.R16_SNORM_EXT)),t===a.RED_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.R8UI),r===a.UNSIGNED_SHORT&&(l=a.R16UI),r===a.UNSIGNED_INT&&(l=a.R32UI),r===a.BYTE&&(l=a.R8I),r===a.SHORT&&(l=a.R16I),r===a.INT&&(l=a.R32I)),t===a.RG&&(r===a.FLOAT&&(l=a.RG32F),r===a.HALF_FLOAT&&(l=a.RG16F),r===a.UNSIGNED_BYTE&&(l=a.RG8),r===a.BYTE&&(l=a.RG8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RG16_EXT),r===a.SHORT&&u&&(l=u.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RG8UI),r===a.UNSIGNED_SHORT&&(l=a.RG16UI),r===a.UNSIGNED_INT&&(l=a.RG32UI),r===a.BYTE&&(l=a.RG8I),r===a.SHORT&&(l=a.RG16I),r===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGB32F),r===a.HALF_FLOAT&&(l=a.RGB16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8:a.RGB8),r===a.BYTE&&(l=a.RGB8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGB16_EXT),r===a.SHORT&&u&&(l=u.RGB16_SNORM_EXT),r===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),r===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),r===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGB8UI),r===a.UNSIGNED_SHORT&&(l=a.RGB16UI),r===a.UNSIGNED_INT&&(l=a.RGB32UI),r===a.BYTE&&(l=a.RGB8I),r===a.SHORT&&(l=a.RGB16I),r===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGBA32F),r===a.HALF_FLOAT&&(l=a.RGBA16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8_ALPHA8:a.RGBA8),r===a.BYTE&&(l=a.RGBA8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGBA16_EXT),r===a.SHORT&&u&&(l=u.RGBA16_SNORM_EXT),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),r===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),r===a.UNSIGNED_INT&&(l=a.RGBA32UI),r===a.BYTE&&(l=a.RGBA8I),r===a.SHORT&&(l=a.RGBA16I),r===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(r===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),r===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),r===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&r===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,{state:n}=this.backend,a=p.getPrimaries(p.workingColorSpace),o=t.colorSpace===T?null:p.getPrimaries(t.colorSpace),u=t.colorSpace===T||a===o?r.NONE:r.BROWSER_DEFAULT_WEBGL;n.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,u),r.texParameteri(e,r.TEXTURE_WRAP_S,CR[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,CR[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,CR[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,MR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,d=t.minFilter===le&&l?Y:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,MR[d]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,BR[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===B)return;if(t.minFilter!==bt&&t.minFilter!==Y)return;if(t.type===K&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i})}createTexture(e,t){const{gl:r,backend:s}=this,{levels:i,width:n,height:a,depth:o}=t,u=s.utils.convert(e.format,e.colorSpace),l=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.normalized,e.colorSpace,e.isVideoTexture),c=r.createTexture(),h=this.getGLTextureType(e);s.state.bindTexture(h,c),this.setTextureParameters(h,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,i,d,n,a,o):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,i,d,n,a,o):e.isVideoTexture||r.texStorage2D(h,i,d,n,a),s.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{state:i}=s,{textureGPU:n,glTextureType:a,glFormat:o,glType:u}=s.get(t),{width:l,height:d}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(a,n),i.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(a,0,0,0,l,d,o,u,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t0){const t=jr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function PR(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 UR{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 DR{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 r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.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 IR={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 OR{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:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;sthis.maxQueries)return v(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){o("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){o("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,r]of this.queryOffsets){if("ended"===this.queryStates.get(r)){const s=this.queries[r];e.set(t,this.resolveQuery(s))}}if(0===e.size)return this.lastValue;const t={},r=[];for(const[s,i]of e){const e=s.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===r.includes(n)&&r.push(n),void 0===t[n]&&(t[n]=0);const a=await i;this.timestamps.set(s,a),t[n]+=a}const s=t[r[r.length-1]];return this.lastValue=s,this.frames=r,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return o("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 r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){o("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class GR extends _R{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,r={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new UR(this),this.capabilities=new DR(this),this.attributeUtils=new AR(this),this.textureUtils=new FR(this),this.bufferRenderer=new OR(this),this.state=new ER(this),this.utils=new wR(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:(d("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 c}async getArrayBufferAsync(e,t=null,r=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,r,s)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&d("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 kR(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.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,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.scissor(0,0,e,r)}this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e{let a=0;for(let t=0;t1?t.renderInstances(r,s,i):t.render(r,s)}draw(e){const{object:t,pipeline:r,material:s,context:i,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(r),{gl:o,state:u}=this,l=this.get(i),d=e.getDrawParameters();if(null===d)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;u.setMaterial(s,c,n),null!==i.mrt&&null!==i.textures&&u.setMRTBlending(i.textures,i.mrt,s),u.useProgram(a);const h=e.getAttributes(),p=this.get(h);let g=p.vaoGPU;if(void 0===g){const e=this._getVaoKey(h);g=this.vaoCache[e],void 0===g&&(g=this._createVao(h),this.vaoCache[e]=g,p.vaoGPU=g)}const m=e.getIndex(),f=null!==m?this.get(m).bufferGPU:null;u.setVertexState(g,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===s.wireframe?(u.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:x,instanceCount:T}=d;let{firstVertex:_}=d;if(b.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);b.index=m.count,b.type=e.type}else b.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()});return void t.push(i)}this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(e,t,r){if(this.renderer.debug.checkShaderErrors){const s=this.gl,i=(s.getProgramInfoLog(e)||"").trim();if(!1===s.getProgramParameter(e,s.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(s,e,r,t);else{const n=this._getShaderErrors(s,r,"vertex"),a=this._getShaderErrors(s,t,"fragment");o("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+n+"\n"+a)}else""!==i&&d("WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;eIR[t]===e),r=this.extensions;for(let e=0;e1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=Zy(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const zR="point-list",$R="line-list",WR="line-strip",HR="triangle-list",qR="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},jR="never",XR="less",KR="equal",QR="less-equal",YR="greater",ZR="not-equal",JR="greater-equal",eA="always",tA="store",rA="load",sA="clear",iA="ccw",nA="cw",aA="none",oA="back",uA="uint16",lA="uint32",dA="r8unorm",cA="r8snorm",hA="r8uint",pA="r8sint",gA="r16uint",mA="r16sint",fA="r16float",yA="rg8unorm",bA="rg8snorm",xA="rg8uint",TA="rg8sint",_A="r16unorm",vA="r16snorm",NA="r32uint",SA="r32sint",RA="r32float",AA="rg16uint",EA="rg16sint",wA="rg16float",CA="rgba8unorm",MA="rgba8unorm-srgb",BA="rgba8snorm",LA="rgba8uint",FA="rgba8sint",PA="bgra8unorm",UA="bgra8unorm-srgb",DA="rg16unorm",IA="rg16snorm",OA="rgb9e5ufloat",VA="rgb10a2unorm",kA="rg11b10ufloat",GA="rg32uint",zA="rg32sint",$A="rg32float",WA="rgba16uint",HA="rgba16sint",qA="rgba16float",jA="rgba16unorm",XA="rgba16snorm",KA="rgba32uint",QA="rgba32sint",YA="rgba32float",ZA="depth16unorm",JA="depth24plus",eE="depth24plus-stencil8",tE="depth32float",rE="depth32float-stencil8",sE="bc1-rgba-unorm",iE="bc1-rgba-unorm-srgb",nE="bc2-rgba-unorm",aE="bc2-rgba-unorm-srgb",oE="bc3-rgba-unorm",uE="bc3-rgba-unorm-srgb",lE="bc4-r-unorm",dE="bc4-r-snorm",cE="bc5-rg-unorm",hE="bc5-rg-snorm",pE="bc6h-rgb-ufloat",gE="bc6h-rgb-float",mE="bc7-rgba-unorm",fE="bc7-rgba-unorm-srgb",yE="etc2-rgb8unorm",bE="etc2-rgb8unorm-srgb",xE="etc2-rgb8a1unorm",TE="etc2-rgb8a1unorm-srgb",_E="etc2-rgba8unorm",vE="etc2-rgba8unorm-srgb",NE="eac-r11unorm",SE="eac-r11snorm",RE="eac-rg11unorm",AE="eac-rg11snorm",EE="astc-4x4-unorm",wE="astc-4x4-unorm-srgb",CE="astc-5x4-unorm",ME="astc-5x4-unorm-srgb",BE="astc-5x5-unorm",LE="astc-5x5-unorm-srgb",FE="astc-6x5-unorm",PE="astc-6x5-unorm-srgb",UE="astc-6x6-unorm",DE="astc-6x6-unorm-srgb",IE="astc-8x5-unorm",OE="astc-8x5-unorm-srgb",VE="astc-8x6-unorm",kE="astc-8x6-unorm-srgb",GE="astc-8x8-unorm",zE="astc-8x8-unorm-srgb",$E="astc-10x5-unorm",WE="astc-10x5-unorm-srgb",HE="astc-10x6-unorm",qE="astc-10x6-unorm-srgb",jE="astc-10x8-unorm",XE="astc-10x8-unorm-srgb",KE="astc-10x10-unorm",QE="astc-10x10-unorm-srgb",YE="astc-12x10-unorm",ZE="astc-12x10-unorm-srgb",JE="astc-12x12-unorm",ew="astc-12x12-unorm-srgb",tw="clamp-to-edge",rw="repeat",sw="mirror-repeat",iw="linear",nw="nearest",aw="zero",ow="one",uw="src",lw="one-minus-src",dw="src-alpha",cw="one-minus-src-alpha",hw="dst",pw="one-minus-dst",gw="dst-alpha",mw="one-minus-dst-alpha",fw="src-alpha-saturated",yw="constant",bw="one-minus-constant",xw="add",Tw="subtract",_w="reverse-subtract",vw="min",Nw="max",Sw=0,Rw=15,Aw="keep",Ew="zero",ww="replace",Cw="invert",Mw="increment-clamp",Bw="decrement-clamp",Lw="increment-wrap",Fw="decrement-wrap",Pw="storage",Uw="read-only-storage",Dw="write-only",Iw="read-only",Ow="read-write",Vw="non-filtering",kw="comparison",Gw="float",zw="unfilterable-float",$w="depth",Ww="sint",Hw="uint",qw="2d",jw="3d",Xw="2d",Kw="2d-array",Qw="cube",Yw="3d",Zw="all",Jw="vertex",eC="instance",tC={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"},rC={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class sC extends nR{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class iC extends ZS{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let nC=0;class aC extends iC{constructor(e,t){super("StorageBuffer_"+nC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ii.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class oC extends Ry{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:iw}),this.flipYSampler=e.createSampler({minFilter:nw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const r=`${e}-${t=t||"2d-array"}`;let s=this.transferPipelines[r];return void 0===s&&(s=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[r]=s),s}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.device.createTexture({size:{width:i,height:n},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(s,e.textureBindingViewDimension),u=this.getTransferPipeline(s,a.textureBindingViewDimension),l=this.device.createCommandEncoder({}),d=(e,t,r,s,i,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),u=l.beginRenderPass({colorAttachments:[{view:s.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:i,arrayLayerCount:1}),loadOp:sA,storeOp:tA}]});u.setPipeline(e),u.setBindGroup(0,o),u.draw(3,1,0,r),u.end()};d(o,e,r,a,0,!1),d(u,a,0,e,r,!0),this.device.queue.submit([l.finish()]),a.destroy()}generateMipmaps(e,t=null){const r=this.get(e),s=r.layers||this._mipmapCreateBundles(e),i=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(i,s),null===t&&this.device.queue.submit([i.finish()]),r.layers=s}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",r=this.getTransferPipeline(e.format,t),s=r.getBindGroupLayout(0),i=[];for(let n=1;n0)for(let t=0,n=s.length;t0){for(const s of e.layerUpdates)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);e.clearLayerUpdates()}else for(let s=0;s0)for(let t=0,n=s.length;t{const t=e.changedElements;for(const e of r)t.includes(e.image)&&(e.needsUpdate=!0)}}dispose(){this._samplerCache.clear(),this._htmlTextures.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new N;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,format:e}),this.defaultTexture[e]=t=r}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const r=new U;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=r}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,r){const s=e.images,i=e.mipmaps;for(let n=0;n<6;n++){const a=s[n],o=!0===e.flipY?lC[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha);for(let s=0;s0?e.width:r.size.width,l=a>0?e.height:r.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:n},{width:u,height:l,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new oC(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},u,{offset:e.width*e.height*l*n,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r){const s=this.backend.device,i=this._getBlockData(r.format),n=r.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,pC=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,gC={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",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 mC extends hS{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(hC);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=pC.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class fC extends cS{parseFunction(e){return new mC(e)}}const yC={[ii.READ_ONLY]:"read",[ii.WRITE_ONLY]:"write",[ii.READ_WRITE]:"read_write"},bC={[kr]:"repeat",[_e]:"clamp",[Vr]:"mirror"},xC={vertex:qR.VERTEX,fragment:qR.FRAGMENT,compute:qR.COMPUTE},TC={instance:!0,swizzleAssign:!1,storageBuffer:!0},_C={"^^":"tsl_xor"},vC={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},NC={},SC={tsl_xor:new fT("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new fT("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new fT("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new fT("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new fT("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new fT("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new fT("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new fT("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new fT("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new fT("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new fT("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 fT("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new fT("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new fT("\nfn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},RC={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let AC="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(AC+="diagnostic( off, derivative_uniformity );\n");class EC extends QN{constructor(e,t){super(e,t,new fC),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${bC[e.wrapS]}S_${bC[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let r=NC[t];if(void 0===r){const s=[],i=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===kr?(s.push(SC.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===_e?(s.push(SC.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Vr?(s.push(SC.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,d(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",NC[t]=r=new fT(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Uu(new wl(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Uu(new wl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Uu(new wl("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2(${s}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${r} ), ${o}, u32( ${n} ), u32( ${i} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${r} ), ${o}, u32( ${i} ) )`)}generateTextureLod(e,t,r,s,i,n="0u"){if(!0===e.isCubeTexture){i&&(r=`${r} + vec3(${i})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}(${i}) / ${u}( ${o} )`);return r=`${u}( clamp( floor( ${a}( ${r} ) * ${u}( ${o} ) ), ${`${u}( 0 )`}, ${`${u}( ${o} - ${"vec3"===u?"vec3( 1, 1, 1 )":"vec2( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,r,n,s,null)}generateStorageTextureLoad(e,t,r,s,i,n){let a;return n&&(r=`${r} + ${n}`),a=i?`textureLoad( ${t}, ${r}, ${i} )`:`textureLoad( ${t}, ${r} )`,a}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0u"),n&&(r=`${r} + ${n}`),i?a=`textureLoad( ${t}, ${r}, ${i}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(A.TEXTURE_COMPARE)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===K||!1===this.isSampleCompare(e)&&e.minFilter===B&&e.magFilter===B||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;o(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`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,r=e.type;return"texture"===r||"cubeTexture"===r||"cubeDepthTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=_C[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(d("WebGPURenderer: Atomic operations are only supported in compute shaders."),ii.READ_WRITE):ii.READ_ONLY:e.access}getStorageAccess(e,t){return yC[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);"texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new dR(i.name,i.node,o,n):new uR(i.name,i.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?s=new lR(i.name,i.node,o,n):"texture3D"===t&&(s=new dR(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(xC[r]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new sC(`${i.name}_sampler`,i.node,o);e.setVisibility(xC[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let u=n.buffer;if(void 0===u){u=new("buffer"===t?tR:aC)(e,o),n.buffer=u}u.setVisibility(u.getVisibility()|xC[r]),l.push(u),a=u,i.name=s||"NodeBuffer_"+i.id}else{let e=this.uniformGroups[u];void 0===e&&(e=new iR(u,o),e.setVisibility(qR.VERTEX|qR.FRAGMENT|qR.COMPUTE),this.uniformGroups[u]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),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,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null,s=""){let i=`var${s} ${t} : `;return i+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),i}getVars(e,t=!1){let r="";t&&(r="");const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count,r)};`);return t?s.join("\n"):`\n\t${s.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];let i=0;for(let n=0;nr.value.itemSize;return s&&!i}getUniforms(e){const t=this.renderer.backend,r=this.uniforms[e],s=[],i=[],n=[],a={};for(const n of r){const r=n.groupNode.name,o=this.bindingsIndexes[r];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const r=n.node.value;let i;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==n.node.isStorageTextureNode)&&(this.isSampleCompare(r)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let a="";const{primarySamples:u}=t.utils.getTextureSampleData(r);if(u>1&&(a="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)i="texture_depth_cube";else if(!0===r.isCubeTexture)i="texture_cube";else if(!0===r.isDepthTexture)i=t.compatibilityMode&&null===r.compareFunction?`texture${a}_2d`:`texture_depth${a}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const s=cC(r,t.device),a=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,u=n.node.value.isArrayTexture;i=`texture_storage_${o?"3d":"2d"+(u?"_array":"")}<${s}, ${a}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture)i="texture_2d_array";else if(!0===r.is3DTexture||!0===r.isData3DTexture)i="texture_3d";else{i=`texture${a}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${i};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,r=this.getType(t.getNodeType(this)),s=t.bufferCount,a=s>0&&"buffer"===n.type?", "+s:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${u}> ${n.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${a} >`;i.push(this._getWGSLStructBinding(n.name,e,u,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const r=[];for(const e of t.uniforms){const t=e.getType(),s=this.getType(this.getVectorType(t));r.push(`\t${e.name} : ${s}`)}let s=this.uniformGroupsBindings[e];void 0===s&&(s={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=s),a[e]={index:s.index,id:s.id,snippets:r}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=this.allowGlobalVariables,s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t,r),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,u=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const r=this.getFlowData(e),n=e.name;if(n&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${n}\n`),i+=`${r.code}\n\t`,e===a&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(u)s.returnType=o.getNodeType(this),s.structs+="var output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location( 0 ) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return vC[e]||e}isAvailable(e){let t=TC[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),TC[e]=t),t}_getWGSLMethod(e){return void 0!==SC[e]&&this._include(e),RC[e]}_include(e){const t=SC[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${AC}\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[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\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 * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * 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,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class wC{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?rE:eE:!0===this.backend.renderer.reversedDepthBuffer?tE:JA),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}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?zR:e.isLineSegments||e.isMesh&&!0===t.wireframe?$R:e.isLine?WR:e.isMesh?HR:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ve)return PA;if(e===Te)return qA;throw new Error("Unsupported output buffer type.")}}const CC=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&CC.set(Float16Array,["float16"]);const MC=new Map([[xt,["float16"]]]),BC=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class LC{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o=r.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e{t.buffer=null,t._mapped=!1,u.unmap()},s=()=>{t.buffer=null,t._mapped=!1,u.destroy(),i.delete(t),t.removeEventListener("release",r),t.removeEventListener("dispose",s)};t.addEventListener("release",r),t.addEventListener("dispose",s),e.readBufferGPU=u}else u=e.readBufferGPU}else u=n.createBuffer({label:`${e.name}_readback`,size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const l=n.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(a,r,u,0,o);const d=l.finish();if(n.queue.submit([d]),await u.mapAsync(GPUMapMode.READ,0,o),null===t){const e=u.getMappedRange(0,o).slice();return u.destroy(),e}if(t.isReadbackBuffer)return t.buffer=u.getMappedRange(0,o),t;{const e=u.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),u.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:r}=e,s=e.array.constructor,i=e.constructor;let n;if(1===t)n=BC.get(s);else{const e=(MC.get(i)||CC.get(s))[r?1:0];if(e){const r=s.BYTES_PER_ELEMENT*t,i=4*Math.floor((r+3)/4)/s.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${i}`}}return n||o("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class FC{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class PC{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,r=t.device,s=t.get(e);if(s.layout)return s.layout.layoutGPU;const i=this._createLayoutEntries(e),n=Vs(JSON.stringify(i));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new FC(r.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,s.layout=a,s.layoutKey=n,a.layoutGPU}createBindings(e,t,r,s=0){const{backend:i}=this,n=i.get(e),a=this.createBindingsLayout(e);let o;r>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[r]===s&&(o=n.groups[r])),void 0===o&&(o=this.createBindGroup(e,a),r>0&&(n.groups[r]=o,n.versions[r]=s)),n.group=o}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer,n=e.updateRanges;if(0===n.length)r.queue.writeBuffer(i,0,s,0);else{const e=Xr(s),t=e?1:s.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${r}-${s}`,a=e[i],void 0===a){const n=Zw;let o;o=t.isSampledCubeTexture?Qw:t.isSampledTexture3D?Yw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Kw:Xw,a=e[i]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:r,baseMipLevel:s})}}n.push({binding:i,resource:a})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let r=0;for(const s of e.bindings){const e=this.backend,i={binding:r,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const e={};s.isStorageBuffer&&(s.visibility&qR.COMPUTE&&(s.access===ii.READ_WRITE||s.access===ii.WRITE_ONLY)?e.type=Pw:e.type=Uw),i.buffer=e}else if(s.isSampledTexture&&s.store){const e={};e.format=this.backend.get(s.texture).texture.format;const t=s.access;e.access=t===ii.READ_WRITE?Ow:t===ii.WRITE_ONLY?Dw:Iw,s.texture.isArrayTexture?e.viewDimension=Kw:s.texture.is3DTexture&&(e.viewDimension=Yw),i.storageTexture=e}else if(s.isSampledTexture){const t={},{primarySamples:r}=e.utils.getTextureSampleData(s.texture);if(r>1&&(t.multisampled=!0,s.texture.isDepthTexture||(t.sampleType=zw)),s.texture.isDepthTexture)e.compatibilityMode&&null===s.texture.compareFunction?t.sampleType=zw:t.sampleType=$w;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture||s.texture.isStorageTexture){const e=s.texture.type;e===R?t.sampleType=Ww:e===S?t.sampleType=Hw:e===K&&(this.backend.hasFeature("float32-filterable")?t.sampleType=Gw:t.sampleType=zw)}s.isSampledCubeTexture?t.viewDimension=Qw:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?t.viewDimension=Kw:s.isSampledTexture3D&&(t.viewDimension=Yw),i.texture=t}else if(s.isSampler){const t={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction&&e.hasCompatibility(A.TEXTURE_COMPARE)?t.type=kw:t.type=Vw),i.sampler=t}else o(`WebGPUBindingUtils: Unsupported binding "${s}".`);t.push(i),r++}return t}deleteBindGroupData(e){const{backend:t}=this,r=t.get(e);r.layout&&(r.layout.usedTimes--,0===r.layout.usedTimes&&this._bindGroupLayoutCache.delete(r.layoutKey),r.layout=void 0,r.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class UC{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class DC{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:r,material:s,geometry:i,pipeline:n}=e,{vertexProgram:a,fragmentProgram:u}=n,l=this.backend,d=l.device,c=l.utils,h=l.get(n),p=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:r}=e.layout;p.push(r)}const g=l.attributeUtils.createShaderVertexBuffers(e);let m;s.blending===re||s.blending===tt&&!1===s.transparent||(m=this._getBlending(s));let f={};!0===s.stencilWrite&&(f={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const y=this._getColorWriteMask(s),b=[];if(null!==e.context.textures){const t=e.context.textures,r=e.context.mrt;for(let e=0;e1},layout:d.createPipelineLayout({bindGroupLayouts:p})},E={},w=e.context.depth,C=e.context.stencil;if(!0!==w&&!0!==C||(!0===w&&(E.format=S,E.depthWriteEnabled=s.depthWrite,E.depthCompare=N),!0===C&&(E.stencilFront=f,E.stencilBack=f,E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),A.depthStencil=E),d.pushErrorScope("validation"),null===t)h.pipeline=d.createRenderPipeline(A),d.popErrorScope().then(e=>{null!==e&&(h.error=!0,o(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await d.createRenderPipelineAsync(A)}catch(e){}const t=await d.popErrorScope();null!==t&&(h.error=!0,o(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:s.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e),{layoutGPU:s}=t.layout;a.push(s)}n.pipeline=s.createComputePipeline({compute:i,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,r;const s=e.blending,i=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(s===Rt){const s=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,u=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},r={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(u)}}else{const i=(e,s,i,n)=>{t={srcFactor:e,dstFactor:s,operation:xw},r={srcFactor:i,dstFactor:n,operation:xw}};if(e.premultipliedAlpha)switch(s){case tt:i(ow,cw,ow,cw);break;case Yt:i(ow,ow,ow,ow);break;case Qt:i(aw,lw,aw,ow);break;case Kt:i(hw,cw,aw,ow)}else switch(s){case tt:i(dw,cw,ow,cw);break;case Yt:i(dw,ow,ow,ow);break;case Qt:o(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Kt:o(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};o("WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case At:t=aw;break;case Ht:t=ow;break;case Wt:t=uw;break;case kt:t=lw;break;case rt:t=dw;break;case st:t=cw;break;case zt:t=hw;break;case Vt:t=pw;break;case Gt:t=gw;break;case Ot:t=mw;break;case $t:t=fw;break;case 211:t=yw;break;case 212:t=bw;break;default:o("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case rs:t=jR;break;case ts:t=eA;break;case es:t=XR;break;case Jr:t=QR;break;case Zr:t=KR;break;case Yr:t=JR;break;case Qr:t=YR;break;case Kr:t=ZR;break;default:o("WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case ds:t=Aw;break;case ls:t=Ew;break;case us:t=ww;break;case os:t=Cw;break;case as:t=Mw;break;case ns:t=Bw;break;case is:t=Lw;break;case ss:t=Fw;break;default:o("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case it:t=xw;break;case It:t=Tw;break;case Dt:t=_w;break;case hs:t=vw;break;case cs:t=Nw;break;default:o("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?uA:lA);let n=r.side===F;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),s.frontFace=!0===n?nA:iA,s.cullMode=r.side===P?aA:oA,s}_getColorWriteMask(e){return!0===e.colorWrite?Rw:Sw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=eA;else{const r=this.backend.parameters.reversedDepthBuffer?ar[e.depthFunc]:e.depthFunc;switch(r){case nr:t=jR;break;case ir:t=eA;break;case sr:t=XR;break;case rr:t=QR;break;case tr:t=KR;break;case er:t=JR;break;case Jt:t=YR;break;case Zt:t=ZR;break;default:o("WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class IC extends VR{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r)),a={},o=[];for(const[t,r]of e){const e=t.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===o.includes(s)&&o.push(s),void 0===a[s]&&(a[s]=0);const i=n[r],u=n[r+1],l=Number(u-i)/1e6;this.timestamps.set(t,l),a[s]+=l}const u=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=u,this.frames=o,u}catch(e){return o("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){o("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){o("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const OC={r:0,g:0,b:0,a:1};class VC extends _R{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 wC(this),this.attributeUtils=new LC(this),this.bindingUtils=new PC(this),this.capabilities=new UC(this),this.pipelineUtils=new DC(this),this.textureUtils=new dC(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[A.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},s="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===s)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(tC),n=[];for(const e of i)s.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};r=await s.requestDevice(a)}else r=t.device;this.compatibilityMode=!r.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),r.lost.then(t=>{if("destroyed"===t.reason)return;const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}),this.device=r,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(tC.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let r=t.context;if(void 0===r){const s=this.parameters;r=!0===e.isDefaultCanvasTarget&&void 0!==s.context?s.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${_t} webgpu`);const i=s.alpha?"premultiplied":"opaque",n=s.outputType===Te?"extended":"standard";r.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),t.context=r}return r}get coordinateSystem(){return h}async getArrayBufferAsync(e,t=null,r=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,r,s)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),r=this.get(t),s=e.currentSamples;let i=r.descriptor;if(void 0===i||r.samples!==s){i={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(i.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=i.colorAttachments[0];s>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,r.descriptor=i,r.samples=s}const n=i.colorAttachments[0];return s>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;void 0!==i&&s.width===r.width&&s.height===r.height&&s.samples===r.samples||(i={},s.descriptors=i);const n=e.getCacheKey();let a=i[n];if(void 0===a){const t=e.textures,o=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s1)if(!0===l){const t=e.camera.cameras;for(let e=0;e0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=r.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:rA}),this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(i=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,i));const n=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),n.dispatchSize=i}i=n.dispatchSize}a.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,r,s,i,n,a,o,u){const{object:l,material:d,context:c}=e,h=e.getIndex(),p=null!==h;this.pipelineUtils.setPipeline(o,s),u.pipeline=s;const g=u.bindingGroups;for(let e=0,t=i.length;e65535?4:2);for(let n=0;n0){const i=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===i.indexesGPU||i.indexesGPU.length!==a.length){const e=this.get(c),t=[],r=new Uint32Array([0,0,0,0]);for(let s=0,i=a.length;s(d("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new GR(e)));super(new t(e),e),this.library=new zC,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class WC extends As{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class HC{constructor(e,t=Cn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new vg;r.name="RenderPipeline",this._quadMesh=new gx(r),this._quadMesh.name="Render Pipeline",this._context=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){const e=this.renderer;this._update(),null!==this._context.onBeforeRenderPipeline&&this._context.onBeforeRenderPipeline();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=m,e.outputColorSpace=p.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterRenderPipeline&&this._context.onAfterRenderPipeline()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),!0===this.needsUpdate){const e=this._toneMapping,t=this._outputColorSpace,r={renderPipeline:this,onBeforeRenderPipeline:null,onAfterRenderPipeline:null};let s=this.outputNode;!0===this.outputColorTransform?(s=s.context(r),s=Ll(s,e,t)):(r.toneMapping=e,r.outputColorSpace=t,s=s.context(r)),this._context=r,this._quadMesh.material.fragmentNode=s,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){v('RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}}class qC extends HC{constructor(e,t){v('PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.'),super(e,t)}}class jC extends u{constructor(e){super(),this.name="",this.buffer=null,this.maxByteLength=e,this.isReadbackBuffer=!0,this._mapped=!1}release(){this.dispatchEvent({type:"release"})}dispose(){this.dispatchEvent({type:"dispose"})}}class XC extends N{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class KC extends N{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!1,this.image={width:e,height:t,depth:r},this.magFilter=le,this.minFilter=le,this.wrapR=_e,this.isStorageTexture=!0,this.is3DTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class QC extends N{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!0,this.image={width:e,height:t,depth:r},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class YC extends Ex{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class ZC extends Es{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new ws(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{try{t(this.parse(JSON.parse(r)))}catch(t){s?s(t):o(t),this.manager.itemError(e)}},r,s)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return void 0===this.nodes[e]?(o("NodeLoader: Node type not found:",e),yn()):new this.nodes[e]}}class JC extends Cs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class eM extends Ms{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}async parseAsync(e){this._nodesJSON=e.nodes;const t=await super.parseAsync(e);return this._nodesJSON=null,t}parseNodes(e,t){if(void 0!==e){const r=new ZC;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new JC;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t createEvent( EventNode.OBJECT, callback ) */ const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback ); +/** + * Creates an event that triggers a function every frame. + * + * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one. + * + * @param {Function} callback - The callback function. + * @returns {EventNode} + */ +const OnFrameUpdate = ( callback ) => createEvent( EventNode.FRAME, callback ); + /** * Creates an event that triggers a function before an object (Mesh|Sprite) is updated. * @@ -38137,6 +38162,16 @@ const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJEC */ const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback ); +/** + * Creates an event that triggers a function before every frame. + * + * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one. + * + * @param {Function} callback - The callback function. + * @returns {EventNode} + */ +const OnBeforeFrameUpdate = ( callback ) => createEvent( EventNode.BEFORE_FRAME, callback ); + /** * This special type of instanced buffer attribute is intended for compute shaders. * In earlier three.js versions it was only possible to update attribute data @@ -47363,8 +47398,10 @@ var TSL = /*#__PURE__*/Object.freeze({ NodeShaderStage: NodeShaderStage, NodeType: NodeType, NodeUpdateType: NodeUpdateType, + OnBeforeFrameUpdate: OnBeforeFrameUpdate, OnBeforeMaterialUpdate: OnBeforeMaterialUpdate, OnBeforeObjectUpdate: OnBeforeObjectUpdate, + OnFrameUpdate: OnFrameUpdate, OnMaterialUpdate: OnMaterialUpdate, OnObjectUpdate: OnObjectUpdate, PCFShadowFilter: PCFShadowFilter, @@ -57733,65 +57770,6 @@ class CanvasTarget extends EventDispatcher { } -/** - * A readback buffer is used to transfer data from the GPU to the CPU. - * It is primarily used to read back compute shader results. - * - * @augments EventDispatcher - */ -class ReadbackBuffer extends EventDispatcher { - - /** - * Constructs a new readback buffer. - * - * @param {BufferAttribute} attribute - The buffer attribute. - */ - constructor( attribute ) { - - super(); - - /** - * The buffer attribute. - * - * @type {BufferAttribute} - */ - this.attribute = attribute; - - /** - * This flag can be used for type testing. - * - * @type {boolean} - * @readonly - * @default true - */ - this.isReadbackBuffer = true; - - } - - /** - * Releases the mapped buffer data so the GPU buffer can be - * used by the GPU again. - * - * Note: Any `ArrayBuffer` data associated with this readback buffer - * are removed and no longer accessible after calling this method. - */ - release() { - - this.dispatchEvent( { type: 'release' } ); - - } - - /** - * Frees internal resources. - */ - dispose() { - - this.dispatchEvent( { type: 'dispose' } ); - - } - -} - const _scene = /*@__PURE__*/ new Scene(); const _drawingBufferSize = /*@__PURE__*/ new Vector2(); const _screen = /*@__PURE__*/ new Vector4(); @@ -59666,61 +59644,42 @@ class Renderer { * from the GPU to the CPU in context of compute shaders. * * @async - * @param {StorageBufferAttribute|ReadbackBuffer} buffer - The storage buffer attribute. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @param {number} offset - The storage buffer attribute. + * @param {number} count - The offset from which to start reading the + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( buffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { - let readbackBuffer = buffer; + // tally the memory for this readback buffer + if ( target !== null && target.isReadbackBuffer ) { - if ( readbackBuffer.isReadbackBuffer !== true ) { + if ( this.info.memoryMap.has( target ) === false ) { - const attribute = buffer; - const attributeData = this.backend.get( attribute ); + this.info.createReadbackBuffer( target ); - readbackBuffer = attributeData.readbackBuffer; - - if ( readbackBuffer === undefined ) { - - readbackBuffer = new ReadbackBuffer( attribute ); - - const dispose = () => { + const disposeInfo = () => { - attribute.removeEventListener( 'dispose', dispose ); + target.removeEventListener( 'dispose', disposeInfo ); - readbackBuffer.dispose(); - - delete attributeData.readbackBuffer; + this.info.destroyReadbackBuffer( target ); }; - attribute.addEventListener( 'dispose', dispose ); - - attributeData.readbackBuffer = readbackBuffer; + target.addEventListener( 'dispose', disposeInfo ); } } - if ( this.info.memoryMap.has( readbackBuffer ) === false ) { - - this.info.createReadbackBuffer( readbackBuffer ); - - const disposeInfo = () => { - - readbackBuffer.removeEventListener( 'dispose', disposeInfo ); - - this.info.destroyReadbackBuffer( readbackBuffer ); - - }; + if ( offset % 4 !== 0 || ( count > 0 && count % 4 !== 0 ) ) { - readbackBuffer.addEventListener( 'dispose', disposeInfo ); + throw new Error( 'THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.' ); } - readbackBuffer.release(); - - return await this.backend.getArrayBufferAsync( readbackBuffer ); + return await this.backend.getArrayBufferAsync( attribute, target, offset, count ); } @@ -65385,76 +65344,81 @@ class WebGLAttributeUtils { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The readback buffer. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @param {number} offset - The storage buffer attribute. + * @param {number} count - The offset from which to start reading the + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { const backend = this.backend; const { gl } = backend; - const attribute = readbackBuffer.attribute; const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute; - const { bufferGPU } = backend.get( bufferAttribute ); + const attributeInfo = backend.get( bufferAttribute ); + const { bufferGPU } = attributeInfo; - const array = attribute.array; - const byteLength = array.byteLength; - - gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU ); + const byteLength = count === -1 ? attributeInfo.byteLength - offset : count; - const readbackBufferData = backend.get( readbackBuffer ); + // read the data back + let dstBuffer; + if ( target === null ) { - let { writeBuffer } = readbackBufferData; + dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) ); - if ( writeBuffer === undefined ) { + } else if ( target.isReadbackBuffer ) { - writeBuffer = gl.createBuffer(); + if ( target._mapped === true ) { - gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer ); - gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ ); + throw new Error( 'WebGPURenderer: ReadbackBuffer must be released before being used again.' ); - // dispose - - const dispose = () => { - - gl.deleteBuffer( writeBuffer ); + } - backend.delete( readbackBuffer ); + const releaseCallback = () => { - readbackBuffer.removeEventListener( 'dispose', dispose ); + target.buffer = null; + target._mapped = false; + target.removeEventListener( 'release', releaseCallback ); + target.removeEventListener( 'dispose', releaseCallback ); }; - readbackBuffer.addEventListener( 'dispose', dispose ); + target.addEventListener( 'release', releaseCallback ); + target.addEventListener( 'dispose', releaseCallback ); - // register - - readbackBufferData.writeBuffer = writeBuffer; + // WebGL has no concept of a "mapped" data buffer so we create a new buffer, instead. + dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) ); + target.buffer = dstBuffer.buffer; } else { - gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer ); + dstBuffer = new Uint8Array( target ); } - gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength ); + // Ensure the buffer is bound before reading + gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU ); + gl.getBufferSubData( gl.COPY_READ_BUFFER, offset, dstBuffer ); - await backend.utils._clientWaitAsync(); + gl.bindBuffer( gl.COPY_READ_BUFFER, null ); + gl.bindBuffer( gl.COPY_WRITE_BUFFER, null ); - const dstBuffer = new attribute.array.constructor( array.length ); + // return the appropriate type + if ( target && target.isReadbackBuffer ) { - // Ensure the buffer is bound before reading - gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer ); + return target; - gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer ); + } else { - gl.bindBuffer( gl.COPY_READ_BUFFER, null ); - gl.bindBuffer( gl.COPY_WRITE_BUFFER, null ); + return dstBuffer.buffer; - return dstBuffer; + } } @@ -69581,15 +69545,20 @@ class WebGLBackend extends Backend { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The readback buffer. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @param {number} offset - The storage buffer attribute. + * @param {number} count - The offset from which to start reading the + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { - return await this.attributeUtils.getArrayBufferAsync( readbackBuffer ); + return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count ); } @@ -73581,7 +73550,9 @@ class WebGPUTextureUtils { await readBuffer.mapAsync( GPUMapMode.READ ); - const buffer = readBuffer.getMappedRange(); + const buffer = readBuffer.getMappedRange().slice(); + + readBuffer.destroy(); return new typedArrayType( buffer ); @@ -77884,82 +77855,137 @@ class WebGPUAttributeUtils { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The storage buffer attribute. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {number} count - The offset from which to start reading the + * @param {number} offset - The storage buffer attribute. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { const backend = this.backend; const device = backend.device; - const attribute = readbackBuffer.attribute; const data = backend.get( this._getBufferAttribute( attribute ) ); const bufferGPU = data.buffer; - const size = bufferGPU.size; + const byteLength = count === -1 ? bufferGPU.size - offset : count; - const readbackBufferData = backend.get( readbackBuffer ); + let readBufferGPU; + if ( target !== null && target.isReadbackBuffer ) { - let { readBufferGPU } = readbackBufferData; + const readbackInfo = backend.get( target ); - if ( readBufferGPU === undefined ) { + if ( target._mapped === true ) { - readBufferGPU = device.createBuffer( { - label: `${ attribute.name }_readback`, - size, - usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ - } ); + throw new Error( 'WebGPURenderer: ReadbackBuffer must be released before being used again.' ); - // release / dispose + } - const release = () => { + target._mapped = true; - readBufferGPU.unmap(); + // initialize the GPU-side read copy buffer if it is not present + if ( readbackInfo.readBufferGPU === undefined ) { - }; + readBufferGPU = device.createBuffer( { + label: `${ target.name }_readback`, + size: target.maxByteLength, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ + } ); - const dispose = () => { + // release / dispose + const releaseCallback = () => { - readBufferGPU.destroy(); + target.buffer = null; + target._mapped = false; - backend.delete( readbackBuffer ); + readBufferGPU.unmap(); - readbackBuffer.removeEventListener( 'release', release ); - readbackBuffer.removeEventListener( 'dispose', dispose ); + }; - }; + const disposeCallback = () => { + + target.buffer = null; + target._mapped = false; + + readBufferGPU.destroy(); + + backend.delete( target ); + + target.removeEventListener( 'release', releaseCallback ); + target.removeEventListener( 'dispose', disposeCallback ); + + }; + + target.addEventListener( 'release', releaseCallback ); + target.addEventListener( 'dispose', disposeCallback ); + + // register + readbackInfo.readBufferGPU = readBufferGPU; + + } else { - readbackBuffer.addEventListener( 'release', release ); - readbackBuffer.addEventListener( 'dispose', dispose ); + readBufferGPU = readbackInfo.readBufferGPU; - // register + } - readbackBufferData.readBufferGPU = readBufferGPU; + } else { + + // create a new temp buffer for array buffers otherwise + readBufferGPU = device.createBuffer( { + label: `${ attribute.name }_readback`, + size: byteLength, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ + } ); } + // copy the data const cmdEncoder = device.createCommandEncoder( { label: `readback_encoder_${ attribute.name }` } ); cmdEncoder.copyBufferToBuffer( bufferGPU, - 0, + offset, readBufferGPU, 0, - size + byteLength, ); const gpuCommands = cmdEncoder.finish(); device.queue.submit( [ gpuCommands ] ); - await readBufferGPU.mapAsync( GPUMapMode.READ ); + // map the data to the CPU + await readBufferGPU.mapAsync( GPUMapMode.READ, 0, byteLength ); + + if ( target === null ) { + + // return a new array buffer and clean up the gpu handles + const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength ); + const result = arrayBuffer.slice(); + readBufferGPU.destroy(); + return result; + + } else if ( target.isReadbackBuffer ) { + + // assign the data to the read back handle + target.buffer = readBufferGPU.getMappedRange( 0, byteLength ); + return target; + + } else { - const arrayBuffer = readBufferGPU.getMappedRange(); + // copy the data into the target array buffer + const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength ); + new Uint8Array( target ).set( new Uint8Array( arrayBuffer ) ); + readBufferGPU.destroy(); + return target; - return arrayBuffer; + } } @@ -80155,15 +80181,20 @@ class WebGPUBackend extends Backend { /** * This method performs a readback operation by moving buffer data from - * a storage buffer attribute from the GPU to the CPU. + * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can + * be used to retain and reuse handles to the intermediate buffers and prevent + * new allocation. * * @async - * @param {ReadbackBuffer} readbackBuffer - The readback buffer. - * @return {Promise} A promise that resolves with the buffer data when the data are ready. + * @param {BufferAttribute} attribute - The storage buffer attribute to read frm. + * @param {number} count - The offset from which to start reading the + * @param {number} offset - The storage buffer attribute. + * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute. + * @return {Promise} A promise that resolves with the buffer data when the data are ready. */ - async getArrayBufferAsync( readbackBuffer ) { + async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) { - return await this.attributeUtils.getArrayBufferAsync( readbackBuffer ); + return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count ); } @@ -81438,20 +81469,17 @@ class WebGPUBackend extends Backend { for ( let i = 0; i < drawCount; i ++ ) { - const count = 1; - const firstInstance = i; - if ( hasIndex === true ) { - passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance ); + passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i ); } else { - passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance ); + passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i ); } - info.update( object, counts[ i ], count ); + info.update( object, counts[ i ], 1 ); } @@ -82964,6 +82992,81 @@ class PostProcessing extends RenderPipeline { } +/** + * A readback buffer is used to transfer data from the GPU to the CPU. + * It is primarily used to read back compute shader results. + * + * @augments EventDispatcher + */ +class ReadbackBuffer extends EventDispatcher { + + /** + * Constructs a new readback buffer. + * + * @param {number} maxByteLength - The maximum size of the buffer to be read back. + */ + constructor( maxByteLength ) { + + super(); + + /** + * Name used for debugging purposes. + * + * @type {string} + */ + this.name = ''; + + /** + * The mapped, read back array buffer. + * + * @type {ArrayBuffer|null} + */ + this.buffer = null; + + /** + * The maximum size of the buffer to be read back. + * + * @type {number} + */ + this.maxByteLength = maxByteLength; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isReadbackBuffer = true; + + this._mapped = false; + + } + + /** + * Releases the mapped buffer data so the GPU buffer can be + * used by the GPU again. + * + * Note: Any `ArrayBuffer` data associated with this readback buffer + * are removed and no longer accessible after calling this method. + */ + release() { + + this.dispatchEvent( { type: 'release' } ); + + } + + /** + * Frees internal resources. + */ + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + /** * This special type of texture is intended for compute shaders. * It can be used to compute the data of a texture with a compute shader. @@ -83459,6 +83562,24 @@ class NodeObjectLoader extends ObjectLoader { } + /** + * Async version of {@link NodeObjectLoader#parse}. + * + * @param {Object} json - The JSON definition + * @return {Promise} A Promise that resolves with the parsed 3D object. + */ + async parseAsync( json ) { + + this._nodesJSON = json.nodes; + + const data = await super.parseAsync( json ); + + this._nodesJSON = null; // dispose + + return data; + + } + /** * Parses the node objects from the given JSON and textures. * diff --git a/build/three.webgpu.nodes.min.js b/build/three.webgpu.nodes.min.js index fedd349c8e8eb8..763ac428260c87 100644 --- a/build/three.webgpu.nodes.min.js +++ b/build/three.webgpu.nodes.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2026 Three.js Authors * SPDX-License-Identifier: MIT */ -import{Color as e,Vector2 as t,Vector3 as r,Vector4 as s,Matrix2 as i,Matrix3 as n,Matrix4 as a,error as o,EventDispatcher as u,MathUtils as l,warn as d,WebGLCoordinateSystem as c,WebGPUCoordinateSystem as h,ColorManagement as p,SRGBTransfer as g,NoToneMapping as m,StaticDrawUsage as f,InterleavedBufferAttribute as y,InterleavedBuffer as b,DynamicDrawUsage as x,NoColorSpace as T,log as _,warnOnce as v,Texture as N,UnsignedIntType as S,IntType as R,Compatibility as E,LessCompare as A,LessEqualCompare as w,GreaterCompare as C,GreaterEqualCompare as M,NearestFilter as B,Sphere as F,BackSide as L,DoubleSide as P,CubeTexture as D,CubeReflectionMapping as U,CubeRefractionMapping as I,TangentSpaceNormalMap as O,NoNormalPacking as V,NormalRGPacking as k,NormalGAPacking as G,ObjectSpaceNormalMap as z,RGFormat as $,RED_GREEN_RGTC2_Format as W,RG11_EAC_Format as H,InstancedBufferAttribute as q,InstancedInterleavedBuffer as j,DataArrayTexture as X,FloatType as K,FramebufferTexture as Q,LinearMipmapLinearFilter as Y,DepthTexture as Z,Material as J,LineBasicMaterial as ee,LineDashedMaterial as te,NoBlending as re,MeshNormalMaterial as se,SRGBColorSpace as ie,RenderTarget as ne,BoxGeometry as ae,Mesh as oe,Scene as ue,LinearFilter as le,CubeCamera as de,EquirectangularReflectionMapping as ce,EquirectangularRefractionMapping as he,AddOperation as pe,MixOperation as ge,MultiplyOperation as me,MeshBasicMaterial as fe,MeshLambertMaterial as ye,MeshPhongMaterial as be,DataTexture as xe,HalfFloatType as Te,ClampToEdgeWrapping as _e,BufferGeometry as ve,OrthographicCamera as Ne,PerspectiveCamera as Se,LinearSRGBColorSpace as Re,RGBAFormat as Ee,CubeUVReflectionMapping as Ae,BufferAttribute as we,MeshStandardMaterial as Ce,MeshPhysicalMaterial as Me,MeshToonMaterial as Be,MeshMatcapMaterial as Fe,SpriteMaterial as Le,PointsMaterial as Pe,ShadowMaterial as De,Uint32BufferAttribute as Ue,Uint16BufferAttribute as Ie,ByteType as Oe,UnsignedByteType as Ve,ShortType as ke,UnsignedShortType as Ge,AlphaFormat as ze,RedFormat as $e,RedIntegerFormat as We,DepthFormat as He,DepthStencilFormat as qe,RGIntegerFormat as je,RGBFormat as Xe,RGBIntegerFormat as Ke,UnsignedShort4444Type as Qe,UnsignedShort5551Type as Ye,UnsignedInt248Type as Ze,UnsignedInt5999Type as Je,UnsignedInt101111Type as et,NormalBlending as tt,SrcAlphaFactor as rt,OneMinusSrcAlphaFactor as st,AddEquation as it,MaterialBlending as nt,Object3D as at,LinearMipMapLinearFilter as ot,Plane as ut,Float32BufferAttribute as lt,UVMapping as dt,PCFShadowMap as ct,PCFSoftShadowMap as ht,VSMShadowMap as pt,BasicShadowMap as gt,CubeDepthTexture as mt,SphereGeometry as ft,LinearMipmapNearestFilter as yt,NearestMipmapLinearFilter as bt,Float16BufferAttribute as xt,yieldToMain as Tt,REVISION as _t,ArrayCamera as vt,PlaneGeometry as Nt,FrontSide as St,CustomBlending as Rt,ZeroFactor as Et,CylinderGeometry as At,Quaternion as wt,WebXRController as Ct,RAD2DEG as Mt,FrustumArray as Bt,Frustum as Ft,RGBAIntegerFormat as Lt,TimestampQuery as Pt,createCanvasElement as Dt,ReverseSubtractEquation as Ut,SubtractEquation as It,OneMinusDstAlphaFactor as Ot,OneMinusDstColorFactor as Vt,OneMinusSrcColorFactor as kt,DstAlphaFactor as Gt,DstColorFactor as zt,SrcAlphaSaturateFactor as $t,SrcColorFactor as Wt,OneFactor as Ht,CullFaceNone as qt,CullFaceBack as jt,CullFaceFront as Xt,MultiplyBlending as Kt,SubtractiveBlending as Qt,AdditiveBlending as Yt,NotEqualDepth as Zt,GreaterDepth as Jt,GreaterEqualDepth as er,EqualDepth as tr,LessEqualDepth as rr,LessDepth as sr,AlwaysDepth as ir,NeverDepth as nr,ReversedDepthFuncs as ar,RGB_S3TC_DXT1_Format as or,RGBA_S3TC_DXT1_Format as ur,RGBA_S3TC_DXT3_Format as lr,RGBA_S3TC_DXT5_Format as dr,RGB_PVRTC_4BPPV1_Format as cr,RGB_PVRTC_2BPPV1_Format as hr,RGBA_PVRTC_4BPPV1_Format as pr,RGBA_PVRTC_2BPPV1_Format as gr,RGB_ETC1_Format as mr,RGB_ETC2_Format as fr,RGBA_ETC2_EAC_Format as yr,R11_EAC_Format as br,SIGNED_R11_EAC_Format as xr,SIGNED_RG11_EAC_Format as Tr,RGBA_ASTC_4x4_Format as _r,RGBA_ASTC_5x4_Format as vr,RGBA_ASTC_5x5_Format as Nr,RGBA_ASTC_6x5_Format as Sr,RGBA_ASTC_6x6_Format as Rr,RGBA_ASTC_8x5_Format as Er,RGBA_ASTC_8x6_Format as Ar,RGBA_ASTC_8x8_Format as wr,RGBA_ASTC_10x5_Format as Cr,RGBA_ASTC_10x6_Format as Mr,RGBA_ASTC_10x8_Format as Br,RGBA_ASTC_10x10_Format as Fr,RGBA_ASTC_12x10_Format as Lr,RGBA_ASTC_12x12_Format as Pr,RGBA_BPTC_Format as Dr,RED_RGTC1_Format as Ur,SIGNED_RED_RGTC1_Format as Ir,SIGNED_RED_GREEN_RGTC2_Format as Or,MirroredRepeatWrapping as Vr,RepeatWrapping as kr,NearestMipmapNearestFilter as Gr,NotEqualCompare as zr,EqualCompare as $r,AlwaysCompare as Wr,NeverCompare as Hr,LinearTransfer as qr,getByteLength as jr,isTypedArray as Xr,NotEqualStencilFunc as Kr,GreaterStencilFunc as Qr,GreaterEqualStencilFunc as Yr,EqualStencilFunc as Zr,LessEqualStencilFunc as Jr,LessStencilFunc as es,AlwaysStencilFunc as ts,NeverStencilFunc as rs,DecrementWrapStencilOp as ss,IncrementWrapStencilOp as is,DecrementStencilOp as ns,IncrementStencilOp as as,InvertStencilOp as os,ReplaceStencilOp as us,ZeroStencilOp as ls,KeepStencilOp as ds,MaxEquation as cs,MinEquation as hs,SpotLight as ps,PointLight as gs,DirectionalLight as ms,RectAreaLight as fs,AmbientLight as ys,HemisphereLight as bs,LightProbe as xs,LinearToneMapping as Ts,ReinhardToneMapping as _s,CineonToneMapping as vs,ACESFilmicToneMapping as Ns,AgXToneMapping as Ss,NeutralToneMapping as Rs,Group as Es,Loader as As,FileLoader as ws,MaterialLoader as Cs,ObjectLoader as Ms}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,BezierInterpolant,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,ConstantAlphaFactor,ConstantColorFactor,Controls,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CustomToneMapping,Cylindrical,Data3DTexture,DataTextureLoader,DataUtils,DefaultLoadingManager,DetachedBindMode,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,Euler,ExternalTexture,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HTMLTexture,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,InterpolateBezier,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,KeyframeTrack,LOD,LatheGeometry,Layers,Light,Line,Line3,LineCurve,LineCurve3,LineLoop,LineSegments,LinearInterpolant,LinearMipMapNearestFilter,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,MeshDepthMaterial,MeshDistanceMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NormalAnimationBlendMode,NumberKeyframeTrack,OctahedronGeometry,OneMinusConstantAlphaFactor,OneMinusConstantColorFactor,Path,PlaneHelper,PointLightHelper,Points,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBADepthPacking,RGBDepthPacking,RGB_BPTC_SIGNED_Format,RGB_BPTC_UNSIGNED_Format,RGDepthPacking,RawShaderMaterial,Ray,Raycaster,RenderTarget3D,RingGeometry,ShaderMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Spherical,SphericalHarmonics3,SplineCurve,SpotLightHelper,Sprite,StaticCopyUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,Timer,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding,getConsoleFunction,setConsoleFunction}from"./three.core.min.js";const Bs=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],Fs=new WeakMap,Ls=new WeakMap,Ps=new WeakMap;class Ds{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Bs,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:r,object:s}=e;if(t={geometryId:r.id,worldMatrix:s.matrixWorld.clone()},s.center&&(t.center=s.center.clone()),s.morphTargetInfluences&&(t.morphTargetInfluences=s.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),e.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={id:s.id,version:s.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=Ps.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Ps.set(e,t)),t}getMaterialData(e){let t=Ls.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:s.version}:t[r]=s.clone():t[r]=s)}Ls.set(e,t)}return t}equals(e,t,r){const{object:s,material:i,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(s.matrixWorld))return a.worldMatrix.copy(s.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==r){o._renderId=r;for(const e in o){const t=o[e],r=i[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),o._equal=!1,!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,o._equal=!1,!1}else if(t!==r)return o[e]=r,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:r}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==r)return a.bufferWidth=t,a.bufferHeight=r,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==r){u._renderId=r;const e=n.attributes,t=u.attributes;let s=0,i=0;for(const t in e)s++;for(const r in t){i++;const s=t[r],n=e[r];if(void 0===n)return delete t[r],u._equal=!1,!1;if(s.id!==n.id||s.version!==n.version)return s.id=n.id,s.version=n.version,u._equal=!1,!1}if(i!==s)return u.attributes=this.getAttributesData(e),u._equal=!1,!1;const a=n.index,o=u.indexId,l=u.indexVersion,d=a?a.id:null,c=a?a.version:null;if(o!==d||l!==c)return u.indexId=d,u.indexVersion=c,u._equal=!1,!1;if(u.drawRange.start!==n.drawRange.start||u.drawRange.count!==n.drawRange.count)return u.drawRange.start=n.drawRange.start,u.drawRange.count=n.drawRange.count,u._equal=!1,!1;u._equal=!0}else if(!1===u._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t{const r=e.match(t);if(!r)return null;const s=r[1]||r[2]||"",i=r[3].split("?")[0],n=parseInt(r[4],10),a=parseInt(r[5],10);return{fn:s,file:i.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Us.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Os(e,t=0){let r=3735928559^t,s=1103547991^t;if(Array.isArray(e))for(let t,i=0;i>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const Vs=e=>Os(e),ks=e=>Os(e),Gs=(...e)=>Os(e),zs=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),$s=new WeakMap;function Ws(e){return zs.get(e)}function Hs(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function qs(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function js(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Xs(e){return/float|int|uint/.test(e)?4:/vec2/.test(e)?8:/vec3/.test(e)||/vec4/.test(e)?16:/mat2/.test(e)?8:/mat3/.test(e)||/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Ks(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 Qs(o,...u){const l=o?o.slice(-4):void 0;return 1===u.length&&("vec2"===l?u=[u[0],u[0]]:"vec3"===l?u=[u[0],u[0],u[0]]:"vec4"===l&&(u=[u[0],u[0],u[0],u[0]])),"color"===o?new e(...u):"vec2"===l?new t(...u):"vec3"===l?new r(...u):"vec4"===l?new s(...u):"mat2"===l?new i(...u):"mat3"===l?new n(...u):"mat4"===l?new a(...u):"bool"===o?u[0]||!1:"float"===o||"int"===o||"uint"===o?u[0]||0:"string"===o?u[0]||"":"ArrayBuffer"===o?Js(u[0]):null}function Ys(e){let t=$s.get(e);return void 0===t&&(t={},$s.set(e,t)),t}function Zs(e){let t="";const r=new Uint8Array(e);for(let e=0;ee.charCodeAt(0)).buffer}var ei=Object.freeze({__proto__:null,arrayBufferToBase64:Zs,base64ToArrayBuffer:Js,getAlignmentFromType:Xs,getDataFromObject:Ys,getLengthFromType:qs,getMemoryLengthFromType:js,getTypeFromLength:Ws,getTypedArrayFromType:Hs,getValueFromType:Qs,getValueType:Ks,hash:Gs,hashArray:ks,hashString:Vs});const ti={VERTEX:"vertex",FRAGMENT:"fragment"},ri={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},si={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},ii={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ni=["fragment","vertex"],ai=["setup","analyze","generate"],oi=[...ni,"compute"],ui=["x","y","z","w"],li={analyze:"setup",generate:"analyze"};let di=0;class ci extends u{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ri.NONE,this.updateBeforeType=ri.NONE,this.updateAfterType=ri.NONE,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=di++,this.stackTrace=null,!0===ci.captureStackTrace&&(this.stackTrace=new Is)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=l.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,ri.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ri.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ri.OBJECT)}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 r of Object.getOwnPropertyNames(this)){const s=this[r];if(!0!==r.startsWith("_")&&!e.has(s))if(!0===Array.isArray(s))for(let e=0;e0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}ci.captureStackTrace=!1;class hi extends ci{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 pi extends ci{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class gi extends ci{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 r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class mi extends gi{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,r)=>t+e.getTypeLength(r.getNodeType(e)),0))}generate(e,t){const r=this.getNodeType(e),s=e.getTypeLength(r),i=this.nodes,n=e.getComponentType(r),a=[];let u=0;for(const t of i){if(u>=s){o(`TSL: Length of parameters exceeds maximum length of function '${r}()' type.`,this.stackTrace);break}let i,l=t.getNodeType(e),d=e.getTypeLength(l);u+d>s&&(o(`TSL: Length of '${r}()' data exceeds maximum length of output type.`,this.stackTrace),d=s-u,l=e.getTypeFromLength(d)),u+=d,i=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(d,n);i=e.format(i,l,t)}a.push(i)}const l=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(l,r,t)}}const fi=ui.join("");class yi extends ci{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(ui.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 r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===fi.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class bi extends gi{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");ci.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Si?Si.assign(this,...e):o("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Is),this;{const t=Ri.get("assign");return this.addToStack(t(...e))}},ci.prototype.toVarIntent=function(){return this},ci.prototype.get=function(e){return new Ni(this,e)};const wi={};function Ci(e,t,r){wi[e]=wi[t]=wi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new yi(this,e),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();ci.prototype["set"+s]=ci.prototype["set"+i]=ci.prototype["set"+n]=function(t){const r=Ai(e);return new bi(this,r,tn(t))},ci.prototype["flip"+s]=ci.prototype["flip"+i]=ci.prototype["flip"+n]=function(){const t=Ai(e);return new xi(this,t)}}const Mi=["x","y","z","w"],Bi=["r","g","b","a"],Fi=["s","t","p","q"];for(let e=0;e<4;e++){let t=Mi[e],r=Bi[e],s=Fi[e];Ci(t,r,s);for(let i=0;i<4;i++){t=Mi[e]+Mi[i],r=Bi[e]+Bi[i],s=Fi[e]+Fi[i],Ci(t,r,s);for(let n=0;n<4;n++){t=Mi[e]+Mi[i]+Mi[n],r=Bi[e]+Bi[i]+Bi[n],s=Fi[e]+Fi[i]+Fi[n],Ci(t,r,s);for(let a=0;a<4;a++)t=Mi[e]+Mi[i]+Mi[n]+Mi[a],r=Bi[e]+Bi[i]+Bi[n]+Bi[a],s=Fi[e]+Fi[i]+Fi[n]+Fi[a],Ci(t,r,s)}}}for(let e=0;e<32;e++)wi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new hi(this,new vi(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};Object.defineProperties(ci.prototype,wi);const Li=new WeakMap,Pi=function(e,t=null){for(const r in e)e[r]=tn(e[r],t);return e},Di=function(e,t=null){const r=e.length;for(let s=0;su?(o(`TSL: "${r}" parameter length exceeds limit.`,new Is),t.slice(0,u)):t}return null===t?n=(...t)=>i(new e(...nn(d(t)))):null!==r?(r=tn(r),n=(...s)=>i(new e(t,...nn(d(s)),r))):n=(...r)=>i(new e(t,...nn(d(r)))),n.setParameterLength=(...e)=>(1===e.length?a=u=e[0]:2===e.length&&([a,u]=e),n),n.setName=e=>(l=e,n),n},Ii=function(e,...t){return new e(...nn(t))};class Oi extends ci{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:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let u=null;if(t.layout){let s=Li.get(e.constructor);void 0===s&&(s=new WeakMap,Li.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=tn(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i);const n=r?function(e){let t;sn(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(r):null;u=tn(i.call(n))}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return sn(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield tn(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof ci&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=tn(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,o=n||a.length>1?a(i,s):a(s);u=tn(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(s[n]=u),u}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return e.fnCall=o,r}}class Vi extends ci{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 Oi(this,e)}setup(){return this.call()}}const ki=[!1,!0],Gi=[0,1,2,3],zi=[-1,-2],$i=[.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],Wi=new Map;for(const e of ki)Wi.set(e,new vi(e));const Hi=new Map;for(const e of Gi)Hi.set(e,new vi(e,"uint"));const qi=new Map([...Hi].map(e=>new vi(e.value,"int")));for(const e of zi)qi.set(e,new vi(e,"int"));const ji=new Map([...qi].map(e=>new vi(e.value)));for(const e of $i)ji.set(e,new vi(e));for(const e of $i)ji.set(-e,new vi(-e));const Xi={bool:Wi,uint:Hi,ints:qi,float:ji},Ki=new Map([...Wi,...ji]),Qi=(e,t)=>Ki.has(e)?Ki.get(e):!0===e.isNode?e:new vi(e,t),Yi=function(e,t=null){return(...r)=>{for(const t of r)if(void 0===t)return o(`TSL: Invalid parameter for the type "${e}".`,new Is),new vi(0,e);if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(r=[Qs(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return rn(t.get(r[0]));if(1===r.length){const t=Qi(r[0],e);return t.nodeType===e?rn(t):rn(new pi(t,e))}const s=r.map(e=>Qi(e));return rn(new mi(s,e))}};function Zi(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}const Ji=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function en(e,t){return new Vi(e,t)}const tn=(e,t=null)=>function(e,t=null){const r=Ks(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?tn(Qi(e,t)):"shader"===r?e.isFn?e:cn(e):e}(e,t),rn=(e,t=null)=>tn(e,t).toVarIntent(),sn=(e,t=null)=>new Pi(e,t),nn=(e,t=null)=>new Di(e,t),an=(e,t=null,r=null,s=null)=>new Ui(e,t,r,s),on=(e,...t)=>new Ii(e,...t),un=(e,t=null,r=null,s={})=>new Ui(e,t,r,{...s,intent:!0});let ln=0;class dn extends ci{constructor(e,t=null){super();let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:o("TSL: Invalid layout type.",new Is),t=null)),this.shaderNode=new en(e,r),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+ln++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}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 o('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function cn(e,t=null){const r=new dn(e,t);return new Proxy(()=>{},{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const hn=e=>{Si=e},pn=()=>Si,gn=(...e)=>Si.If(...e);function mn(e){return Si&&Si.addToStack(e),e}Ei("toStack",mn);const fn=new Yi("color"),yn=new Yi("float",Xi.float),bn=new Yi("int",Xi.ints),xn=new Yi("uint",Xi.uint),Tn=new Yi("bool",Xi.bool),_n=new Yi("vec2"),vn=new Yi("ivec2"),Nn=new Yi("uvec2"),Sn=new Yi("bvec2"),Rn=new Yi("vec3"),En=new Yi("ivec3"),An=new Yi("uvec3"),wn=new Yi("bvec3"),Cn=new Yi("vec4"),Mn=new Yi("ivec4"),Bn=new Yi("uvec4"),Fn=new Yi("bvec4"),Ln=new Yi("mat2"),Pn=new Yi("mat3"),Dn=new Yi("mat4");Ei("toColor",fn),Ei("toFloat",yn),Ei("toInt",bn),Ei("toUint",xn),Ei("toBool",Tn),Ei("toVec2",_n),Ei("toIVec2",vn),Ei("toUVec2",Nn),Ei("toBVec2",Sn),Ei("toVec3",Rn),Ei("toIVec3",En),Ei("toUVec3",An),Ei("toBVec3",wn),Ei("toVec4",Cn),Ei("toIVec4",Mn),Ei("toUVec4",Bn),Ei("toBVec4",Fn),Ei("toMat2",Ln),Ei("toMat3",Pn),Ei("toMat4",Dn);const Un=an(hi).setParameterLength(2),In=(e,t)=>new pi(tn(e),t);Ei("element",Un),Ei("convert",In);Ei("append",e=>(d("TSL: .append() has been renamed to .toStack().",new Is),mn(e)));class On extends ci{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1){super(e),this.name=t,this.varying=r,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Vs(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Vn=(e,t)=>new On(e,t),kn=(e,t)=>new On(e,t,!0),Gn=on(On,"vec4","DiffuseColor"),zn=on(On,"vec3","DiffuseContribution"),$n=on(On,"vec3","EmissiveColor"),Wn=on(On,"float","Roughness"),Hn=on(On,"float","Metalness"),qn=on(On,"float","Clearcoat"),jn=on(On,"float","ClearcoatRoughness"),Xn=on(On,"vec3","Sheen"),Kn=on(On,"float","SheenRoughness"),Qn=on(On,"float","Iridescence"),Yn=on(On,"float","IridescenceIOR"),Zn=on(On,"float","IridescenceThickness"),Jn=on(On,"float","AlphaT"),ea=on(On,"float","Anisotropy"),ta=on(On,"vec3","AnisotropyT"),ra=on(On,"vec3","AnisotropyB"),sa=on(On,"color","SpecularColor"),ia=on(On,"color","SpecularColorBlended"),na=on(On,"float","SpecularF90"),aa=on(On,"float","Shininess"),oa=on(On,"vec4","Output"),ua=on(On,"float","dashSize"),la=on(On,"float","gapSize"),da=on(On,"float","pointWidth"),ca=on(On,"float","IOR"),ha=on(On,"float","Transmission"),pa=on(On,"float","Thickness"),ga=on(On,"float","AttenuationDistance"),ma=on(On,"color","AttenuationColor"),fa=on(On,"float","Dispersion");class ya extends ci{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1,s=null){super("string"),this.name=e,this.shared=t,this.order=r,this.updateType=s,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 ba=(e,t=1,r=null)=>new ya(e,!1,t,r),xa=(e,t=0,r=null)=>new ya(e,!0,t,r),Ta=xa("frame",0,ri.FRAME),_a=xa("render",0,ri.RENDER),va=ba("object",1,ri.OBJECT);class Na extends Ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=va}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const r=e(t,this);void 0!==r&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const Sa=(e,t)=>{const r=Ji(t||e);if(r===e&&(e=Qs(r)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new Na(e,r)};class Ra extends gi{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,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 Ea=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Ra(null,r.length,r)}else{const r=e[0],s=e[1];t=new Ra(r,s)}return tn(t)};Ei("toArray",(e,t)=>Ea(Array(t).fill(e)));class Aa extends gi{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 r=e.getTypeLength(t.node.getNodeType(e));return ui.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getDataFromNode(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t{const s=r.type;let i;return i="pointer"===s?"&"+t.build(e):t.build(e,s),i};if(Array.isArray(i)){if(i.length>s.length)o("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=s.length;else if(i.length(t=t.length>1||t[0]&&!0===t[0].isNode?nn(t):sn(t[0]),new Ca(tn(e),t));Ei("call",Ma);const Ba={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Fa extends gi{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new Fa(e,t,r);for(let t=0;t>"===r||"<<"===r)return e.getIntegerType(n);if("!"===r||"&&"===r||"||"===r||"^^"===r)return"bool";if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),l=i?i.build(e,o):null,d=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===c;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${r} ${l} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${l} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(d)return e.format(`${d}( ${u}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${l}`,n,t);{let i=`( ${u} ${r} ${l} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return d?e.format(`${d}( ${u}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${r} ${u}`,n,t):e.format(`${u} ${r} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const La=un(Fa,"+").setParameterLength(2,1/0).setName("add"),Pa=un(Fa,"-").setParameterLength(2,1/0).setName("sub"),Da=un(Fa,"*").setParameterLength(2,1/0).setName("mul"),Ua=un(Fa,"/").setParameterLength(2,1/0).setName("div"),Ia=un(Fa,"%").setParameterLength(2).setName("mod"),Oa=un(Fa,"==").setParameterLength(2).setName("equal"),Va=un(Fa,"!=").setParameterLength(2).setName("notEqual"),ka=un(Fa,"<").setParameterLength(2).setName("lessThan"),Ga=un(Fa,">").setParameterLength(2).setName("greaterThan"),za=un(Fa,"<=").setParameterLength(2).setName("lessThanEqual"),$a=un(Fa,">=").setParameterLength(2).setName("greaterThanEqual"),Wa=un(Fa,"&&").setParameterLength(2,1/0).setName("and"),Ha=un(Fa,"||").setParameterLength(2,1/0).setName("or"),qa=un(Fa,"!").setParameterLength(1).setName("not"),ja=un(Fa,"^^").setParameterLength(2).setName("xor"),Xa=un(Fa,"&").setParameterLength(2).setName("bitAnd"),Ka=un(Fa,"~").setParameterLength(1).setName("bitNot"),Qa=un(Fa,"|").setParameterLength(2).setName("bitOr"),Ya=un(Fa,"^").setParameterLength(2).setName("bitXor"),Za=un(Fa,"<<").setParameterLength(2).setName("shiftLeft"),Ja=un(Fa,">>").setParameterLength(2).setName("shiftRight"),eo=cn(([e])=>(e.addAssign(1),e)),to=cn(([e])=>(e.subAssign(1),e)),ro=cn(([e])=>{const t=bn(e).toConst();return e.addAssign(1),t}),so=cn(([e])=>{const t=bn(e).toConst();return e.subAssign(1),t});Ei("add",La),Ei("sub",Pa),Ei("mul",Da),Ei("div",Ua),Ei("mod",Ia),Ei("equal",Oa),Ei("notEqual",Va),Ei("lessThan",ka),Ei("greaterThan",Ga),Ei("lessThanEqual",za),Ei("greaterThanEqual",$a),Ei("and",Wa),Ei("or",Ha),Ei("not",qa),Ei("xor",ja),Ei("bitAnd",Xa),Ei("bitNot",Ka),Ei("bitOr",Qa),Ei("bitXor",Ya),Ei("shiftLeft",Za),Ei("shiftRight",Ja),Ei("incrementBefore",eo),Ei("decrementBefore",to),Ei("increment",ro),Ei("decrement",so);const io=(e,t)=>(d('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Is),Ia(bn(e),bn(t)));Ei("modInt",io);class no extends gi{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===no.MAX||e===no.MIN)&&arguments.length>3){let i=new no(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}generateNodeType(e){const t=this.method;return t===no.LENGTH||t===no.DISTANCE||t===no.DOT?"float":t===no.CROSS?"vec3":t===no.ALL||t===no.ANY?"bool":t===no.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===no.ONE_MINUS)i=Pa(1,t);else if(s===no.RECIPROCAL)i=Ua(1,t);else if(s===no.DIFFERENCE)i=Vo(Pa(t,r));else if(s===no.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=Cn(Rn(n),0):s=Cn(Rn(s),0);const a=Da(s,n).xyz;i=Ro(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===no.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const l=[];return r===no.CROSS?l.push(n.build(e,s),a.build(e,s)):u===c&&r===no.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==c||r!==no.MIN&&r!==no.MAX?r===no.REFRACT?l.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===no.MIX?l.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===h&&r===no.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==no.DFDX&&r!==no.DFDY||(d(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),r="/*"+r+"*/"),l.push(n.build(e,i)),null!==a&&l.push(a.build(e,i)),null!==o&&l.push(o.build(e,i))):l.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${l.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}no.ALL="all",no.ANY="any",no.RADIANS="radians",no.DEGREES="degrees",no.EXP="exp",no.EXP2="exp2",no.LOG="log",no.LOG2="log2",no.SQRT="sqrt",no.INVERSE_SQRT="inversesqrt",no.FLOOR="floor",no.CEIL="ceil",no.NORMALIZE="normalize",no.FRACT="fract",no.SIN="sin",no.SINH="sinh",no.COS="cos",no.COSH="cosh",no.TAN="tan",no.TANH="tanh",no.ASIN="asin",no.ASINH="asinh",no.ACOS="acos",no.ACOSH="acosh",no.ATAN="atan",no.ATANH="atanh",no.ABS="abs",no.SIGN="sign",no.LENGTH="length",no.NEGATE="negate",no.ONE_MINUS="oneMinus",no.DFDX="dFdx",no.DFDY="dFdy",no.ROUND="round",no.RECIPROCAL="reciprocal",no.TRUNC="trunc",no.FWIDTH="fwidth",no.TRANSPOSE="transpose",no.DETERMINANT="determinant",no.INVERSE="inverse",no.EQUALS="equals",no.MIN="min",no.MAX="max",no.STEP="step",no.REFLECT="reflect",no.DISTANCE="distance",no.DIFFERENCE="difference",no.DOT="dot",no.CROSS="cross",no.POW="pow",no.TRANSFORM_DIRECTION="transformDirection",no.MIX="mix",no.CLAMP="clamp",no.REFRACT="refract",no.SMOOTHSTEP="smoothstep",no.FACEFORWARD="faceforward";const ao=yn(1e-6),oo=yn(1e6),uo=yn(Math.PI),lo=yn(2*Math.PI),co=yn(2*Math.PI),ho=yn(.5*Math.PI),po=un(no,no.ALL).setParameterLength(1),go=un(no,no.ANY).setParameterLength(1),mo=un(no,no.RADIANS).setParameterLength(1),fo=un(no,no.DEGREES).setParameterLength(1),yo=un(no,no.EXP).setParameterLength(1),bo=un(no,no.EXP2).setParameterLength(1),xo=un(no,no.LOG).setParameterLength(1),To=un(no,no.LOG2).setParameterLength(1),_o=un(no,no.SQRT).setParameterLength(1),vo=un(no,no.INVERSE_SQRT).setParameterLength(1),No=un(no,no.FLOOR).setParameterLength(1),So=un(no,no.CEIL).setParameterLength(1),Ro=un(no,no.NORMALIZE).setParameterLength(1),Eo=un(no,no.FRACT).setParameterLength(1),Ao=un(no,no.SIN).setParameterLength(1),wo=un(no,no.SINH).setParameterLength(1),Co=un(no,no.COS).setParameterLength(1),Mo=un(no,no.COSH).setParameterLength(1),Bo=un(no,no.TAN).setParameterLength(1),Fo=un(no,no.TANH).setParameterLength(1),Lo=un(no,no.ASIN).setParameterLength(1),Po=un(no,no.ASINH).setParameterLength(1),Do=un(no,no.ACOS).setParameterLength(1),Uo=un(no,no.ACOSH).setParameterLength(1),Io=un(no,no.ATAN).setParameterLength(1,2),Oo=un(no,no.ATANH).setParameterLength(1),Vo=un(no,no.ABS).setParameterLength(1),ko=un(no,no.SIGN).setParameterLength(1),Go=un(no,no.LENGTH).setParameterLength(1),zo=un(no,no.NEGATE).setParameterLength(1),$o=un(no,no.ONE_MINUS).setParameterLength(1),Wo=un(no,no.DFDX).setParameterLength(1),Ho=un(no,no.DFDY).setParameterLength(1),qo=un(no,no.ROUND).setParameterLength(1),jo=un(no,no.RECIPROCAL).setParameterLength(1),Xo=un(no,no.TRUNC).setParameterLength(1),Ko=un(no,no.FWIDTH).setParameterLength(1),Qo=un(no,no.TRANSPOSE).setParameterLength(1),Yo=un(no,no.DETERMINANT).setParameterLength(1),Zo=un(no,no.INVERSE).setParameterLength(1),Jo=un(no,no.MIN).setParameterLength(2,1/0),eu=un(no,no.MAX).setParameterLength(2,1/0),tu=un(no,no.STEP).setParameterLength(2),ru=un(no,no.REFLECT).setParameterLength(2),su=un(no,no.DISTANCE).setParameterLength(2),iu=un(no,no.DIFFERENCE).setParameterLength(2),nu=un(no,no.DOT).setParameterLength(2),au=un(no,no.CROSS).setParameterLength(2),ou=un(no,no.POW).setParameterLength(2),uu=e=>Da(e,e),lu=e=>Da(e,e,e),du=e=>Da(e,e,e,e),cu=un(no,no.TRANSFORM_DIRECTION).setParameterLength(2),hu=e=>Da(ko(e),ou(Vo(e),1/3)),pu=e=>nu(e,e),gu=un(no,no.MIX).setParameterLength(3),mu=(e,t=0,r=1)=>new no(no.CLAMP,tn(e),tn(t),tn(r)),fu=e=>mu(e),yu=un(no,no.REFRACT).setParameterLength(3),bu=un(no,no.SMOOTHSTEP).setParameterLength(3),xu=un(no,no.FACEFORWARD).setParameterLength(3),Tu=cn(([e])=>{const t=nu(e.xy,_n(12.9898,78.233)),r=Ia(t,uo);return Eo(Ao(r).mul(43758.5453))}),_u=(e,t,r)=>gu(t,r,e),vu=(e,t,r)=>bu(t,r,e),Nu=(e,t)=>tu(t,e),Su=xu,Ru=vo;Ei("all",po),Ei("any",go),Ei("radians",mo),Ei("degrees",fo),Ei("exp",yo),Ei("exp2",bo),Ei("log",xo),Ei("log2",To),Ei("sqrt",_o),Ei("inverseSqrt",vo),Ei("floor",No),Ei("ceil",So),Ei("normalize",Ro),Ei("fract",Eo),Ei("sin",Ao),Ei("sinh",wo),Ei("cos",Co),Ei("cosh",Mo),Ei("tan",Bo),Ei("tanh",Fo),Ei("asin",Lo),Ei("asinh",Po),Ei("acos",Do),Ei("acosh",Uo),Ei("atan",Io),Ei("atanh",Oo),Ei("abs",Vo),Ei("sign",ko),Ei("length",Go),Ei("lengthSq",pu),Ei("negate",zo),Ei("oneMinus",$o),Ei("dFdx",Wo),Ei("dFdy",Ho),Ei("round",qo),Ei("reciprocal",jo),Ei("trunc",Xo),Ei("fwidth",Ko),Ei("min",Jo),Ei("max",eu),Ei("step",Nu),Ei("reflect",ru),Ei("distance",su),Ei("dot",nu),Ei("cross",au),Ei("pow",ou),Ei("pow2",uu),Ei("pow3",lu),Ei("pow4",du),Ei("transformDirection",cu),Ei("mix",_u),Ei("clamp",mu),Ei("refract",yu),Ei("smoothstep",vu),Ei("faceForward",xu),Ei("difference",iu),Ei("saturate",fu),Ei("cbrt",hu),Ei("transpose",Qo),Ei("determinant",Yo),Ei("inverse",Zo),Ei("rand",Tu);class Eu extends ci{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}generateNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode,r=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?Vn(r).build(e):"";s.nodeProperty=l;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(c,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=n.build(e,r);if(h&&(u?h=l+" = "+h+";":(h="return "+h+";",null===o&&(d("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,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Au=an(Eu).setParameterLength(2,3);Ei("select",Au);class wu extends ci{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const r=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(r),s}}const Cu=(e=null,t={})=>{let r=e;return null!==r&&!0===r.isNode||(t=r||t,r=null),new wu(r,t)},Mu=e=>Cu(e,{uniformFlow:!0}),Bu=(e,t)=>Cu(e,{nodeName:t});function Fu(e,t,r=null){return Cu(r,{getShadow:({light:r,shadowColorNode:s})=>t===r?s.mul(e):s})}function Lu(e,t=null){return Cu(t,{getAO:(t,{material:r})=>!0===r.transparent?t:null!==t?t.mul(e):e})}function Pu(e,t){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),Bu(e,t)}Ei("context",Cu),Ei("label",Pu),Ei("uniformFlow",Mu),Ei("setName",Bu),Ei("builtinShadowContext",(e,t,r)=>Fu(t,r,e)),Ei("builtinAOContext",(e,t)=>Lu(t,e));class Du extends ci{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const r=t.getBaseStack();e?r.addToStackBefore(this):r.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,u=!1;s&&(a=e.isDeterministic(t),u=n?s:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&o('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const d=e.getVectorType(l),c=t.build(e,d),h=e.getVarFromNode(this,r,d,void 0,u),p=e.getPropertyName(h);let g=p;if(u)if(n)g=a?`const ${p}`:`let ${p}`;else{const r=t.getArrayCount(e);g=`const ${e.getVar(h.type,p,r)}`}return e.addLineFlowCode(`${g} = ${c}`,this),p}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Uu=an(Du),Iu=(e,t=null)=>Uu(e,t).toStack(),Ou=(e,t=null)=>Uu(e,t,!0).toStack(),Vu=e=>Uu(e).setIntent(!0).toStack();Ei("toVar",Iu),Ei("toConst",Ou),Ei("toVarIntent",Vu);class ku extends ci{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),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 r=this.node.build(e,...t);return e.removeSubBuild(),r}}const Gu=(e,t,r=null)=>new ku(tn(e),t,r);class zu extends ci{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Gu(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 r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=Gu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,ti.VERTEX);e.flowNodeFromShaderStage(ti.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const $u=an(zu).setParameterLength(1,2),Wu=e=>$u(e);Ei("toVarying",$u),Ei("toVertexStage",Wu);const Hu=cn(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return gu(t,r,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),qu=cn(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return gu(t,r,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ju="WorkingColorSpace";class Xu extends gi{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===ju?p.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==p.enabled&&r!==s&&r&&s?(p.getTransfer(r)===g&&(i=Cn(Hu(i.rgb),i.a)),p.getPrimaries(r)!==p.getPrimaries(s)&&(i=Cn(Pn(p._getMatrix(new n,r,s)).mul(i.rgb),i.a)),p.getTransfer(s)===g&&(i=Cn(qu(i.rgb),i.a)),i):i}}const Ku=(e,t)=>new Xu(tn(e),ju,t),Qu=(e,t)=>new Xu(tn(e),t,ju);Ei("workingToColorSpace",Ku),Ei("colorSpaceToWorking",Qu);let Yu=class extends hi{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),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class Zu extends ci{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=ri.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Yu(this,tn(e))}setNodeType(e){const t=Sa(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 r=e[t[0]];for(let e=1;enew Ju(e,t,r);class tl extends gi{static get type(){return"ToneMappingNode"}constructor(e,t=sl,r=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Gs(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,r=this._toneMapping;if(r===m)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=Cn(i(t.rgb,this.exposureNode),t.a):(o("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const rl=(e,t,r)=>new tl(e,tn(t),tn(r)),sl=el("toneMappingExposure","float");Ei("toneMapping",(e,t,r)=>rl(t,r,e));const il=new WeakMap;function nl(e,t){let r=il.get(e);return void 0===r&&(r=new b(e,t),il.set(e,r)),r}class al extends Ti{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=f,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.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),r=e.getTypeLength(t),s=this.value,i=this.bufferStride||r,n=this.bufferOffset;let a;a=!0===s.isInterleavedBuffer?s:!0===s.isBufferAttribute?nl(s.array,i):nl(s,i);const o=new y(a,r,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(r);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=s,i=s;else{i=$u(this).build(e,t)}return i}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 ol(e,t=null,r=0,s=0,i=f,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Pn(new al(e,"vec3",9,0).setUsage(i).setInstanced(n),new al(e,"vec3",9,3).setUsage(i).setInstanced(n),new al(e,"vec3",9,6).setUsage(i).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Dn(new al(e,"vec4",16,0).setUsage(i).setInstanced(n),new al(e,"vec4",16,4).setUsage(i).setInstanced(n),new al(e,"vec4",16,8).setUsage(i).setInstanced(n),new al(e,"vec4",16,12).setUsage(i).setInstanced(n)):new al(e,t,r,s).setUsage(i)}const ul=(e,t=null,r=0,s=0)=>ol(e,t,r,s),ll=(e,t=null,r=0,s=0)=>ol(e,t,r,s,f,!0),dl=(e,t=null,r=0,s=0)=>ol(e,t,r,s,x,!0);Ei("toAttribute",e=>ul(e.value));class cl extends ci{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===cl.VERTEX)s=e.getVertexIndex();else if(r===cl.INSTANCE)s=e.getInstanceIndex();else if(r===cl.DRAW)s=e.getDrawIndex();else if(r===cl.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===cl.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==cl.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=$u(this).build(e,t)}return i}}cl.VERTEX="vertex",cl.INSTANCE="instance",cl.SUBGROUP="subgroup",cl.INVOCATION_LOCAL="invocationLocal",cl.INVOCATION_SUBGROUP="invocationSubgroup",cl.DRAW="draw";const hl=on(cl,cl.VERTEX),pl=on(cl,cl.INSTANCE),gl=on(cl,cl.SUBGROUP),ml=on(cl,cl.INVOCATION_SUBGROUP),fl=on(cl,cl.INVOCATION_LOCAL),yl=on(cl,cl.DRAW);class bl extends ci{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=ri.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=Sa(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:r}=e;if("compute"===r){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"),r=pl.build(e,"uint");e.flow.code=`${e.tab}if ( ${r} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const xl=(e,t=[64])=>{(0===t.length||t.length>3)&&o("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Is);for(let e=0;e{const s=xl(e,r);return"number"==typeof t?s.count=t:s.dispatchSize=t,s};Ei("compute",Tl),Ei("computeKernel",xl);class _l extends ci{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(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vl=e=>new _l(tn(e));function Nl(e,t=!0){return d('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vl(e).setParent(t)}Ei("cache",Nl),Ei("isolate",vl);class Sl extends ci{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)}}const Rl=an(Sl).setParameterLength(2);Ei("bypass",Rl);const El=cn(([e,t,r,s=yn(0),i=yn(1),n=Tn(!1)])=>{let a=e.sub(t).div(r.sub(t));return Zi(n)&&(a=a.clamp()),a.mul(i.sub(s)).add(s)});function Al(e,t,r,s=yn(0),i=yn(1)){return El(e,t,r,s,i,!0)}Ei("remap",El),Ei("remapClamp",Al);class wl extends ci{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Cl=an(wl).setParameterLength(1,2),Ml=e=>(e?Au(e,Cl("discard")):Cl("discard")).toStack();Ei("discard",Ml);class Bl extends gi{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||m,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||T;return r!==m&&(t=t.toneMapping(r)),s!==T&&s!==p.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Fl=(e,t=null,r=null)=>new Bl(tn(e),t,r);Ei("renderOutput",Fl);class Ll extends gi{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,r=this.node.build(e);if(null!==t)t(e,r);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(t.length);let i="";i+="// #"+t+"#\n",i+=e.flow.code.replace(/^\t/gm,"")+"\n",i+="/* ... */ "+r+" /* ... */\n",i+="// #"+s+"#\n",_(i)}return r}}const Pl=(e,t=null)=>new Ll(tn(e),t).toStack();Ei("debug",Pl);class Dl extends u{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Ul extends ci{static get type(){return"InspectorNode"}constructor(e,t="",r=null){super(),this.node=e,this.name=t,this.callback=r,this.updateType=ri.FRAME,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!==Dl&&v('TSL: ".toInspector()" is only available with WebGPU.'),t}}function Il(e,t="",r=null){return(e=tn(e)).before(new Ul(e,t,r))}Ei("toInspector",Il);class Ol extends ci{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 r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return $u(this).build(e,r)}return d(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Vl=(e,t=null)=>new Ol(e,t),kl=(e=0)=>Vl("uv"+(e>0?e:""),"vec2");class Gl extends ci{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const zl=an(Gl).setParameterLength(1,2);class $l extends Na{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ri.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const Wl=an($l).setParameterLength(1);class Hl extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const ql=new N;class jl extends Na{static get type(){return"TextureNode"}constructor(e=ql,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ri.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===S?"uvec4":this.value.type===R?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return kl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Sa(this.value.matrix)),this._matrixUniform.mul(Rn(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Sa(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(bn(zl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Hl("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const s=cn(()=>{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?ri.OBJECT:ri.NONE,t})();let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(E.TEXTURE_COMPARE))n=this.compareNode;else{const e=r.compareFunction;null===e||e===A||e===w||e===C||e===M?a=this.compareNode:(n=this.compareNode,v('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;let d;return d=i?e.generateTextureBias(l,t,r,i,n,u):o?e.generateTextureGrad(l,t,r,o,n,u):a?e.generateTextureCompare(l,t,r,a,n,u):!1===this.sampler?e.generateTextureLoad(l,t,r,s,n,u):s?e.generateTextureLevel(l,t,r,s,n,u):e.generateTexture(l,t,r,n,u),d}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:u,biasNode:l,compareNode:d,compareStepNode:c,depthNode:h,gradNode:p,offsetNode:g}=s,m=this.generateUV(e,t),f=u?u.build(e,"float"):null,y=l?l.build(e,"float"):null,b=h?h.build(e,"int"):null,x=d?d.build(e,"float"):null,T=c?c.build(e,"float"):null,_=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,v=g?this.generateOffset(e,g):null;let N=b;null===N&&r.isArrayTexture&&!0!==this.isTexture3DNode&&(N="0");const S=e.getVarFromNode(this);o=e.getPropertyName(S);let R=this.generateSnippet(e,i,m,f,y,N,x,_,v);if(null!==T){const t=r.compareFunction;R=t===C||t===M?tu(Cl(R,a),Cl(T,"float")).build(e,a):tu(Cl(T,"float"),Cl(R,a)).build(e,a)}e.addLineFlowCode(`${o} = ${R}`,this),n.snippet=R,n.propertyName=o}let u=o;return e.needsToWorkingColorSpace(r)&&(u=Qu(Cl(u,a),r.colorSpace).setup(e).build(e,a)),e.format(u,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=tn(e),t.referenceNode=this.getBase(),tn(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=tn(e).mul(Wl(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===B||r.magFilter===B)&&(d("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),tn(t)}level(e){const t=this.clone();return t.levelNode=tn(e),t.referenceNode=this.getBase(),tn(t)}size(e){return zl(this,e)}bias(e){const t=this.clone();return t.biasNode=tn(e),t.referenceNode=this.getBase(),tn(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=tn(e),t.referenceNode=this.getBase(),tn(t)}grad(e,t){const r=this.clone();return r.gradNode=[tn(e),tn(t)],r.referenceNode=this.getBase(),tn(r)}depth(e){const t=this.clone();return t.depthNode=tn(e),t.referenceNode=this.getBase(),tn(t)}offset(e){const t=this.clone();return t.offsetNode=tn(e),t.referenceNode=this.getBase(),tn(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 r=this._flipYUniform;null!==r&&(r.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const Xl=an(jl).setParameterLength(1,4).setName("texture"),Kl=(e=ql,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=tn(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=Xl(e,t,r,s),i},Ql=(...e)=>Kl(...e).setSampler(!1);class Yl extends Na{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r,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 Zl=(e,t,r)=>new Yl(e,t,r);class Jl extends hi{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(e),s=this.node.getPaddedType();return e.format(t,s,r)}}class ed extends Yl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ks(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ri.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rnew ed(e,t);class rd extends ci{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const sd=an(rd).setParameterLength(1);let id,nd;class ad extends ci{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===ad.DPR?"float":this.scope===ad.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ri.NONE;return this.scope!==ad.SIZE&&this.scope!==ad.VIEWPORT&&this.scope!==ad.DPR||(e=ri.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===ad.VIEWPORT?null!==t?nd.copy(t.viewport):(e.getViewport(nd),nd.multiplyScalar(e.getPixelRatio())):this.scope===ad.DPR?this._output.value=e.getPixelRatio():null!==t?(id.width=t.width,id.height=t.height):e.getDrawingBufferSize(id)}setup(){const e=this.scope;let r=null;return r=e===ad.SIZE?Sa(id||(id=new t)):e===ad.VIEWPORT?Sa(nd||(nd=new s)):e===ad.DPR?Sa(1):_n(dd.div(ld)),this._output=r,r}generate(e){if(this.scope===ad.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(ld).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}ad.COORDINATE="coordinate",ad.VIEWPORT="viewport",ad.SIZE="size",ad.UV="uv",ad.DPR="dpr";const od=on(ad,ad.DPR),ud=on(ad,ad.UV),ld=on(ad,ad.SIZE),dd=on(ad,ad.COORDINATE),cd=on(ad,ad.VIEWPORT),hd=cd.zw,pd=dd.sub(cd.xy),gd=pd.div(hd),md=cn(()=>(d('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new Is),ld),"vec2").once()();let fd=null,yd=null,bd=null,xd=null,Td=null,_d=null,vd=null,Nd=null,Sd=null,Rd=null,Ed=null,Ad=null,wd=null,Cd=null;const Md=Sa(0,"uint").setName("u_cameraIndex").setGroup(xa("cameraIndex")).toVarying("v_cameraIndex"),Bd=Sa("float").setName("cameraNear").setGroup(_a).onRenderUpdate(({camera:e})=>e.near),Fd=Sa("float").setName("cameraFar").setGroup(_a).onRenderUpdate(({camera:e})=>e.far),Ld=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);null===yd?yd=td(r).setGroup(_a).setName("cameraProjectionMatrices"):yd.array=r,t=yd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrix")}else null===fd&&(fd=Sa(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=fd;return t}).once()(),Pd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);null===xd?xd=td(r).setGroup(_a).setName("cameraProjectionMatricesInverse"):xd.array=r,t=xd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrixInverse")}else null===bd&&(bd=Sa(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=bd;return t}).once()(),Dd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);null===_d?_d=td(r).setGroup(_a).setName("cameraViewMatrices"):_d.array=r,t=_d.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraViewMatrix")}else null===Td&&(Td=Sa(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=Td;return t}).once()(),Ud=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);null===Nd?Nd=td(r).setGroup(_a).setName("cameraWorldMatrices"):Nd.array=r,t=Nd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraWorldMatrix")}else null===vd&&(vd=Sa(e.matrixWorld).setName("cameraWorldMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=vd;return t}).once()(),Id=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);null===Rd?Rd=td(r).setGroup(_a).setName("cameraNormalMatrices"):Rd.array=r,t=Rd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraNormalMatrix")}else null===Sd&&(Sd=Sa(e.normalMatrix).setName("cameraNormalMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.normalMatrix)),t=Sd;return t}).once()(),Od=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t{const r=e.cameras,s=t.array;for(let e=0,t=r.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=Ed;return t}).once()(),Vd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);null===Cd?Cd=td(r,"vec4").setGroup(_a).setName("cameraViewports"):Cd.array=r,t=Cd.element(Md).toConst("cameraViewport")}else null===wd&&(wd=Cn(0,0,ld.x,ld.y).toConst("cameraViewport")),t=wd;return t}).once()(),kd=new F;class Gd extends ci{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ri.OBJECT,this.uniformNode=new Na(null)}generateNodeType(){const e=this.scope;return e===Gd.WORLD_MATRIX?"mat4":e===Gd.POSITION||e===Gd.VIEW_POSITION||e===Gd.DIRECTION||e===Gd.SCALE?"vec3":e===Gd.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Gd.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gd.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gd.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gd.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===Gd.VIEW_POSITION){const i=e.camera;s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Gd.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),kd.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=kd.radius}}generate(e){const t=this.scope;return t===Gd.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Gd.POSITION||t===Gd.VIEW_POSITION||t===Gd.DIRECTION||t===Gd.SCALE?this.uniformNode.nodeType="vec3":t===Gd.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}}Gd.WORLD_MATRIX="worldMatrix",Gd.POSITION="position",Gd.SCALE="scale",Gd.VIEW_POSITION="viewPosition",Gd.DIRECTION="direction",Gd.RADIUS="radius";const zd=an(Gd,Gd.DIRECTION).setParameterLength(1),$d=an(Gd,Gd.WORLD_MATRIX).setParameterLength(1),Wd=an(Gd,Gd.POSITION).setParameterLength(1),Hd=an(Gd,Gd.SCALE).setParameterLength(1),qd=an(Gd,Gd.VIEW_POSITION).setParameterLength(1),jd=an(Gd,Gd.RADIUS).setParameterLength(1);class Xd extends Gd{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Kd=on(Xd,Xd.DIRECTION),Qd=on(Xd,Xd.WORLD_MATRIX),Yd=on(Xd,Xd.POSITION),Zd=on(Xd,Xd.SCALE),Jd=on(Xd,Xd.VIEW_POSITION),ec=on(Xd,Xd.RADIUS),tc=Sa(new n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),rc=Sa(new a).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),sc=cn(e=>e.context.modelViewMatrix||ic).once()().toVar("modelViewMatrix"),ic=Dd.mul(Qd),nc=cn(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Sa("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),ac=cn(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Sa("mat3").onObjectUpdate(({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),oc=cn(e=>"fragment"!==e.shaderStage?(v("TSL: `clipSpace` is only available in fragment stage."),Cn()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),uc=Vl("position","vec3"),lc=uc.toVarying("positionLocal"),dc=uc.toVarying("positionPrevious"),cc=cn(e=>Qd.mul(lc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),hc=cn(()=>lc.transformDirection(Qd).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),pc=cn(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Pd.mul(oc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),gc=cn(e=>{let t;return t=e.camera.isOrthographicCamera?Rn(0,0,1):pc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class mc extends ci{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===L?"false":e.getFrontFacing()}}const fc=on(mc),yc=yn(fc).mul(2).sub(1),bc=cn(([e],{material:t})=>{const r=t.side;return r===L?e=e.mul(-1):r===P&&(e=e.mul(yc)),e}),xc=Vl("normal","vec3"),Tc=cn(e=>!1===e.geometry.hasAttribute("normal")?(d('TSL: Vertex attribute "normal" not found on geometry.'),Rn(0,1,0)):xc,"vec3").once()().toVar("normalLocal"),_c=pc.dFdx().cross(pc.dFdy()).normalize().toVar("normalFlat"),vc=cn(e=>{let t;return t=e.isFlatShading()?_c:wc(Tc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Nc=cn(e=>{let t=vc.transformDirection(Dd);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Sc=cn(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=vc,!0!==e.isFlatShading()&&(t=bc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Rc=Sc.transformDirection(Dd).toVar("normalWorld"),Ec=cn(({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Sc:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Ac=cn(([e,t=Qd])=>{const r=Pn(t),s=e.div(Rn(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz}),wc=cn(([e],t)=>{const r=t.context.modelNormalViewMatrix;if(r)return r.transformDirection(e);const s=tc.mul(e);return Dd.transformDirection(s)}),Cc=cn(()=>(d('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Sc)).once(["NORMAL","VERTEX"])(),Mc=cn(()=>(d('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Rc)).once(["NORMAL","VERTEX"])(),Bc=cn(()=>(d('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ec)).once(["NORMAL","VERTEX"])(),Fc=new a,Lc=Sa(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Pc=Sa(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Dc=Sa(new a).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const r=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?Fc.makeRotationFromEuler(r).transpose():Fc.identity(),Fc}),Uc=gc.negate().reflect(Sc),Ic=gc.negate().refract(Sc,Lc),Oc=Uc.transformDirection(Dd).toVar("reflectVector"),Vc=Ic.transformDirection(Dd).toVar("reflectVector"),kc=new D;class Gc extends jl{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===U?Oc:e.mapping===I?Vc:(o('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Rn(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!0===r.isDepthTexture?e.renderer.coordinateSystem===h?Rn(t.x,t.y.negate(),t.z):t:(t=Dc.mul(t),e.renderer.coordinateSystem!==h&&r.isRenderTargetTexture||(t=Rn(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const zc=an(Gc).setParameterLength(1,4).setName("cubeTexture"),$c=(e=kc,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=tn(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=zc(e,t,r,s),i};class Wc extends hi{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),r=this.referenceNode.getNodeType(e),s=this.getNodeType(e);return e.format(t,r,s)}}class Hc extends ci{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=ri.OBJECT}element(e){return new Wc(this,tn(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Zl(null,e,this.count):Array.isArray(this.getValueFromReference())?td(null,e):"texture"===e?Kl(null):"cubeTexture"===e?$c(null):Sa(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 r=e[t[0]];for(let e=1;enew Hc(e,t,r),jc=(e,t,r,s)=>new Hc(e,t,s,r);class Xc extends Hc{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Kc=(e,t,r=null)=>new Xc(e,t,r),Qc=kl(),Yc=pc.dFdx(),Zc=pc.dFdy(),Jc=Qc.dFdx(),eh=Qc.dFdy(),th=Sc,rh=Zc.cross(th),sh=th.cross(Yc),ih=rh.mul(Jc.x).add(sh.mul(eh.x)),nh=rh.mul(Jc.y).add(sh.mul(eh.y)),ah=ih.dot(ih).max(nh.dot(nh)),oh=ah.equal(0).select(0,ah.inverseSqrt()),uh=ih.mul(oh).toVar("tangentViewFrame"),lh=nh.mul(oh).toVar("bitangentViewFrame"),dh=Vl("tangent","vec4"),ch=dh.xyz.toVar("tangentLocal"),hh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?sc.mul(Cn(ch,0)).xyz.toVarying("v_tangentView").normalize():uh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ph=hh.transformDirection(Dd).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),gh=cn(([e,t],r)=>{let s=e.mul(dh.w).xyz;return"NORMAL"===r.subBuildFn&&!0!==r.isFlatShading()&&(s=s.toVarying(t)),s}).once(["NORMAL"]),mh=gh(xc.cross(dh),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),fh=gh(Tc.cross(ch),"v_bitangentLocal").normalize().toVar("bitangentLocal"),yh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?gh(Sc.cross(hh),"v_bitangentView").normalize():lh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),bh=gh(Rc.cross(ph),"v_bitangentWorld").normalize().toVar("bitangentWorld"),xh=Pn(hh,yh,Sc).toVar("TBNViewMatrix"),Th=gc.mul(xh),_h=cn(()=>{let e=ra.cross(gc);return e=e.cross(ra).normalize(),e=gu(e,Sc,ea.mul(Wn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),vh=e=>tn(e).mul(.5).add(.5),Nh=e=>Rn(e,_o(fu(yn(1).sub(nu(e,e)))));class Sh extends gi{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=O,this.unpackNormalMode=V}setup(e){const{normalMapType:t,scaleNode:r,unpackNormalMode:s}=this;let i=this.node.mul(2).sub(1);if(t===O?s===k?i=Nh(i.xy):s===G?i=Nh(i.yw):s!==V&&o(`THREE.NodeMaterial: Unexpected unpack normal mode: ${s}`):s!==V&&o(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${s}'`),null!==r){let t=r;!0===e.isFlatShading()&&(t=bc(t)),i=Rn(i.xy.mul(t),i.z)}let n=null;return t===z?n=wc(i):t===O?n=xh.mul(i).normalize():(o(`NodeMaterial: Unsupported normal map type: ${t}`),n=Sc),n}}const Rh=an(Sh).setParameterLength(1,2),Eh=cn(({textureNode:e,bumpScale:t})=>{const r=t=>e.isolate().context({getUV:e=>t(e.uvNode||kl()),forceUVContext:!0}),s=yn(r(e=>e));return _n(yn(r(e=>e.add(e.dFdx()))).sub(s),yn(r(e=>e.add(e.dFdy()))).sub(s)).mul(t)}),Ah=cn(e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(yc),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()});class wh extends gi{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Eh({textureNode:this.textureNode,bumpScale:e});return Ah({surf_pos:pc,surf_norm:Sc,dHdxy:t})}}const Ch=an(wh).setParameterLength(1,2),Mh=new Map;class Bh extends ci{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Mh.get(e);return void 0===r&&(r=Kc(e,t),Mh.set(e,r)),r}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,r=this.scope;let s=null;if(r===Bh.COLOR){const e=void 0!==t.color?this.getColor(r):Rn();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Bh.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Bh.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:yn(1);else if(r===Bh.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Bh.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Bh.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Bh.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Bh.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Bh.NORMAL)t.normalMap?(s=Rh(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType,t.normalMap.format!=$&&t.normalMap.format!=W&&t.normalMap.format!=H||(s.unpackNormalMode=k)):s=t.bumpMap?Ch(this.getTexture("bump").r,this.getFloat("bumpScale")):Sc;else if(r===Bh.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Rh(this.getTexture(r),this.getCache(r+"Scale","vec2")):Sc;else if(r===Bh.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Bh.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(1e-4,1)}else if(r===Bh.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=Ln(mp.x,mp.y,mp.y.negate(),mp.x).mul(e.rg.mul(2).sub(_n(1)).normalize().mul(e.b))}else s=mp;else if(r===Bh.IRIDESCENCE_THICKNESS){const e=qc("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=qc("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Bh.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Bh.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Bh.IOR)s=this.getFloat(r);else if(r===Bh.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Bh.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Bh.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):yn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Bh.ALPHA_TEST="alphaTest",Bh.COLOR="color",Bh.OPACITY="opacity",Bh.SHININESS="shininess",Bh.SPECULAR="specular",Bh.SPECULAR_STRENGTH="specularStrength",Bh.SPECULAR_INTENSITY="specularIntensity",Bh.SPECULAR_COLOR="specularColor",Bh.REFLECTIVITY="reflectivity",Bh.ROUGHNESS="roughness",Bh.METALNESS="metalness",Bh.NORMAL="normal",Bh.CLEARCOAT="clearcoat",Bh.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Bh.CLEARCOAT_NORMAL="clearcoatNormal",Bh.EMISSIVE="emissive",Bh.ROTATION="rotation",Bh.SHEEN="sheen",Bh.SHEEN_ROUGHNESS="sheenRoughness",Bh.ANISOTROPY="anisotropy",Bh.IRIDESCENCE="iridescence",Bh.IRIDESCENCE_IOR="iridescenceIOR",Bh.IRIDESCENCE_THICKNESS="iridescenceThickness",Bh.IOR="ior",Bh.TRANSMISSION="transmission",Bh.THICKNESS="thickness",Bh.ATTENUATION_DISTANCE="attenuationDistance",Bh.ATTENUATION_COLOR="attenuationColor",Bh.LINE_SCALE="scale",Bh.LINE_DASH_SIZE="dashSize",Bh.LINE_GAP_SIZE="gapSize",Bh.LINE_WIDTH="linewidth",Bh.LINE_DASH_OFFSET="dashOffset",Bh.POINT_SIZE="size",Bh.DISPERSION="dispersion",Bh.LIGHT_MAP="light",Bh.AO="ao";const Fh=on(Bh,Bh.ALPHA_TEST),Lh=on(Bh,Bh.COLOR),Ph=on(Bh,Bh.SHININESS),Dh=on(Bh,Bh.EMISSIVE),Uh=on(Bh,Bh.OPACITY),Ih=on(Bh,Bh.SPECULAR),Oh=on(Bh,Bh.SPECULAR_INTENSITY),Vh=on(Bh,Bh.SPECULAR_COLOR),kh=on(Bh,Bh.SPECULAR_STRENGTH),Gh=on(Bh,Bh.REFLECTIVITY),zh=on(Bh,Bh.ROUGHNESS),$h=on(Bh,Bh.METALNESS),Wh=on(Bh,Bh.NORMAL),Hh=on(Bh,Bh.CLEARCOAT),qh=on(Bh,Bh.CLEARCOAT_ROUGHNESS),jh=on(Bh,Bh.CLEARCOAT_NORMAL),Xh=on(Bh,Bh.ROTATION),Kh=on(Bh,Bh.SHEEN),Qh=on(Bh,Bh.SHEEN_ROUGHNESS),Yh=on(Bh,Bh.ANISOTROPY),Zh=on(Bh,Bh.IRIDESCENCE),Jh=on(Bh,Bh.IRIDESCENCE_IOR),ep=on(Bh,Bh.IRIDESCENCE_THICKNESS),tp=on(Bh,Bh.TRANSMISSION),rp=on(Bh,Bh.THICKNESS),sp=on(Bh,Bh.IOR),ip=on(Bh,Bh.ATTENUATION_DISTANCE),np=on(Bh,Bh.ATTENUATION_COLOR),ap=on(Bh,Bh.LINE_SCALE),op=on(Bh,Bh.LINE_DASH_SIZE),up=on(Bh,Bh.LINE_GAP_SIZE),lp=on(Bh,Bh.LINE_WIDTH),dp=on(Bh,Bh.LINE_DASH_OFFSET),cp=on(Bh,Bh.POINT_SIZE),hp=on(Bh,Bh.DISPERSION),pp=on(Bh,Bh.LIGHT_MAP),gp=on(Bh,Bh.AO),mp=Sa(new t).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))}),fp=cn(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class yp extends hi{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 r=this.storageBufferNode.structTypeNode;return r?r.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 r;const s=e.context.assign;if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const bp=an(yp).setParameterLength(2);class xp extends Yl{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStruct?(s="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Ws(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=ii.READ_WRITE,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return bp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ii.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=ul(this.value),this._varying=$u(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:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Tp=(e,t=null,r=0)=>new xp(e,t,r);class _p extends ci{static get type(){return"InstanceNode"}constructor(e,t,r=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=r,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=ri.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:r}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:s,isStorageColor:i}=this;if(s&&null===r){if(i)r=Tp(s,"vec3",Math.max(s.count,1)).element(pl);else{const e=new q(s.array,3),t=s.usage===x?dl:ll;this.bufferColor=e,r=Rn(t(e,"vec3",3,0))}this.instanceColorNode=r}const n=t.mul(lc).xyz;if(lc.assign(n),e.needsPreviousData()&&dc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=Ac(Tc,t);Tc.assign(e)}null!==this.instanceColorNode&&kn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(dc).xyz}_createInstanceMatrixNode(e,t){let r;const{instanceMatrix:s}=this,{count:i}=s;if(this.isStorageMatrix)r=Tp(s,"mat4",Math.max(i,1)).element(pl);else{if(16*i*4<=t.getUniformBufferLimit())r=Zl(s.array,"mat4",Math.max(i,1)).element(pl);else{const t=new j(s.array,16,1);!0===e&&(this.buffer=t);const i=s.usage===x?dl:ll,n=[i(t,"vec4",16,0),i(t,"vec4",16,4),i(t,"vec4",16,8),i(t,"vec4",16,12)];r=Dn(...n)}}return r}}const vp=an(_p).setParameterLength(2,3);class Np extends _p{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Sp=an(Np).setParameterLength(1);class Rp extends ci{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=pl:this.batchingIdNode=yl);const t=cn(([e])=>{const t=bn(zl(Ql(this.batchMesh._indirectTexture),0).x).toConst(),r=bn(e).mod(t).toConst(),s=bn(e).div(t).toConst();return Ql(this.batchMesh._indirectTexture,vn(r,s)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(bn(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=bn(zl(Ql(s),0).x).toConst(),n=yn(r).mul(4).toInt().toConst(),a=n.mod(i).toConst(),o=n.div(i).toConst(),u=Dn(Ql(s,vn(a,o)),Ql(s,vn(a.add(1),o)),Ql(s,vn(a.add(2),o)),Ql(s,vn(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=cn(([e])=>{const t=bn(zl(Ql(l),0).x).toConst(),r=e,s=r.mod(t).toConst(),i=r.div(t).toConst();return Ql(l,vn(s,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);kn("vec3","vBatchColor").assign(t)}const d=Pn(u);lc.assign(u.mul(lc));const c=Tc.div(Rn(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Tc.assign(h),e.hasGeometryAttribute("tangent")&&ch.mulAssign(d)}}const Ep=an(Rp).setParameterLength(1),Ap=new WeakMap;class wp extends ci{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=ri.OBJECT,this.skinIndexNode=Vl("skinIndex","uvec4"),this.skinWeightNode=Vl("skinWeight","vec4"),this.bindMatrixNode=qc("bindMatrix","mat4"),this.bindMatrixInverseNode=qc("bindMatrixInverse","mat4"),this.boneMatricesNode=jc("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=lc,this.toPositionNode=lc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w),d=i.mul(t),c=La(a.mul(s.x).mul(d),o.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=Tc,r=ch){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(s.x),u=e.element(s.y),l=e.element(s.z),d=e.element(s.w);let c=La(i.x.mul(o),i.y.mul(u),i.z.mul(l),i.w.mul(d));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(r).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=jc("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,dc)}setup(e){e.needsPreviousData()&&dc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:r}=this.getSkinnedNormalAndTangent();Tc.assign(t),e.hasGeometryAttribute("tangent")&&ch.assign(r)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Ap.get(t)!==e.frameId&&(Ap.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Cp=e=>new wp(e);class Mp extends ci{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 r={};for(let e=0,t=this.params.length-1;eNumber(l)?">=":"<")),a)n=`while ( ${l} )`;else{const r={start:u,end:l},s=r.start,i=r.end;let a;const g=()=>h.includes("<")?"+=":"-=";if(null!=p)switch(typeof p){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=d+" "+g()+" "+e.generateConst(c,p);break;case"string":a=d+" "+p;break;default:p.isNode?a=d+" "+g()+" "+p.build(e):(o("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else p="int"===c||"uint"===c?h.includes("<")?"++":"--":g()+" 1.",a=d+" "+p;n=`for ( ${e.getVar(c,d)+" = "+s}; ${d+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tnew Mp(nn(e,"int")).toStack(),Fp=()=>Cl("break").toStack(),Lp=new WeakMap,Pp=new s,Dp=cn(({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=bn(hl).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ql(e,vn(u,o)).depth(i).xyz.mul(t)});class Up extends ci{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Sa(1),this.updateType=ri.OBJECT}setup(e){const{geometry:r}=e,s=void 0!==r.morphAttributes.position,i=r.hasAttribute("normal")&&void 0!==r.morphAttributes.normal,n=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,a=void 0!==n?n.length:0,{texture:o,stride:u,size:l}=function(e){const r=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=Lp.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===r&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new X(m,h,p,a);f.type=K,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=yn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ql(this.mesh.morphTexture,vn(bn(e).add(1),bn(pl))).r):t.assign(qc("morphTargetInfluences","float").element(e).toVar()),gn(t.notEqual(0),()=>{!0===s&&lc.addAssign(Dp({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(0)})),!0===i&&Tc.addAssign(Dp({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const Ip=an(Up).setParameterLength(1);class Op extends ci{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vp extends Op{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class kp extends wu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=null,s=null){super(e),this.lightingModel=t,this.backdropNode=r,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,r={directDiffuse:Rn().toVar("directDiffuse"),directSpecular:Rn().toVar("directSpecular"),indirectDiffuse:Rn().toVar("indirectDiffuse"),indirectSpecular:Rn().toVar("indirectSpecular")};return{radiance:Rn().toVar("radiance"),irradiance:Rn().toVar("irradiance"),iblIrradiance:Rn().toVar("iblIrradiance"),ambientOcclusion:yn(1).toVar("ambientOcclusion"),reflectedLight:r,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Gp=an(kp);class zp extends Op{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const $p=new t;class Wp extends jl{static get type(){return"ViewportTextureNode"}constructor(e=ud,t=null,r=null){let s=null;null===r?(s=new Q,s.minFilter=Y,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=ri.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;null===i?t.getDrawingBufferSize($p):i.getDrawingBufferSize?i.getDrawingBufferSize($p):$p.set(i.width,i.height);const n=this.getTextureForReference(i);n.image.width===$p.width&&n.image.height===$p.height||(n.image.width=$p.width,n.image.height=$p.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Hp=an(Wp).setParameterLength(0,3),qp=an(Wp,null,null,{generateMipmaps:!0}).setParameterLength(0,3),jp=qp(),Xp=(e=ud,t=null)=>jp.sample(e,t);let Kp=null;class Qp extends Wp{static get type(){return"ViewportDepthTextureNode"}constructor(e=ud,t=null,r=null){null===r&&(null===Kp&&(Kp=new Z),r=Kp),super(e,t,r)}}const Yp=an(Qp).setParameterLength(0,3);class Zp extends ci{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===Zp.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Zp.DEPTH_BASE)null!==r&&(s=ng().assign(r));else if(t===Zp.DEPTH)s=e.isPerspectiveCamera?tg(pc.z,Bd,Fd):Jp(pc.z,Bd,Fd);else if(t===Zp.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=sg(r,Bd,Fd);s=Jp(e,Bd,Fd)}else s=r;else s=Jp(pc.z,Bd,Fd);return s}}Zp.DEPTH_BASE="depthBase",Zp.DEPTH="depth",Zp.LINEAR_DEPTH="linearDepth";const Jp=(e,t,r)=>e.add(t).div(t.sub(r)),eg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?r.sub(t).mul(e).sub(r):t.sub(r).mul(e).sub(t)),tg=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),rg=(e,t,r)=>t.mul(e.add(r)).div(e.mul(t.sub(r))),sg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?t.mul(r).div(t.sub(r).mul(e).sub(t)):t.mul(r).div(r.sub(t).mul(e).sub(r))),ig=(e,t,r)=>{t=t.max(1e-6).toVar();const s=To(e.negate().div(t)),i=To(r.div(t));return s.div(i)},ng=an(Zp,Zp.DEPTH_BASE),ag=on(Zp,Zp.DEPTH),og=an(Zp,Zp.LINEAR_DEPTH).setParameterLength(0,1),ug=og(Yp());ag.assign=e=>ng(e);class lg extends ci{static get type(){return"ClippingNode"}constructor(e=lg.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===lg.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===lg.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return cn(()=>{const r=yn().toVar("distanceToPlane"),s=yn().toVar("distanceToGradient"),i=yn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=td(t).setGroup(_a);Bp(n,({i:t})=>{const n=e.element(t);r.assign(pc.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(bu(s.negate(),s,r))})}const a=e.length;if(a>0){const t=td(e).setGroup(_a),n=yn(1).toVar("intersectionClipOpacity");Bp(a,({i:e})=>{const i=t.element(e);r.assign(pc.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(bu(s.negate(),s,r).oneMinus())}),i.mulAssign(n.oneMinus())}Gn.a.mulAssign(i),Gn.a.equal(0).discard()})()}setupDefault(e,t){return cn(()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=td(t).setGroup(_a);Bp(r,({i:t})=>{const r=e.element(t);pc.dot(r.xyz).greaterThan(r.w).discard()})}const s=e.length;if(s>0){const t=td(e).setGroup(_a),r=Tn(!0).toVar("clipped");Bp(s,({i:e})=>{const s=t.element(e);r.assign(pc.dot(s.xyz).greaterThan(s.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),cn(()=>{const s=td(e).setGroup(_a),i=sd(t.getClipDistance());Bp(r,({i:e})=>{const t=s.element(e),r=pc.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)})})()}}lg.ALPHA_TO_COVERAGE="alphaToCoverage",lg.DEFAULT="default",lg.HARDWARE="hardware";const dg=cn(([e])=>Eo(Da(1e4,Ao(Da(17,e.x).add(Da(.1,e.y)))).mul(La(.1,Vo(Ao(Da(13,e.y).add(e.x))))))),cg=cn(([e])=>dg(_n(dg(e.xy),e.z))),hg=cn(([e])=>{const t=eu(Go(Wo(e.xyz)),Go(Ho(e.xyz))),r=yn(1).div(yn(.05).mul(t)).toVar("pixScale"),s=_n(bo(No(To(r))),bo(So(To(r)))),i=_n(cg(No(s.x.mul(e.xyz))),cg(No(s.y.mul(e.xyz)))),n=Eo(To(r)),a=La(Da(n.oneMinus(),i.x),Da(n,i.y)),o=Jo(n,n.oneMinus()),u=Rn(a.mul(a).div(Da(2,o).mul(Pa(1,o))),a.sub(Da(.5,o)).div(Pa(1,o)),Pa(1,Pa(1,a).mul(Pa(1,a)).div(Da(2,o).mul(Pa(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return mu(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class pg extends Ol{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 r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new s(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const gg=(e=0)=>new pg(e),mg=cn(([e,t])=>Jo(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),fg=cn(([e,t])=>Jo(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yg=cn(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bg=cn(([e,t])=>gu(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),tu(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xg=cn(([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return Cn(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),Tg=cn(([e])=>Cn(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),_g=cn(([e])=>(gn(e.a.equal(0),()=>Cn(0)),Cn(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class vg extends J{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const r=this[t];r&&!0===r.isNode&&e.push({property:t,childNode:r})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:r}of this._getNodeChildren())e.push(Vs(t.slice(0,-4)),r.getCacheKey());return this.type+ks(e)}build(e){this.setup(e)}setupObserver(e){return new Ds(e)}setup(e){e.context.setupNormal=()=>Gu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=this.setupVertex(e),i=Gu(this.vertexNode||s,"VERTEX");let n;e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const i=Cn(s,Gn.a).max(0);n=this.setupOutput(e,i),oa.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&oa.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Cn(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?s=new lg(lg.ALPHA_TO_COVERAGE):e.stack.addToStack(new lg)}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new lg(lg.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?ig(pc.z,Bd,Fd):Jp(pc.z,Bd,Fd))}null!==s&&ag.assign(s).toStack()}setupPositionView(){return sc.mul(lc).xyz}setupModelViewProjection(){return Ld.mul(pc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),fp}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&Ip(t).toStack(),!0===t.isSkinnedMesh&&Cp(t).toStack(),this.displacementMap){const e=Kc("displacementMap","texture"),t=Kc("displacementScale","float"),r=Kc("displacementBias","float");lc.addAssign(Tc.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Ep(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Sp(t).toStack(),null!==this.positionNode&&lc.assign(Gu(this.positionNode,"POSITION","vec3")),lc}setupDiffuseColor(e){const{object:t,geometry:r}=e;null!==this.maskNode&&Tn(this.maskNode).not().discard();let s=this.colorNode?Cn(this.colorNode):Lh;if(!0===this.vertexColors&&r.hasAttribute("color")&&(s=s.mul(gg())),t.instanceColor){s=kn("vec3","vInstanceColor").mul(s)}if(t.isBatchedMesh&&t._colorsTexture){s=kn("vec3","vBatchColor").mul(s)}Gn.assign(s);const i=this.opacityNode?yn(this.opacityNode):Uh;Gn.a.assign(Gn.a.mul(i));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?yn(this.alphaTestNode):Fh,!0===this.alphaToCoverage?(Gn.a=bu(n,n.add(Ko(Gn.a)),Gn.a),Gn.a.lessThanEqual(0).discard()):Gn.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Gn.a.lessThan(hg(lc)).discard(),e.isOpaque()&&Gn.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Rn(0):Gn.rgb}setupNormal(){return this.normalNode?Rn(this.normalNode):Wh}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Kc("envMap","cubeTexture"):Kc("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zp(pp)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);s&&s.isLightingNode&&t.push(s);let i=this.aoNode;null===i&&e.material.aoMap&&(i=gp),e.context.getAO&&(i=e.context.getAO(i,e)),i&&t.push(new Vp(i));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Gp(n,t,r,s)}else null!==r&&(a=Rn(null!==s?gu(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&($n.assign(Rn(i||Dh)),a=a.add($n)),a}setupFog(e,t){const r=e.fogNode;return r&&(oa.assign(t),t=Cn(r.toVar())),t}setupPremultipliedAlpha(e,t){return Tg(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 r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.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 r=J.prototype.toJSON.call(this,e);r.inputNodes={};for(const{property:t,childNode:s}of this._getNodeChildren())r.inputNodes[t]=s.toJSON(e).uuid;function s(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const Ng=new ee;class Sg extends vg{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Ng),this.setValues(e)}}const Rg=new te;class Eg extends vg{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Rg),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?yn(this.offsetNode):dp,t=this.dashScaleNode?yn(this.dashScaleNode):ap,r=this.dashSizeNode?yn(this.dashSizeNode):op,s=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(r),la.assign(s);const i=$u(Vl("lineDistance").mul(t));(e?i.add(e):i).mod(ua.add(la)).greaterThan(ua).discard()}}const Ag=new te;class wg extends vg{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Ag),this.vertexColors=e.vertexColors,this.dashOffset=0,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=re,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.vertexColors,i=this._useDash,n=this._useWorldUnits,a=cn(({start:e,end:t})=>{const r=Ld.element(2).element(2),s=Ld.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return Cn(gu(e.xyz,t.xyz,s),t.w)}).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=cn(()=>{const e=Vl("instanceStart"),t=Vl("instanceEnd"),r=Cn(sc.mul(Cn(e,1))).toVar("start"),s=Cn(sc.mul(Cn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?yn(this.dashScaleNode):ap,t=this.offsetNode?yn(this.offsetNode):dp,r=Vl("instanceDistanceStart"),s=Vl("instanceDistanceEnd");let i=uc.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),kn("float","lineDistance").assign(i)}n&&(kn("vec3","worldStart").assign(r.xyz),kn("vec3","worldEnd").assign(s.xyz));const o=cd.z.div(cd.w),u=Ld.element(2).element(3).equal(-1);gn(u,()=>{gn(r.z.lessThan(0).and(s.z.greaterThan(0)),()=>{s.assign(a({start:r,end:s}))}).ElseIf(s.z.lessThan(0).and(r.z.greaterThanEqual(0)),()=>{r.assign(a({start:s,end:r}))})});const l=Ld.mul(r),d=Ld.mul(s),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const g=Cn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=gu(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=kn("vec4","worldPos");o.assign(uc.y.lessThan(.5).select(r,s));const u=lp.mul(.5);o.addAssign(Cn(uc.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(Cn(uc.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(Cn(a.mul(u),0)),gn(uc.y.greaterThan(1).or(uc.y.lessThan(0)),()=>{o.subAssign(Cn(a.mul(2).mul(u),0))})),g.assign(Ld.mul(o));const l=Rn().toVar();l.assign(uc.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=_n(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(uc.x.lessThan(0).select(e.negate(),e)),gn(uc.y.lessThan(0),()=>{e.assign(e.sub(p))}).ElseIf(uc.y.greaterThan(1),()=>{e.assign(e.add(p))}),e.assign(e.mul(lp)),e.assign(e.div(cd.w.div(od))),g.assign(uc.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(Cn(e,0,0)))}return g})();const o=cn(({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return _n(h,p)});if(this.colorNode=cn(()=>{const e=kl();if(i){const t=this.dashSizeNode?yn(this.dashSizeNode):op,r=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(t),la.assign(r);const s=kn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(ua.add(la)).greaterThan(ua).discard()}const a=yn(1).toVar("alpha");if(n){const e=kn("vec3","worldStart"),s=kn("vec3","worldEnd"),n=kn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:Rn(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(lp);if(!i)if(r&&t.currentSamples>0){const e=h.fwidth();a.assign(bu(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.currentSamples>0){const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1)),s=t.mul(t).add(r.mul(r)),i=yn(s.fwidth()).toVar("dlen");gn(e.y.abs().greaterThan(1),()=>{a.assign(bu(i.oneMinus(),i.add(1),s).oneMinus())})}else gn(e.y.abs().greaterThan(1),()=>{const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1));t.mul(t).add(r.mul(r)).greaterThan(1).discard()});let u;if(this.lineColorNode)u=this.lineColorNode;else if(s){const e=Vl("instanceColorStart"),t=Vl("instanceColorEnd");u=uc.y.lessThan(.5).select(e,t).mul(Lh)}else u=Lh;return Cn(u,a)})(),this.transparent){const e=this.opacityNode?yn(this.opacityNode):Uh;this.outputNode=Cn(this.colorNode.rgb.mul(e).add(Xp().rgb.mul(e.oneMinus())),this.colorNode.a)}super.setup(e)}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}copy(e){return super.copy(e),this.vertexColors=e.vertexColors,this.dashOffset=e.dashOffset,this.lineColorNode=e.lineColorNode,this.offsetNode=e.offsetNode,this.dashScaleNode=e.dashScaleNode,this.dashSizeNode=e.dashSizeNode,this.gapSizeNode=e.gapSizeNode,this._useDash=e._useDash,this._useAlphaToCoverage=e._useAlphaToCoverage,this._useWorldUnits=e._useWorldUnits,this}}const Cg=new se;class Mg extends vg{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Cg),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?yn(this.opacityNode):Uh;Gn.assign(Qu(Cn(vh(Sc),e),ie))}}const Bg=cn(([e=hc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return _n(t,r)});class Fg extends ne{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const r={width:e,height:e,depth:1},s=[r,r,r,r,r,r];this.texture=new D(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=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 i=new ae(5,5,5),n=Bg(hc),a=new vg;a.colorNode=Kl(t,n,0),a.side=L,a.blending=re;const o=new oe(i,a),u=new ue;u.add(o),t.minFilter===Y&&(t.minFilter=le);const l=new de(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.generateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,r=!0,s=!0){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,r,s);e.setRenderTarget(i)}}const Lg=new WeakMap;class Pg extends gi{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=$c(null);const t=new D;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ri.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===ce||r===he){if(Lg.has(e)){const t=Lg.get(e);Ug(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Fg(r.height);s.fromEquirectangularTexture(t,e),Ug(s.texture,e.mapping),this._cubeTexture=s.texture,Lg.set(e,s.texture),e.addEventListener("dispose",Dg)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Dg(e){const t=e.target;t.removeEventListener("dispose",Dg);const r=Lg.get(t);void 0!==r&&(Lg.delete(t),r.dispose())}function Ug(e,t){t===ce?e.mapping=U:t===he&&(e.mapping=I)}const Ig=an(Pg).setParameterLength(1);class Og extends Op{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Ig(this.envNode)}}class Vg extends Op{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=yn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class kg{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Gg extends kg{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(Cn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(Cn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(Gn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case me:s.rgb.assign(gu(s.rgb,s.rgb.mul(i.rgb),kh.mul(Gh)));break;case ge:s.rgb.assign(gu(s.rgb,i.rgb,kh.mul(Gh)));break;case pe:s.rgb.addAssign(i.rgb.mul(kh.mul(Gh)));break;default:d("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const zg=new fe;class $g extends vg{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(zg),this.setValues(e)}setupNormal(){return bc(vc)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Vg(pp)),t}setupOutgoingLight(){return Gn.rgb}setupLightingModel(){return new Gg}}const Wg=cn(({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))}),Hg=cn(e=>e.diffuseColor.mul(1/Math.PI)),qg=cn(({dotNH:e})=>aa.mul(yn(.5)).add(1).mul(yn(1/Math.PI)).mul(e.pow(aa))),jg=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(t).clamp(),s=gc.dot(t).clamp(),i=Wg({f0:sa,f90:1,dotVH:s}),n=yn(.25),a=qg({dotNH:r});return i.mul(n).mul(a)});class Xg extends Gg{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:Gn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(jg({lightDirection:e})).mul(kh))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Kg=new ye;class Qg extends vg{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Kg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg(!1)}}const Yg=new be;class Zg extends vg{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Yg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg}setupVariants(){const e=(this.shininessNode?yn(this.shininessNode):Ph).max(1e-4);aa.assign(e);const t=this.specularNode||Ih;sa.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Jg=cn(e=>{if(!1===e.geometry.hasAttribute("normal"))return yn(0);const t=vc.dFdx().abs().max(vc.dFdy().abs());return t.x.max(t.y).max(t.z)}),em=cn(e=>{const{roughness:t}=e,r=Jg();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s}),tm=cn(({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return Ua(.5,i.add(n).max(ao))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),rm=cn(({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(Rn(e.mul(r),t.mul(s),a).length()),l=a.mul(Rn(e.mul(i),t.mul(n),o).length());return Ua(.5,u.add(l).max(ao))}).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"}]}),sm=cn(({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),im=yn(1/Math.PI),nm=cn(({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=Rn(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return im.mul(n.mul(u.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"}]}),am=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Sc,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(gc).normalize(),d=n.dot(e).clamp(),c=n.dot(gc).clamp(),h=n.dot(l).clamp(),p=gc.dot(l).clamp();let g,m,f=Wg({f0:t,f90:r,dotVH:p});if(Zi(a)&&(f=Qn.mix(f,i)),Zi(o)){const t=ta.dot(e),r=ta.dot(gc),s=ta.dot(l),i=ra.dot(e),n=ra.dot(gc),a=ra.dot(l);g=rm({alphaT:Jn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=nm({alphaT:Jn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=tm({alpha:u,dotNL:d,dotNV:c}),m=sm({alpha:u,dotNH:h});return f.mul(g).mul(m)}),om=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 um=null;const lm=cn(({roughness:e,dotNV:t})=>{null===um&&(um=new xe(om,16,16,$,Te),um.name="DFG_LUT",um.minFilter=le,um.magFilter=le,um.wrapS=_e,um.wrapT=_e,um.generateMipmaps=!1,um.needsUpdate=!0);const r=_n(e,t);return Kl(um,r).rg}),dm=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=am({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),u=Sc.dot(e).clamp(),l=Sc.dot(gc).clamp(),d=lm({roughness:s,dotNV:l}),c=lm({roughness:s,dotNV:u}),h=t.mul(d.x).add(r.mul(d.y)),p=t.mul(c.x).add(r.mul(c.y)),g=d.x.add(d.y),m=c.x.add(c.y),f=yn(1).sub(g),y=yn(1).sub(m),b=t.add(t.oneMinus().mul(.047619)),x=h.mul(p).mul(b).div(yn(1).sub(f.mul(y).mul(b).mul(b)).add(ao)),T=f.mul(y),_=x.mul(T);return o.add(_)}),cm=cn(e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=lm({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))}),hm=cn(({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(Rn(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),pm=cn(({roughness:e,dotNH:t})=>{const r=e.pow2(),s=yn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return yn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),gm=cn(({dotNV:e,dotNL:t})=>yn(1).div(yn(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),mm=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(e).clamp(),s=Sc.dot(gc).clamp(),i=Sc.dot(t).clamp(),n=pm({roughness:Kn,dotNH:i}),a=gm({dotNV:s,dotNL:r});return Xn.mul(n).mul(a)}),fm=cn(({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=_n(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),ym=cn(({f:e})=>{const t=e.length();return eu(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),bm=cn(({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,eu(r.mul(r).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"}]}),xm=cn(({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=Rn().toVar();return gn(d.dot(r.sub(i)).greaterThanEqual(0),()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(Pn(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=Rn(0).toVar();f.addAssign(bm({v1:h,v2:p})),f.addAssign(bm({v1:p,v2:g})),f.addAssign(bm({v1:g,v2:m})),f.addAssign(bm({v1:m,v2:h})),c.assign(Rn(ym({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Tm=cn(({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=Rn().toVar();return gn(o.dot(e.sub(t)).greaterThanEqual(0),()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=Rn(0).toVar();d.addAssign(bm({v1:n,v2:a})),d.addAssign(bm({v1:a,v2:o})),d.addAssign(bm({v1:o,v2:l})),d.addAssign(bm({v1:l,v2:n})),u.assign(Rn(ym({f:d.abs()})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),_m=1/6,vm=e=>Da(_m,Da(e,Da(e,e.negate().add(3)).sub(3)).add(1)),Nm=e=>Da(_m,Da(e,Da(e,Da(3,e).sub(6))).add(4)),Sm=e=>Da(_m,Da(e,Da(e,Da(-3,e).add(3)).add(3)).add(1)),Rm=e=>Da(_m,ou(e,3)),Em=e=>vm(e).add(Nm(e)),Am=e=>Sm(e).add(Rm(e)),wm=e=>La(-1,Nm(e).div(vm(e).add(Nm(e)))),Cm=e=>La(1,Rm(e).div(Sm(e).add(Rm(e)))),Mm=(e,t,r)=>{const s=e.uvNode,i=Da(s,t.zw).add(.5),n=No(i),a=Eo(i),o=Em(a.x),u=Am(a.x),l=wm(a.x),d=Cm(a.x),c=wm(a.y),h=Cm(a.y),p=_n(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=_n(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=_n(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=_n(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Em(a.y).mul(La(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Am(a.y).mul(La(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},Bm=cn(([e,t])=>{const r=_n(e.size(bn(t))),s=_n(e.size(bn(t.add(1)))),i=Ua(1,r),n=Ua(1,s),a=Mm(e,Cn(i,r),No(t)),o=Mm(e,Cn(n,s),So(t));return Eo(t).mix(a,o)}),Fm=cn(([e,t])=>{const r=t.mul(Wl(e));return Bm(e,r)}),Lm=cn(([e,t,r,s,i])=>{const n=Rn(yu(t.negate(),Ro(e),Ua(1,s))),a=Rn(Go(i[0].xyz),Go(i[1].xyz),Go(i[2].xyz));return Ro(n).mul(r.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"}]}),Pm=cn(([e,t])=>e.mul(mu(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Dm=qp(),Um=Xp(),Im=cn(([e,t,r],{material:s})=>{const i=(s.side===L?Dm:Um).sample(e),n=To(ld.x).mul(Pm(t,r));return Bm(i,n)}),Om=cn(([e,t,r])=>(gn(r.notEqual(0),()=>{const s=xo(t).negate().div(r);return yo(s.negate().mul(e))}),Rn(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Vm=cn(([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=Cn().toVar(),f=Rn().toVar();const i=d.sub(1).mul(g.mul(.025)),n=Rn(d.sub(i),d,d.add(i));Bp({start:0,end:3},({i:i})=>{const d=n.element(i),g=Lm(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(Cn(y,1))),x=_n(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(_n(x.x,x.y.oneMinus()));const T=Im(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(Om(Go(g),h,p).element(i)))}),m.a.divAssign(3)}else{const i=Lm(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(Cn(n,1))),y=_n(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(_n(y.x,y.y.oneMinus())),m=Im(y,r,d),f=s.mul(Om(Go(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=Rn(cm({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return Cn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())}),km=Pn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Gm=(e,t)=>e.sub(t).div(e.add(t)).pow2(),zm=cn(({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=gu(e,t,bu(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();gn(a.lessThan(0),()=>Rn(1));const o=a.sqrt(),u=Gm(n,e),l=Wg({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=yn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Rn(1).add(t).div(Rn(1).sub(t))})(i.clamp(0,.9999)),g=Gm(p,n.toVec3()),m=Wg({f0:g,f90:1,dotVH:o}),f=Rn(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=Rn(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(Rn(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Bp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=Rn(54856e-17,44201e-17,52481e-17),i=Rn(1681e3,1795300,2208400),n=Rn(43278e5,93046e5,66121e5),a=yn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=Rn(o.x.add(a),o.y,o.z).div(1.0685e-7),km.mul(o)})(yn(e).mul(y),yn(e).mul(b)).mul(2);v.addAssign(N.mul(t))}),v.max(Rn(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"}]}),$m=cn(({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.mul(r),n=r.add(.1).reciprocal(),a=yn(-1.9362).add(r.mul(1.0678)).add(i.mul(.4573)).sub(n.mul(.8469)),o=yn(-.6014).add(r.mul(.5538)).sub(i.mul(.467)).sub(n.mul(.1255));return a.mul(s).add(o).exp().saturate()}),Wm=Rn(.04),Hm=yn(1);class qm extends kg{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Rn().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Rn().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Rn().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Rn().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Rn().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Sc.dot(gc).clamp(),t=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:sa}),r=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:Gn.rgb});this.iridescenceFresnel=gu(t,r,Hn),this.iridescenceF0Dielectric=hm({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=hm({f:r,f90:1,dotVH:e}),this.iridescenceF0=gu(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Hn)}if(!0===this.transmission){const t=cc,r=Od.sub(cc).normalize(),s=Rc,i=e.context;i.backdrop=Vm(s,r,Wn,zn,ia,na,t,Qd,Dd,Ld,ca,pa,ma,ga,this.dispersion?fa:null),i.backdropAlpha=ha,Gn.a.mulAssign(gu(1,i.backdrop.a,ha))}super.start(e)}computeMultiscattering(e,t,r,s,i=null){const n=Sc.dot(gc).clamp(),a=lm({roughness:Wn,dotNV:n}),o=i?Qn.mix(s,i):s,u=o.mul(a.x).add(r.mul(a.y)),l=a.x.add(a.y).oneMinus(),d=o.add(o.oneMinus().mul(.047619)),c=u.mul(d).div(l.mul(d).oneMinus());e.addAssign(u),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(s.mul(mm({lightDirection:e})));const t=$m({normal:Sc,viewDir:gc,roughness:Kn}),r=$m({normal:Sc,viewDir:e,roughness:Kn}),i=Xn.r.max(Xn.g).max(Xn.b).mul(t.max(r)).oneMinus();s.mulAssign(i)}if(!0===this.clearcoat){const r=Ec.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(am({lightDirection:e,f0:Wm,f90:Hm,roughness:jn,normalView:Ec})))}r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:zn}))),r.directSpecular.addAssign(s.mul(dm({lightDirection:e,f0:ia,f90:1,roughness:Wn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Sc,h=gc,p=pc.toVar(),g=fm({N:c,V:h,roughness:Wn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=Pn(Rn(m.x,0,m.y),Rn(0,1,0),Rn(m.z,0,m.w)).toVar(),b=ia.mul(f.x).add(na.sub(ia).mul(f.y)).toVar();if(i.directSpecular.addAssign(e.mul(b).mul(xm({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(zn).mul(xm({N:c,V:h,P:p,mInv:Pn(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d}))),!0===this.clearcoat){const t=Ec,r=fm({N:t,V:h,roughness:jn}),s=n.sample(r),i=a.sample(r),c=Pn(Rn(s.x,0,s.y),Rn(0,1,0),Rn(s.z,0,s.w)),g=Wm.mul(i.x).add(Hm.sub(Wm).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(g).mul(xm({N:t,V:h,P:p,mInv:c,p0:o,p1:u,p2:l,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context,s=t.mul(Hg({diffuseColor:zn})).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();s.mulAssign(t)}r.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Xn,$m({normal:Sc,viewDir:gc,roughness:Kn}))),!0===this.clearcoat){const e=Ec.dot(gc).clamp(),t=cm({dotNV:e,specularColor:Wm,specularF90:Hm,roughness:jn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Rn().toVar("singleScatteringDielectric"),n=Rn().toVar("multiScatteringDielectric"),a=Rn().toVar("singleScatteringMetallic"),o=Rn().toVar("multiScatteringMetallic");this.computeMultiscattering(i,n,na,sa,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,na,Gn.rgb,this.iridescenceF0Metallic);const u=gu(i,a,Hn),l=gu(n,o,Hn),d=i.add(n),c=zn.mul(d.oneMinus()),h=r.mul(1/Math.PI),p=t.mul(u).add(l.mul(h)).toVar(),g=c.mul(h).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();p.mulAssign(t),g.mulAssign(t)}s.indirectSpecular.addAssign(p),s.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Sc.dot(gc).clamp().add(t),i=Wn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ec.dot(gc).clamp(),r=Wg({dotVH:e,f0:Wm,f90:Hm}),s=t.mul(qn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(qn));t.assign(s)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const jm=yn(1),Xm=yn(-2),Km=yn(.8),Qm=yn(-1),Ym=yn(.4),Zm=yn(2),Jm=yn(.305),ef=yn(3),tf=yn(.21),rf=yn(4),sf=yn(4),nf=yn(16),af=cn(([e])=>{const t=Rn(Vo(e)).toVar(),r=yn(-1).toVar();return gn(t.x.greaterThan(t.z),()=>{gn(t.x.greaterThan(t.y),()=>{r.assign(Au(e.x.greaterThan(0),0,3))}).Else(()=>{r.assign(Au(e.y.greaterThan(0),1,4))})}).Else(()=>{gn(t.z.greaterThan(t.y),()=>{r.assign(Au(e.z.greaterThan(0),2,5))}).Else(()=>{r.assign(Au(e.y.greaterThan(0),1,4))})}),r}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),of=cn(([e,t])=>{const r=_n().toVar();return gn(t.equal(0),()=>{r.assign(_n(e.z,e.y).div(Vo(e.x)))}).ElseIf(t.equal(1),()=>{r.assign(_n(e.x.negate(),e.z.negate()).div(Vo(e.y)))}).ElseIf(t.equal(2),()=>{r.assign(_n(e.x.negate(),e.y).div(Vo(e.z)))}).ElseIf(t.equal(3),()=>{r.assign(_n(e.z.negate(),e.y).div(Vo(e.x)))}).ElseIf(t.equal(4),()=>{r.assign(_n(e.x.negate(),e.z).div(Vo(e.y)))}).Else(()=>{r.assign(_n(e.x,e.y).div(Vo(e.z)))}),Da(.5,r.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),uf=cn(([e])=>{const t=yn(0).toVar();return gn(e.greaterThanEqual(Km),()=>{t.assign(jm.sub(e).mul(Qm.sub(Xm)).div(jm.sub(Km)).add(Xm))}).ElseIf(e.greaterThanEqual(Ym),()=>{t.assign(Km.sub(e).mul(Zm.sub(Qm)).div(Km.sub(Ym)).add(Qm))}).ElseIf(e.greaterThanEqual(Jm),()=>{t.assign(Ym.sub(e).mul(ef.sub(Zm)).div(Ym.sub(Jm)).add(Zm))}).ElseIf(e.greaterThanEqual(tf),()=>{t.assign(Jm.sub(e).mul(rf.sub(ef)).div(Jm.sub(tf)).add(ef))}).Else(()=>{t.assign(yn(-2).mul(To(Da(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),lf=cn(([e,t])=>{const r=e.toVar();r.assign(Da(2,r).sub(1));const s=Rn(r,1).toVar();return gn(t.equal(0),()=>{s.assign(s.zyx)}).ElseIf(t.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),df=cn(([e,t,r,s,i,n])=>{const a=yn(r),o=Rn(t),u=mu(uf(a),Xm,n),l=Eo(u),d=No(u),c=Rn(cf(e,o,d,s,i,n)).toVar();return gn(l.notEqual(0),()=>{const t=Rn(cf(e,o,d.add(1),s,i,n)).toVar();c.assign(gu(c,t,l))}),c}),cf=cn(([e,t,r,s,i,n])=>{const a=yn(r).toVar(),o=Rn(t),u=yn(af(o)).toVar(),l=yn(eu(sf.sub(a),0)).toVar();a.assign(eu(a,sf));const d=yn(bo(a)).toVar(),c=_n(of(o,u).mul(d.sub(2)).add(1)).toVar();return gn(u.greaterThan(2),()=>{c.y.addAssign(d),u.subAssign(3)}),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(Da(3,nf))),c.y.addAssign(Da(4,bo(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(_n(),_n())}),hf=cn(({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Co(s),l=r.mul(u).add(i.cross(r).mul(Ao(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return cf(e,l,t,n,a,o)}),pf=cn(({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=Rn(Au(t,r,au(r,s))).toVar();gn(h.equal(Rn(0)),()=>{h.assign(Rn(s.z,0,s.x.negate()))}),h.assign(Ro(h));const p=Rn().toVar();return p.addAssign(i.element(0).mul(hf({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Bp({start:bn(1),end:e},({i:e})=>{gn(e.greaterThanEqual(n),()=>{Fp()});const t=yn(a.mul(yn(e))).toVar();p.addAssign(i.element(e).mul(hf({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(hf({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))}),Cn(p,1)}),gf=cn(([e])=>{const t=xn(e).toVar();return t.assign(t.shiftLeft(xn(16)).bitOr(t.shiftRight(xn(16)))),t.assign(t.bitAnd(xn(1431655765)).shiftLeft(xn(1)).bitOr(t.bitAnd(xn(2863311530)).shiftRight(xn(1)))),t.assign(t.bitAnd(xn(858993459)).shiftLeft(xn(2)).bitOr(t.bitAnd(xn(3435973836)).shiftRight(xn(2)))),t.assign(t.bitAnd(xn(252645135)).shiftLeft(xn(4)).bitOr(t.bitAnd(xn(4042322160)).shiftRight(xn(4)))),t.assign(t.bitAnd(xn(16711935)).shiftLeft(xn(8)).bitOr(t.bitAnd(xn(4278255360)).shiftRight(xn(8)))),yn(t).mul(2.3283064365386963e-10)}),mf=cn(([e,t])=>_n(yn(e).div(yn(t)),gf(e))),ff=cn(([e,t,r])=>{const s=r.mul(r).toConst(),i=Rn(1,0,0).toConst(),n=au(t,i).toConst(),a=_o(e.x).toConst(),o=Da(2,3.14159265359).mul(e.y).toConst(),u=a.mul(Co(o)).toConst(),l=a.mul(Ao(o)).toVar(),d=Da(.5,t.z.add(1)).toConst();l.assign(d.oneMinus().mul(_o(u.mul(u).oneMinus())).add(d.mul(l)));const c=i.mul(u).add(n.mul(l)).add(t.mul(_o(eu(0,u.mul(u).add(l.mul(l)).oneMinus()))));return Ro(Rn(s.mul(c.x),s.mul(c.y),eu(0,c.z)))}),yf=cn(({roughness:e,mipInt:t,envMap:r,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Rn(s).toVar(),l=Rn(0).toVar(),d=yn(0).toVar();return gn(e.lessThan(.001),()=>{l.assign(cf(r,u,t,n,a,o))}).Else(()=>{const s=Au(Vo(u.z).lessThan(.999),Rn(0,0,1),Rn(1,0,0)),c=Ro(au(s,u)).toVar(),h=au(u,c).toVar();Bp({start:xn(0),end:i},({i:s})=>{const p=mf(s,i),g=ff(p,Rn(0,0,1),e),m=Ro(c.mul(g.x).add(h.mul(g.y)).add(u.mul(g.z))),f=Ro(m.mul(nu(u,m).mul(2)).sub(u)),y=eu(nu(u,f),0);gn(y.greaterThan(0),()=>{const e=cf(r,f,t,n,a,o);l.addAssign(e.mul(y)),d.addAssign(y)})}),gn(d.greaterThan(0),()=>{l.assign(l.div(d))})}),Cn(l,1)}),bf=[.125,.215,.35,.446,.526,.582],xf=20,Tf=new Ne(-1,1,1,-1,0,1),_f=new Se(90,1),vf=new e;let Nf=null,Sf=0,Rf=0;const Ef=new r,Af=new WeakMap,wf=[3,1,5,0,4,2],Cf=lf(kl(),Vl("faceIndex")).normalize(),Mf=Rn(Cf.x,Cf.y,Cf.z);class Bf{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Ef,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){d('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}Nf=this._renderer.getRenderTarget(),Sf=this._renderer.getActiveCubeFace(),Rf=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget();return u.depthBuffer=!0,this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return v('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){d('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return v('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){d("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return v('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Df(),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===U||e.mapping===I?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;ee-4?o=bf[a-e+4-1]:0===a&&(o=0),r.push(o);const u=1/(n-2),l=-u,d=1+u,c=[l,l,d,l,d,d,l,l,d,d,l,d],h=6,p=6,g=3,m=2,f=1,y=new Float32Array(g*p*h),b=new Float32Array(m*p*h),x=new Float32Array(f*p*h);for(let e=0;e2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=wf[e];y.set(s,g*p*i),b.set(c,m*p*i);const n=[i,i,i,i,i,i];x.set(n,f*p*i)}const T=new ve;T.setAttribute("position",new we(y,g)),T.setAttribute("uv",new we(b,m)),T.setAttribute("faceIndex",new we(x,f)),s.push(new oe(T,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t,sigmas:r}}(t)),this._blurMaterial=function(e,t,s){const i=td(new Array(xf).fill(0)),n=Sa(new r(0,1,0)),a=Sa(0),o=yn(xf),u=Sa(0),l=Sa(1),d=Kl(),c=Sa(0),h=yn(1/t),p=yn(1/s),g=yn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:Mf,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Lf("blur");return f.fragmentNode=pf({...m,latitudinal:u.equal(1)}),Af.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,r){const s=Kl(),i=Sa(0),n=Sa(0),a=yn(1/t),o=yn(1/r),u=yn(e),l={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:u},d=Lf("ggx");return d.fragmentNode=yf({...l,N_immutable:Mf,GGX_SAMPLES:xn(512)}),Af.set(d,l),d}(t,e.width,e.height)}}async _compileMaterial(e){const t=new oe(new ve,e);await this._renderer.compile(t,Tf)}_sceneToCubeUV(e,t,r,s,i){const n=_f;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(vf),u.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new oe(new ae,new fe({name:"PMREM.Background",side:L,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,c=d.material;let h=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,h=!0):(c.color.copy(vf),h=!0),u.setRenderTarget(s),u.clear(),h&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;this._setViewport(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=p}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===U||e.mapping===I;s?null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(e)):null===this._equirectMaterial&&(this._equirectMaterial=Df(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,Tf)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let t=1;tc-4?r-c+4:0),g=4*(this._cubeSize-h);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=d,o.mipInt.value=c-t,this._setViewport(i,p,g,3*h,2*h),s.setRenderTarget(i),s.render(a,Tf),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=c-r,this._setViewport(e,p,g,3*h,2*h),s.setRenderTarget(e),s.render(a,Tf)}_blur(e,t,r,s,i){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,r,s,"latitudinal",i),this._halfBlur(n,e,r,r,s,"longitudinal",i)}_halfBlur(e,t,r,s,i,n,a){const u=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&o("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[s];c.material=l;const h=Af.get(l),p=this._sizeLods[r]-1,g=isFinite(i)?Math.PI/(2*p):2*Math.PI/39,m=i/g,f=isFinite(i)?1+Math.floor(3*m):xf;f>xf&&d(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const y=[];let b=0;for(let e=0;ex-4?s-x+4:0),v=4*(this._cubeSize-T);this._setViewport(t,_,v,3*T,2*T),u.setRenderTarget(t),u.render(c,Tf)}_setViewport(e,t,r,s,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-r,s,i),e.scissor.set(t,e.height-i-r,s,i)):(e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i))}}function Ff(e,t){const r=new ne(e,t,{magFilter:le,minFilter:le,generateMipmaps:!1,type:Te,format:Ee,colorSpace:Re});return r.texture.mapping=Ae,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Lf(e){const t=new vg;return t.depthTest=!1,t.depthWrite=!1,t.blending=re,t.name=`PMREM_${e}`,t}function Pf(e){const t=Lf("cubemap");return t.fragmentNode=$c(e,Mf),t}function Df(e){const t=Lf("equirect");return t.fragmentNode=Kl(e,Bg(Mf),0),t}const Uf=new WeakMap;function If(e,t,r){const s=function(e){let t=Uf.get(e);void 0===t&&(t=new WeakMap,Uf.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s0}(t))return null;i=r.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,s.set(e,i)}return i.texture}class Of extends gi{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new N;s.isRenderTargetTexture=!0,this._texture=Kl(s),this._width=Sa(0),this._height=Sa(0),this._maxMip=Sa(0),this.updateBeforeType=ri.RENDER}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,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,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 r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture?s:If(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Bf(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Dc.mul(Rn(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),df(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Vf=an(Of).setParameterLength(1,3),kf=new WeakMap;class Gf extends Op{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const s=r.isTextureNode?r.value:t[r.property],i=this._getPMREMNodeCache(e.renderer);let n=i.get(s);void 0===n&&(n=Vf(s),i.set(s,n)),r=n}const s=!0===t.useAnisotropy||t.anisotropy>0?_h:Sc,i=r.context(zf(Wn,s)).mul(Pc),n=r.context($f(Rc)).mul(Math.PI).mul(Pc),a=vl(i),o=vl(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(zf(jn,Ec)).mul(Pc),t=vl(e);u.addAssign(t)}}_getPMREMNodeCache(e){let t=kf.get(e);return void 0===t&&(t=new WeakMap,kf.set(e,t)),t}}const zf=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=gc.negate().reflect(t),r=du(e).mix(r,t).normalize(),r=r.transformDirection(Dd)),r),getTextureLevel:()=>e}},$f=e=>({getUV:()=>e,getTextureLevel:()=>yn(1)}),Wf=new Ce;class Hf extends vg{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(Wf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Gf(t):null}setupLightingModel(){return new qm}setupSpecular(){const e=gu(Rn(.04),Gn.rgb,Hn);sa.assign(Rn(.04)),ia.assign(e),na.assign(1)}setupVariants(){const e=this.metalnessNode?yn(this.metalnessNode):$h;Hn.assign(e);let t=this.roughnessNode?yn(this.roughnessNode):zh;t=em({roughness:t}),Wn.assign(t),this.setupSpecular(),zn.assign(Gn.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const qf=new Me;class jf extends Hf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(qf),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?yn(this.iorNode):sp;ca.assign(e),sa.assign(Jo(uu(ca.sub(1).div(ca.add(1))).mul(Vh),Rn(1)).mul(Oh)),ia.assign(gu(sa,Gn.rgb,Hn)),na.assign(gu(Oh,1,Hn))}setupLightingModel(){return new qm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?yn(this.clearcoatNode):Hh,t=this.clearcoatRoughnessNode?yn(this.clearcoatRoughnessNode):qh;qn.assign(e),jn.assign(em({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Rn(this.sheenNode):Kh,t=this.sheenRoughnessNode?yn(this.sheenRoughnessNode):Qh;Xn.assign(e),Kn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?yn(this.iridescenceNode):Zh,t=this.iridescenceIORNode?yn(this.iridescenceIORNode):Jh,r=this.iridescenceThicknessNode?yn(this.iridescenceThicknessNode):ep;Qn.assign(e),Yn.assign(t),Zn.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?_n(this.anisotropyNode):Yh).toVar();ea.assign(e.length()),gn(ea.equal(0),()=>{e.assign(_n(1,0))}).Else(()=>{e.divAssign(_n(ea)),ea.assign(ea.saturate())}),Jn.assign(ea.pow2().mix(Wn.pow2(),1)),ta.assign(xh[0].mul(e.x).add(xh[1].mul(e.y))),ra.assign(xh[1].mul(e.x).sub(xh[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?yn(this.transmissionNode):tp,t=this.thicknessNode?yn(this.thicknessNode):rp,r=this.attenuationDistanceNode?yn(this.attenuationDistanceNode):ip,s=this.attenuationColorNode?Rn(this.attenuationColorNode):np;if(ha.assign(e),pa.assign(t),ga.assign(r),ma.assign(s),this.useDispersion){const e=this.dispersionNode?yn(this.dispersionNode):hp;fa.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Rn(this.clearcoatNormalNode):jh}setup(e){e.context.setupClearcoatNormal=()=>Gu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}class Xf extends qm{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Sc.mul(a)).normalize(),h=yn(gc.dot(c.negate()).saturate().pow(l).mul(d)),p=Rn(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Kf extends jf{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=yn(.1),this.thicknessAmbientNode=yn(0),this.thicknessAttenuationNode=yn(.1),this.thicknessPowerNode=yn(2),this.thicknessScaleNode=yn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Xf(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}copy(e){return this.thicknessColorNode=e.thicknessColorNode,this.thicknessDistortionNode=e.thicknessDistortionNode,this.thicknessAmbientNode=e.thicknessAmbientNode,this.thicknessAttenuationNode=e.thicknessAttenuationNode,this.thicknessPowerNode=e.thicknessPowerNode,this.thicknessScaleNode=e.thicknessScaleNode,super.copy(e)}}const Qf=cn(({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=_n(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Kc("gradientMap","texture").context({getUV:()=>i});return Rn(e.r)}{const e=i.fwidth().mul(.5);return gu(Rn(.7),Rn(1),bu(yn(.7).sub(e.x),yn(.7).add(e.x),i.x))}});class Yf extends kg{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Qf({normal:xc,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Hg({diffuseColor:Gn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Zf=new Be;class Jf extends vg{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Zf),this.setValues(e)}setupLightingModel(){return new Yf}}const ey=cn(()=>{const e=Rn(gc.z,0,gc.x.negate()).normalize(),t=gc.cross(e);return _n(e.dot(Sc),t.dot(Sc)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),ty=new Fe;class ry extends vg{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupVariants(e){const t=ey;let r;r=e.material.matcap?Kc("matcap","texture").context({getUV:()=>t}):Rn(gu(.2,.8,t.y)),Gn.rgb.mulAssign(r.rgb)}}class sy extends gi{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return Ln(e,s,s.negate(),e).mul(r)}{const e=t,s=Dn(Cn(1,0,0,0),Cn(0,Co(e.x),Ao(e.x).negate(),0),Cn(0,Ao(e.x),Co(e.x),0),Cn(0,0,0,1)),i=Dn(Cn(Co(e.y),0,Ao(e.y),0),Cn(0,1,0,0),Cn(Ao(e.y).negate(),0,Co(e.y),0),Cn(0,0,0,1)),n=Dn(Cn(Co(e.z),Ao(e.z).negate(),0,0),Cn(Ao(e.z),Co(e.z),0,0),Cn(0,0,1,0),Cn(0,0,0,1));return s.mul(i).mul(n).mul(Cn(r,1)).xyz}}}const iy=an(sy).setParameterLength(2),ny=new Le;class ay extends vg{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ny),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=sc.mul(Rn(s||0));let u=_n(Qd[0].xyz.length(),Qd[1].xyz.length());null!==n&&(u=u.mul(_n(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=uc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>new Zu(e,t,r))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=yn(i||Xh),c=iy(l,d);return Cn(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const oy=new Pe,uy=new t;class ly extends ay{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(oy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return sc.mul(Rn(e||lc)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?_n(n):cp;u=u.mul(od),r.isPerspectiveCamera&&!0===a&&(u=u.mul(dy.div(pc.z.negate()))),i&&i.isNode&&(u=u.mul(_n(i)));let l=uc.xy;if(s&&s.isNode){const e=yn(s);l=iy(l,e)}return l=l.mul(u),l=l.div(hd.div(2)),l=l.mul(o.w),o=o.add(Cn(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const dy=Sa(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(uy);this.value=.5*t.y});class cy extends kg{constructor(){super(),this.shadowNode=yn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Gn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Gn.rgb)}}const hy=new De;class py extends vg{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(hy),this.setValues(e)}setupLightingModel(){return new cy}}const gy=Vn("vec3"),my=Vn("vec3"),fy=Vn("vec3");class yy extends kg{constructor(){super()}start(e){const{material:t}=e,r=Vn("vec3"),s=Vn("vec3");gn(Od.sub(cc).length().greaterThan(ec.mul(2)),()=>{r.assign(Od),s.assign(cc)}).Else(()=>{r.assign(cc),s.assign(Od)});const i=s.sub(r),n=Sa("int").onRenderUpdate(({material:e})=>e.steps),a=i.length().div(n).toVar(),o=i.normalize().toVar(),u=yn(0).toVar(),l=Rn(1).toVar();t.offsetNode&&u.addAssign(t.offsetNode.mul(a)),Bp(n,()=>{const s=r.add(o.mul(u)),i=Dd.mul(Cn(s,1)).xyz;let n;null!==t.depthNode&&(my.assign(og(tg(i.z,Bd,Fd))),e.context.sceneDepthNode=og(t.depthNode).toVar()),e.context.positionWorld=s,e.context.shadowPositionWorld=s,e.context.positionView=i,gy.assign(0),t.scatteringNode&&(n=t.scatteringNode({positionRay:s})),super.start(e),n&&gy.mulAssign(n);const d=gy.mul(.01).negate().mul(a).exp();l.mulAssign(d),u.addAssign(a)}),fy.addAssign(l.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?gn(r.greaterThanEqual(my),()=>{gy.addAssign(e)}):gy.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(void 0===e.light.distance)return;const s=t.xyz.toVar();s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul(Tm({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(fy)}}class by extends vg{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=L,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new yy}}class xy{constructor(e,t,r){this.renderer=e,this.nodes=t,this.info=r,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,r),this.renderer._inspector.finish()};e()}stop(){null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Ty{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let r=this.weakMaps[t];return void 0===r&&(r=new WeakMap,this.weakMaps[t]=r),r}get(e){let t=this._getWeakMap(e);for(let r=0;r{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),i[n.name]=e.id),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e1||Array.isArray(e.morphTargetInfluences))&&(s+=e.uuid+","),s+=this.context.id+",",s+=e.receiveShadow+",",Vs(s)}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 r=this.geometry.getAttribute(t);if(void 0===r||e[t]!==r.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Gs(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Gs(e,1)),e=Gs(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Ny=[];class Sy{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);Ny[0]=e,Ny[1]=t,Ny[2]=n,Ny[3]=i;let l=u.get(Ny);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Ny,l)):(l.camera=s,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Ny[0]=null,Ny[1]=null,Ny[2]=null,Ny[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Ty)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new vy(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.deleteForRender(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Ry{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 Ey=1,Ay=2,wy=3,Cy=4,My=16;class By extends Ry{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 r=this.get(e);if(void 0===r.version)t===Ey?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ay?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===wy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Cy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version=65535?Ue:Ie)(t,1);return i.version=Fy(e),i.__id=Ly(e),i}class Dy extends Ry{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 r=()=>{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,wy):this.updateAttribute(e,Ey);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,Ay);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,Cy)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=Py(t),e.set(t,r)):r.version===Fy(t)&&r.__id===Ly(t)||(this.attributes.delete(r),r=Py(t),e.set(t,r)),s=r}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Uy{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,r){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=r*(t/3):e.isPoints?this.render.points+=r*t:e.isLineSegments?this.render.lines+=r*(t/2):e.isLine?this.render.lines+=r*(t-1):o("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const r=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:r,type:t}),this.memory[t]++,this.memory.total+=r,this.memory[t+"Size"]+=r}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=this._getAttributeMemorySize(e.attribute);this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){this.destroyAttribute(e)}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===Oe||e.type===Ve?t=1:e.type===ke||e.type===Ge||e.type===Te?t=2:e.type!==R&&e.type!==S&&e.type!==K||(t=4);let r=4;e.format===ze||e.format===$e||e.format===We||e.format===He||e.format===qe?r=1:e.format===$||e.format===je?r=2:e.format!==Xe&&e.format!==Ke||(r=3);let s=t*r;e.type===Qe||e.type===Ye?s=2:e.type!==Ze&&e.type!==Je&&e.type!==et||(s=4);const i=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=i*n*a*s;const u=e.mipmaps;if(u&&u.length>0){let e=0;for(let t=0;t>t))*(r.height||Math.max(1,n>>t))*a*s}}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 Iy{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Oy extends Iy{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Vy extends Iy{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let ky=0;class Gy{constructor(e,t,r,s=null,i=null){this.id=ky++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class zy extends Ry{constructor(e,t,r){super(),this.backend=e,this.nodes=t,this.info=r,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new Gy(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new Gy(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o),this.info.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new Gy(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u),this.info.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const r=this.backend.get(t);return void 0!==r.pipeline&&null!==r.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,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new Vy(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new Oy(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].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 $y extends Ry{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?Cy:wy;this.attributes.update(e,r)}}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,i=e.isIndirectStorageBufferAttribute?Cy:wy,n=r.get(t);this.attributes.update(e,i),n.attribute!==e&&(n.attribute=e,s=!0)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),u=t.texture,l=this.textures.get(u);o&&(this.textures.updateTexture(u),t.generation!==l.generation&&(t.generation=l.generation,s=!0),l.bindGroups.add(e));if(void 0!==r.get(u).externalTexture||l.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===u.isStorageTexture&&!0===u.mipmapsAutoUpdate){const e=this.get(u);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(u)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(u),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,s=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function Wy(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 Hy(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 qy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===P&&!1===e.forceSinglePass}class jy{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,r),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&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||Wy),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Hy),this.transparent.length>1&&this.transparent.sort(t||Hy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&d&&(l=new Z,l.format=e.stencilBuffer?qe:He,l.type=e.stencilBuffer?Ze:S,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=l),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=l.isArrayTexture?l.image.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const h={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener("dispose",r.onDispose))}updateTexture(e,t={}){const r=this.get(e);if(!0===r.initialized&&r.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(s&&!0===r.initialized&&i.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:Ve}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;"requestPaint"in t&&(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image))}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),r.generation=e.version;else if(e.version>0){const s=e.image;if(void 0===s)d("Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)d("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version;!0!==r.initialized&&(r.initialized=!0,r.generation=e.version,r.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===p.enabled&&p.getTransfer(e.colorSpace)!==g&&d("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),r.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",r.onDispose)),r.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=eb){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),e.isHTMLTexture?(t.width=r.offsetWidth||1,t.height=r.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),r=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e=2)for(let r=0;r{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===s)t.build(e);else if("analyze"===s)t.build(e,this);else if("generate"===s){const r=e.getDataFromNode(t,"any").stages,s=r&&r[e.shaderStage];if(t.isVarNode&&s&&1===s.length&&s[0]&&s[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)i(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)i(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),hn(r),e.removeActiveStack(this),o}}const nb=an(ib).setParameterLength(0,1);class ab extends ci{static get type(){return"StructTypeNode"}constructor(e,t=null){var r;super("struct"),this.membersLayout=(r=e,Object.entries(r).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,r=0;for(const s of this.membersLayout){const i=s.type,n=js(i),a=Xs(i)/e;t=Math.max(t,a);const o=r%t%a;0!==o&&(r+=a-o),r+=n}return Math.ceil(r/t)*t}getMemberType(e,t){const r=this.membersLayout.find(e=>e.name===t);return r?r.type:"void"}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class ob extends ci{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){const e=super._getChildren(),t=e.find(e=>e.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class ub extends ci{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}generateNodeType(){return"OutputType"}generate(e){const t=e.getDataFromNode(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;tnew fb(e,"uint","float"),xb={};class Tb extends no{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,r){"int"===r?t.assign(yb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return xn;case"int":return bn;case"uvec2":return Nn;case"uvec3":return An;case"uvec4":return Bn;case"ivec2":return vn;case"ivec3":return En;case"ivec4":return Mn}}_createTrailingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t);const i=yn(s.bitAnd(zo(s))),n=bb(i).shiftRight(23).sub(127);return r(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{gn(e.equal(xn(0)),()=>xn(32));const s=xn(0),i=xn(0);return this._resolveElementType(e,s,t),gn(s.shiftRight(16).equal(0),()=>{i.addAssign(16),s.shiftLeftAssign(16)}),gn(s.shiftRight(24).equal(0),()=>{i.addAssign(8),s.shiftLeftAssign(8)}),gn(s.shiftRight(28).equal(0),()=>{i.addAssign(4),s.shiftLeftAssign(4)}),gn(s.shiftRight(30).equal(0),()=>{i.addAssign(2),s.shiftLeftAssign(2)}),gn(s.shiftRight(31).equal(0),()=>{i.addAssign(1)}),r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t),s.assign(s.sub(s.shiftRight(xn(1)).bitAnd(xn(1431655765)))),s.assign(s.bitAnd(xn(858993459)).add(s.shiftRight(xn(2)).bitAnd(xn(858993459))));const i=s.add(s.shiftRight(xn(4))).bitAnd(xn(252645135)).mul(xn(16843009)).shiftRight(xn(24));return r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,r,s){const i=this._returnDataNode(t);return cn(([e])=>{if(1===r)return i(s(e));{const t=i(0),n=["x","y","z","w"];for(let i=0;id(r))()}}Tb.COUNT_TRAILING_ZEROS="countTrailingZeros",Tb.COUNT_LEADING_ZEROS="countLeadingZeros",Tb.COUNT_ONE_BITS="countOneBits";const _b=un(Tb,Tb.COUNT_TRAILING_ZEROS).setParameterLength(1),vb=un(Tb,Tb.COUNT_LEADING_ZEROS).setParameterLength(1),Nb=un(Tb,Tb.COUNT_ONE_BITS).setParameterLength(1),Sb=cn(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)}),Rb=(e,t)=>ou(Da(4,e.mul(Pa(1,e))),t);class Eb extends gi{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}generateNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const Ab=un(Eb,"snorm").setParameterLength(1),wb=un(Eb,"unorm").setParameterLength(1),Cb=un(Eb,"float16").setParameterLength(1);class Mb extends gi{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}generateNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const Bb=un(Mb,"snorm").setParameterLength(1),Fb=un(Mb,"unorm").setParameterLength(1),Lb=un(Mb,"float16").setParameterLength(1),Pb=cn(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Db=cn(([e])=>Rn(Pb(e.z.add(Pb(e.y.mul(1)))),Pb(e.z.add(Pb(e.x.mul(1)))),Pb(e.y.add(Pb(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Ub=cn(([e,t,r])=>{const s=Rn(e).toVar(),i=yn(1.4).toVar(),n=yn(0).toVar(),a=Rn(s).toVar();return Bp({start:yn(0),end:yn(3),type:"float",condition:"<="},()=>{const e=Rn(Db(a.mul(2))).toVar();s.addAssign(e.add(r.mul(yn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=yn(Pb(s.z.add(Pb(s.x.add(Pb(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class Ib extends ci{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let r=this._candidateFn;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;ri&&(s=r,i=n)}}this._candidateFn=r=s}return r}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const Ob=an(Ib),Vb=e=>(...t)=>Ob(e,...t),kb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.time),Gb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.deltaTime),zb=Sa(0,"uint").setGroup(_a).onRenderUpdate(e=>e.frameId);const $b=cn(([e,t,r=_n(.5)])=>iy(e.sub(r),t).add(r)),Wb=cn(([e,t,r=_n(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))}),Hb=cn(({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=Qd.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=Qd;const i=Dd.mul(s);return Zi(t)&&(i[0][0]=Qd[0].length(),i[0][1]=0,i[0][2]=0),Zi(r)&&(i[1][0]=0,i[1][1]=Qd[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,Ld.mul(i).mul(lc)}),qb=cn(([e=null])=>{const t=og();return og(Yp(e)).sub(t).lessThan(0).select(ud,e)}),jb=cn(([e,t=kl(),r=yn(0)])=>{const s=e.x,i=e.y,n=r.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=e.reciprocal(),l=_n(a,o);return t.add(l).mul(u)}),Xb=cn(([e,t=null,r=null,s=yn(1),i=lc,n=Tc])=>{let a=n.abs().normalize();a=a.div(a.dot(Rn(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=Kl(d,o).mul(a.x),g=Kl(c,u).mul(a.y),m=Kl(h,l).mul(a.z);return La(p,g,m)}),Kb=new ut,Qb=new r,Yb=new r,Zb=new r,Jb=new a,ex=new r(0,0,-1),tx=new s,rx=new r,sx=new r,ix=new s,nx=new t,ax=new ne,ox=ud.flipX();ax.depthTexture=new Z(1,1);let ux=!1;class lx extends jl{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||ax.texture,ox),this._reflectorBaseNode=e.reflector||new dx(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new lx({defaultTexture:ax.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class dx extends ci{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new at,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(v('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?ri.RENDER:ri.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(nx),e.setSize(Math.round(nx.width*r),Math.round(nx.height*r))}setup(e){return this._updateResolution(ax,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new ne(0,0,{type:Te,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=ot,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Z),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&ux)return!1;ux=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(nx),this._updateResolution(o,s),Yb.setFromMatrixPosition(n.matrixWorld),Zb.setFromMatrixPosition(r.matrixWorld),Jb.extractRotation(n.matrixWorld),Qb.set(0,0,1),Qb.applyMatrix4(Jb),rx.subVectors(Yb,Zb);let u=!1;if(!0===rx.dot(Qb)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(ux=!1);u=!0}rx.reflect(Qb).negate(),rx.add(Yb),Jb.extractRotation(r.matrixWorld),ex.set(0,0,-1),ex.applyMatrix4(Jb),ex.add(Zb),sx.subVectors(Yb,ex),sx.reflect(Qb).negate(),sx.add(Yb),a.coordinateSystem=r.coordinateSystem,a.position.copy(rx),a.up.set(0,1,0),a.up.applyMatrix4(Jb),a.up.reflect(Qb),a.lookAt(sx),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Kb.setFromNormalAndCoplanarPoint(Qb,Yb),Kb.applyMatrix4(a.matrixWorldInverse),tx.set(Kb.normal.x,Kb.normal.y,Kb.normal.z,Kb.constant);const l=a.projectionMatrix;ix.x=(Math.sign(tx.x)+l.elements[8])/l.elements[0],ix.y=(Math.sign(tx.y)+l.elements[9])/l.elements[5],ix.z=-1,ix.w=(1+l.elements[10])/l.elements[14],tx.multiplyScalar(1/tx.dot(ix));l.elements[2]=tx.x,l.elements[6]=tx.y,l.elements[10]=s.coordinateSystem===h?tx.z-0:tx.z+1-0,l.elements[14]=tx.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const d=s.getRenderTarget(),c=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0;const g=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),t.name=g,s.setMRT(c),s.setRenderTarget(d),s.autoClear=p,i.visible=!0,ux=!1,this.forceUpdate=!1}get resolution(){return v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const cx=new Ne(-1,1,1,-1,0,1);class hx extends ve{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lt(t,2))}}const px=new hx;class gx extends oe{constructor(e=null){super(px,e),this.camera=cx,this.isQuadMesh=!0}async renderAsync(e){v('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,cx)}render(e){e.render(this,cx)}}const mx=new t;class fx extends jl{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:Te}){const i=new ne(t,r,s);super(i.texture,kl()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.pixelRatio=1,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new gx(new vg),this.updateBeforeType=ri.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const r=e*this.pixelRatio,s=t*this.pixelRatio;this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),r=e.getSize(mx),s=Math.floor(r.width*t),i=Math.floor(r.height*t);s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const r=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(r)}clone(){const e=new jl(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const yx=(e,...t)=>new fx(tn(e),...t),bx=cn(([e,t,r],s)=>{let i;s.renderer.coordinateSystem===h?(e=_n(e.x,e.y.oneMinus()).mul(2).sub(1),i=Cn(Rn(e,t),1)):i=Cn(Rn(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Cn(r.mul(i));return n.xyz.div(n.w)}),xx=cn(([e,t])=>{const r=t.mul(Cn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return _n(s.x,s.y.oneMinus())}),Tx=cn(([e,t,r])=>{const s=zl(Ql(t)),i=vn(e.mul(s)).toVar(),n=Ql(t,i).toVar(),a=Ql(t,i.sub(vn(2,0))).toVar(),o=Ql(t,i.sub(vn(1,0))).toVar(),u=Ql(t,i.add(vn(1,0))).toVar(),l=Ql(t,i.add(vn(2,0))).toVar(),d=Ql(t,i.add(vn(0,2))).toVar(),c=Ql(t,i.add(vn(0,1))).toVar(),h=Ql(t,i.sub(vn(0,1))).toVar(),p=Ql(t,i.sub(vn(0,2))).toVar(),g=Vo(Pa(yn(2).mul(o).sub(a),n)).toVar(),m=Vo(Pa(yn(2).mul(u).sub(l),n)).toVar(),f=Vo(Pa(yn(2).mul(c).sub(d),n)).toVar(),y=Vo(Pa(yn(2).mul(h).sub(p),n)).toVar(),b=bx(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(bx(e.sub(_n(yn(1).div(s.x),0)),o,r)),b.negate().add(bx(e.add(_n(yn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(bx(e.add(_n(0,yn(1).div(s.y))),c,r)),b.negate().add(bx(e.sub(_n(0,yn(1).div(s.y))),h,r)));return Ro(au(x,T))}),_x=cn(([e])=>Eo(yn(52.9829189).mul(Eo(nu(e,_n(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),vx=cn(([e,t,r])=>{const s=yn(2.399963229728653),i=_o(yn(e).add(.5).div(yn(t))),n=yn(e).mul(s).add(r);return _n(Co(n),Ao(n)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class Nx extends ci{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(kl())}sample(e){return this.callback(e)}}class Sx extends ci{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Sx.OBJECT?this.updateType=ri.OBJECT:e===Sx.MATERIAL?this.updateType=ri.RENDER:e===Sx.BEFORE_OBJECT?this.updateBeforeType=ri.OBJECT:e===Sx.BEFORE_MATERIAL&&(this.updateBeforeType=ri.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}Sx.OBJECT="object",Sx.MATERIAL="material",Sx.BEFORE_OBJECT="beforeObject",Sx.BEFORE_MATERIAL="beforeMaterial";const Rx=(e,t)=>new Sx(e,t).toStack();class Ex extends q{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Ax extends we{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class wx extends ci{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Cx=on(wx),Mx=new a,Bx=Sa(0).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Fx=Sa(1).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundIntensity),Lx=Sa(new a).setGroup(_a).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&t.mapping!==dt?Mx.makeRotationFromEuler(e.backgroundRotation).transpose():Mx.identity(),Mx});class Px extends jl{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=ii.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return null!==this.storeNode?(this.generateStore(e),""):super.generate(e,t)}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;return e.generateStorageTextureLoad(l,t,r,s,n,u)}toReadWrite(){return this.setAccess(ii.READ_WRITE)}toReadOnly(){return this.setAccess(ii.READ_ONLY)}toWriteOnly(){return this.setAccess(ii.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(this.value,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}}const Dx=an(Px).setParameterLength(1,3),Ux=cn(({texture:e,uv:t})=>{const r=1e-4,s=Rn().toVar();return gn(t.x.lessThan(r),()=>{s.assign(Rn(1,0,0))}).ElseIf(t.y.lessThan(r),()=>{s.assign(Rn(0,1,0))}).ElseIf(t.z.lessThan(r),()=>{s.assign(Rn(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{s.assign(Rn(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{s.assign(Rn(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{s.assign(Rn(0,0,-1))}).Else(()=>{const r=.01,i=e.sample(t.add(Rn(-.01,0,0))).r.sub(e.sample(t.add(Rn(r,0,0))).r),n=e.sample(t.add(Rn(0,-.01,0))).r.sub(e.sample(t.add(Rn(0,r,0))).r),a=e.sample(t.add(Rn(0,0,-.01))).r.sub(e.sample(t.add(Rn(0,0,r))).r);s.assign(Rn(i,n,a))}),s.normalize()});class Ix extends jl{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Rn(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return Ux({texture:this,uv:e})}}const Ox=an(Ix).setParameterLength(1,3);class Vx extends Hc{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const kx=new WeakMap;class Gx extends gi{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=ri.OBJECT,this.updateAfterType=ri.OBJECT,this.previousModelWorldMatrix=Sa(new a),this.previousProjectionMatrix=Sa(new a).setGroup(_a),this.previousCameraViewMatrix=Sa(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=$x(r);this.previousModelWorldMatrix.value.copy(s);const i=zx(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new a,i.previousCameraViewMatrix=new a,i.currentProjectionMatrix=new a,i.currentCameraViewMatrix=new a,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){$x(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Ld:Sa(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(sc).mul(lc),s=this.previousProjectionMatrix.mul(t).mul(dc),i=r.xy.div(r.w),n=s.xy.div(s.w);return Pa(i,n)}}function zx(e){let t=kx.get(e);return void 0===t&&(t={},kx.set(e,t)),t}function $x(e,t=0){const r=zx(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const Wx=on(Gx),Hx=cn(([e])=>Kx(e.rgb)),qx=cn(([e,t=yn(1)])=>t.mix(Kx(e.rgb),e.rgb)),jx=cn(([e,t=yn(1)])=>{const r=La(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return gu(e.rgb,s,i)}),Xx=cn(([e,t=yn(1)])=>{const r=Rn(.57735,.57735,.57735),s=t.cos();return Rn(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(nu(r,e.rgb).mul(s.oneMinus())))))}),Kx=(e,t=Rn(p.getLuminanceCoefficients(new r)))=>nu(e,t),Qx=cn(([e,t=Rn(1),s=Rn(0),i=Rn(1),n=yn(1),a=Rn(p.getLuminanceCoefficients(new r,Re))])=>{const o=e.rgb.dot(Rn(a)),u=eu(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return gn(u.r.greaterThan(0),()=>{u.r.assign(l.r)}),gn(u.g.greaterThan(0),()=>{u.g.assign(l.g)}),gn(u.b.greaterThan(0),()=>{u.b.assign(l.b)}),u.assign(o.add(u.sub(o).mul(n))),Cn(u.rgb,e.a)}),Yx=cn(([e,t])=>e.mul(t).floor().div(t));let Zx=null;class Jx extends Wp{static get type(){return"ViewportSharedTextureNode"}constructor(e=ud,t=null){null===Zx&&(Zx=new Q),super(e,t,Zx)}getTextureForReference(){return Zx}updateReference(){return this}}const eT=an(Jx).setParameterLength(0,2),tT=new t;class rT extends jl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class sT extends rT{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class iT extends gi{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const i=new Z;i.isRenderTargetTexture=!0,i.name="depth";const n=new ne(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Te,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Sa(0),this._cameraFar=Sa(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=ri.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return d("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return d("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new sT(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new sT(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=sg(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=Jp(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),!0===e.reversedDepthBuffer&&(this.renderTarget.depthTexture.type=K),this.scope===iT.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s,i;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(i=1,s=t.xr.getCamera(),t.xr.updateCamera(s),tT.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(tT)),this._pixelRatio=i,this.setSize(tT.width,tT.height);const a=t.getRenderTarget(),o=t.getMRT(),u=t.autoClear,l=t.transparent,d=t.opaque,c=s.layers.mask,h=t.contextNode,p=r.overrideMaterial;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(r.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Cu({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const g=r.name;r.name=this.name?this.name:r.name,t.render(r,s),r.name=g,r.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=u,t.transparent=l,t.opaque=d,t.contextNode=h,s.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const r=Math.floor(this._width*this._pixelRatio*this._resolutionScale),s=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(r,s),null!==this._scissor?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,r,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new s),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,i))}setViewport(e,t,r,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new s),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}iT.COLOR="color",iT.DEPTH="depth";class nT extends iT{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(iT.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)}),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new vg;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=L;const t=Tc.negate(),r=Ld.mul(sc),s=yn(1),i=r.mul(Cn(lc,1)),n=r.mul(Cn(lc.add(t),1)),a=Ro(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=Cn(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const aT=cn(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),oT=cn(([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"}]}),uT=cn(([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lT=cn(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)}),dT=cn(([e,t])=>{const r=Pn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Pn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=lT(e),(e=s.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),cT=Pn(Rn(1.6605,-.1246,-.0182),Rn(-.5876,1.1329,-.1006),Rn(-.0728,-.0083,1.1187)),hT=Pn(Rn(.6274,.0691,.0164),Rn(.3293,.9195,.088),Rn(.0433,.0113,.8956)),pT=cn(([e])=>{const t=Rn(e).toVar(),r=Rn(t.mul(t)).toVar(),s=Rn(r.mul(r)).toVar();return yn(15.5).mul(s.mul(r)).sub(Da(40.14,s.mul(t))).add(Da(31.96,s).sub(Da(6.868,r.mul(t))).add(Da(.4298,r).add(Da(.1191,t).sub(.00232))))}),gT=cn(([e,t])=>{const r=Rn(e).toVar(),s=Pn(Rn(.856627153315983,.137318972929847,.11189821299995),Rn(.0951212405381588,.761241990602591,.0767994186031903),Rn(.0482516061458583,.101439036467562,.811302368396859)),i=Pn(Rn(1.1271005818144368,-.1413297634984383,-.14132976349843826),Rn(-.11060664309660323,1.157823702216272,-.11060664309660294),Rn(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=yn(-12.47393),a=yn(4.026069);return r.mulAssign(t),r.assign(hT.mul(r)),r.assign(s.mul(r)),r.assign(eu(r,1e-10)),r.assign(To(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(mu(r,0,1)),r.assign(pT(r)),r.assign(i.mul(r)),r.assign(ou(eu(Rn(0),r),Rn(2.2))),r.assign(cT.mul(r)),r.assign(mu(r,0,1)),r}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),mT=cn(([e,t])=>{const r=yn(.76),s=yn(.15);e=e.mul(t);const i=Jo(e.r,Jo(e.g,e.b)),n=Au(i.lessThan(.08),i.sub(Da(6.25,i.mul(i))),.04);e.subAssign(n);const a=eu(e.r,eu(e.g,e.b));gn(a.lessThan(r),()=>e);const o=Pa(1,r),u=Pa(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=Pa(1,Ua(1,s.mul(a.sub(u)).add(1)));return gu(e,Rn(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class fT extends ci{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.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}}const yT=an(fT).setParameterLength(1,3);class bT extends fT{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const xT=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};function TT(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||pc.z).negate()}const _T=cn(([e,t],r)=>{const s=TT(r);return bu(e,t,s)}),vT=cn(([e],t)=>{const r=TT(t);return e.mul(e,r,r).negate().exp().oneMinus()}),NT=cn(([e,t],r)=>{const s=TT(r),i=t.sub(cc.y).max(0).toConst().mul(s).toConst();return e.mul(e,i,i).negate().exp().oneMinus()}),ST=cn(([e,t])=>Cn(t.toFloat().mix(oa.rgb,e.toVec3()),oa.a));let RT=null,ET=null;class AT extends ci{static get type(){return"RangeNode"}constructor(e=yn(),t=yn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),s=e.getTypeLength(Ks(t.value)),i=e.getTypeLength(Ks(r.value));return s>i?s:i}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Hl('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=i.value,o=n.value,u=e.getTypeLength(Ks(a)),d=e.getTypeLength(Ks(o));RT=RT||new s,ET=ET||new s,RT.setScalar(0),ET.setScalar(0),1===u?RT.setScalar(a):a.isColor?RT.set(a.r,a.g,a.b,1):RT.set(a.x,a.y,a.z||0,a.w||0),1===d?ET.setScalar(o):o.isColor?ET.set(o.r,o.g,o.b,1):ET.set(o.x,o.y,o.z||0,o.w||0);const c=4,h=c*t.count,p=new Float32Array(h);for(let e=0;enew CT(e,t),BT=MT("numWorkgroups","uvec3"),FT=MT("workgroupId","uvec3"),LT=MT("globalId","uvec3"),PT=MT("localId","uvec3"),DT=MT("subgroupSize","uint");class UT extends ci{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}const IT=an(UT);class OT extends hi{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.context.assign;if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class VT extends ci{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new OT(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class kT extends ci{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Cl(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}kT.ATOMIC_LOAD="atomicLoad",kT.ATOMIC_STORE="atomicStore",kT.ATOMIC_ADD="atomicAdd",kT.ATOMIC_SUB="atomicSub",kT.ATOMIC_MAX="atomicMax",kT.ATOMIC_MIN="atomicMin",kT.ATOMIC_AND="atomicAnd",kT.ATOMIC_OR="atomicOr",kT.ATOMIC_XOR="atomicXor";const GT=an(kT),zT=(e,t,r)=>GT(e,t,r).toStack();class $T extends gi{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}generateNodeType(e){const t=this.method;return t===$T.SUBGROUP_ELECT?"bool":t===$T.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===$T.SUBGROUP_BROADCAST||r===$T.SUBGROUP_SHUFFLE||r===$T.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===$T.SUBGROUP_SHUFFLE_XOR||r===$T.SUBGROUP_SHUFFLE_DOWN||r===$T.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}$T.SUBGROUP_ELECT="subgroupElect",$T.SUBGROUP_BALLOT="subgroupBallot",$T.SUBGROUP_ADD="subgroupAdd",$T.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",$T.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",$T.SUBGROUP_MUL="subgroupMul",$T.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",$T.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",$T.SUBGROUP_AND="subgroupAnd",$T.SUBGROUP_OR="subgroupOr",$T.SUBGROUP_XOR="subgroupXor",$T.SUBGROUP_MIN="subgroupMin",$T.SUBGROUP_MAX="subgroupMax",$T.SUBGROUP_ALL="subgroupAll",$T.SUBGROUP_ANY="subgroupAny",$T.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",$T.QUAD_SWAP_X="quadSwapX",$T.QUAD_SWAP_Y="quadSwapY",$T.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",$T.SUBGROUP_BROADCAST="subgroupBroadcast",$T.SUBGROUP_SHUFFLE="subgroupShuffle",$T.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",$T.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",$T.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",$T.QUAD_BROADCAST="quadBroadcast";const WT=un($T,$T.SUBGROUP_ELECT).setParameterLength(0),HT=un($T,$T.SUBGROUP_BALLOT).setParameterLength(1),qT=un($T,$T.SUBGROUP_ADD).setParameterLength(1),jT=un($T,$T.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),XT=un($T,$T.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),KT=un($T,$T.SUBGROUP_MUL).setParameterLength(1),QT=un($T,$T.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),YT=un($T,$T.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),ZT=un($T,$T.SUBGROUP_AND).setParameterLength(1),JT=un($T,$T.SUBGROUP_OR).setParameterLength(1),e_=un($T,$T.SUBGROUP_XOR).setParameterLength(1),t_=un($T,$T.SUBGROUP_MIN).setParameterLength(1),r_=un($T,$T.SUBGROUP_MAX).setParameterLength(1),s_=un($T,$T.SUBGROUP_ALL).setParameterLength(0),i_=un($T,$T.SUBGROUP_ANY).setParameterLength(0),n_=un($T,$T.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),a_=un($T,$T.QUAD_SWAP_X).setParameterLength(1),o_=un($T,$T.QUAD_SWAP_Y).setParameterLength(1),u_=un($T,$T.QUAD_SWAP_DIAGONAL).setParameterLength(1),l_=un($T,$T.SUBGROUP_BROADCAST).setParameterLength(2),d_=un($T,$T.SUBGROUP_SHUFFLE).setParameterLength(2),c_=un($T,$T.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),h_=un($T,$T.SUBGROUP_SHUFFLE_UP).setParameterLength(2),p_=un($T,$T.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),g_=un($T,$T.QUAD_BROADCAST).setParameterLength(1);let m_;function f_(e){m_=m_||new WeakMap;let t=m_.get(e);return void 0===t&&m_.set(e,t={}),t}function y_(e){const t=f_(e);return t.shadowMatrix||(t.shadowMatrix=Sa("mat4").setGroup(_a).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 b_(e,t=cc){const r=y_(e).mul(t);return r.xyz.div(r.w)}function x_(e){const t=f_(e);return t.position||(t.position=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld)))}function T_(e){const t=f_(e);return t.targetPosition||(t.targetPosition=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld)))}function __(e){const t=f_(e);return t.viewPosition||(t.viewPosition=Sa(new r).setGroup(_a).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const v_=e=>Dd.transformDirection(x_(e).sub(T_(e))),N_=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},S_=new WeakMap,R_=[];class E_ extends ci{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Vn("vec3","totalDiffuse"),this.totalSpecularNode=Vn("vec3","totalSpecular"),this.outgoingLightNode=Vn("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(tn(e));else{let s=null;if(null!==r&&(s=N_(e.id,r)),null===s){const t=i.getLightNodeClass(e.constructor);if(null===t){d(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===S_.has(e)&&S_.set(e,new t(e)),s=S_.get(e)}t.push(s)}this._lightNodes=t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=Rn(null!==l?l.mix(g,u):u)),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class A_ extends ci{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ri.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){w_.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||cc)}}const w_=Vn("vec3","shadowPositionWorld");function C_(t,r={}){return r.toneMapping=t.toneMapping,r.toneMappingExposure=t.toneMappingExposure,r.outputColorSpace=t.outputColorSpace,r.renderTarget=t.getRenderTarget(),r.activeCubeFace=t.getActiveCubeFace(),r.activeMipmapLevel=t.getActiveMipmapLevel(),r.renderObjectFunction=t.getRenderObjectFunction(),r.pixelRatio=t.getPixelRatio(),r.mrt=t.getMRT(),r.clearColor=t.getClearColor(r.clearColor||new e),r.clearAlpha=t.getClearAlpha(),r.autoClear=t.autoClear,r.scissorTest=t.getScissorTest(),r}function M_(e,t){return t=C_(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function B_(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)}function F_(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function L_(e,t){return t=F_(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function P_(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function D_(e,t,r){return r=L_(t,r=M_(e,r))}function U_(e,t,r){B_(e,r),P_(t,r)}var I_=Object.freeze({__proto__:null,resetRendererAndSceneState:D_,resetRendererState:M_,resetSceneState:L_,restoreRendererAndSceneState:U_,restoreRendererState:B_,restoreSceneState:P_,saveRendererAndSceneState:function(e,t,r={}){return r=F_(t,r=C_(e,r))},saveRendererState:C_,saveSceneState:F_});const O_=new WeakMap,V_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Kl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)}),k_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=qc("radius","float",r).setGroup(_a),o=_n(1).div(n),u=a.mul(o.x),l=_x(dd.xy).mul(6.28318530718);return La(i(t.xy.add(vx(0,5,l).mul(u)),t.z),i(t.xy.add(vx(1,5,l).mul(u)),t.z),i(t.xy.add(vx(2,5,l).mul(u)),t.z),i(t.xy.add(vx(3,5,l).mul(u)),t.z),i(t.xy.add(vx(4,5,l).mul(u)),t.z)).mul(.2)}),G_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=_n(1).div(n),o=a.x,u=a.y,l=t.xy,d=Eo(l.mul(n).add(.5));return l.subAssign(d.mul(a)),La(i(l,t.z),i(l.add(_n(o,0)),t.z),i(l.add(_n(0,u)),t.z),i(l.add(a),t.z),gu(i(l.add(_n(o.negate(),0)),t.z),i(l.add(_n(o.mul(2),0)),t.z),d.x),gu(i(l.add(_n(o.negate(),u)),t.z),i(l.add(_n(o.mul(2),u)),t.z),d.x),gu(i(l.add(_n(0,u.negate())),t.z),i(l.add(_n(0,u.mul(2))),t.z),d.y),gu(i(l.add(_n(o,u.negate())),t.z),i(l.add(_n(o,u.mul(2))),t.z),d.y),gu(gu(i(l.add(_n(o.negate(),u.negate())),t.z),i(l.add(_n(o.mul(2),u.negate())),t.z),d.x),gu(i(l.add(_n(o.negate(),u.mul(2))),t.z),i(l.add(_n(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)}),z_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r},s)=>{let i=Kl(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=i.x,a=eu(1e-7,i.y.mul(i.y)),o=s.renderer.reversedDepthBuffer?tu(n,t.z):tu(t.z,n),u=yn(1).toVar();return gn(o.notEqual(1),()=>{const e=t.z.sub(n);let r=a.div(a.add(e.mul(e)));r=mu(Pa(r,.3).div(.65)),u.assign(eu(o,r))}),u}),$_=e=>{let t=O_.get(e);return void 0===t&&(t=new vg,t.colorNode=Cn(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=re,t.fog=!1,O_.set(e,t)),t},W_=e=>{const t=O_.get(e);void 0!==t&&(t.dispose(),O_.delete(e))},H_=new Ty,q_=[],j_=(e,t,r,s)=>{q_[0]=e,q_[1]=t;let i=H_.get(q_);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===pt)&&(s&&(Ys(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,...d),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,H_.set(q_,i)),q_[0]=null,q_[1]=null,i},X_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanVertical"),a=yn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(La(dd.xy,_n(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),K_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanHorizontal"),a=yn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(La(dd.xy,_n(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(La(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),Q_=[V_,k_,G_,z_];let Y_;const Z_=new gx;class J_ extends A_{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:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,yn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=r.biasNode||qc("bias","float",r).setGroup(_a);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=qc("near","float",r.camera).setGroup(_a),s=qc("far","float",r.camera).setGroup(_a);n=ig(e.negate(),t,s)}return a=Rn(a.x,a.y.oneMinus(),s.reversedDepthBuffer?n.sub(i):n.add(i)),a}getShadowFilterFn(e){return Q_[e]}setupRenderTarget(e,t){const r=new Z(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t,camera:r}=e,{light:s,shadow:i}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(i,e),o=t.shadowMap.type,u=t.hasCompatibility(E.TEXTURE_COMPARE);if(o!==ct&&o!==ht||!u?(n.minFilter=B,n.magFilter=B):(n.minFilter=le,n.magFilter=le),i.camera.coordinateSystem=r.coordinateSystem,i.camera.updateProjectionMatrix(),o===pt&&!0!==i.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}));let t=Kl(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Kl(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const s=qc("blurSamples","float",i).setGroup(_a),o=qc("radius","float",i).setGroup(_a),u=qc("mapSize","vec2",i).setGroup(_a);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new vg);l.fragmentNode=X_({samples:s,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new vg),l.fragmentNode=K_({samples:s,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=qc("intensity","float",i).setGroup(_a),d=qc("normalBias","float",i).setGroup(_a),c=y_(s),h=Rc.mul(d);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(w_.add(h));else{p=Sa("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(lc).add(c.mul(Cn(h,0)))}const g=this.setupShadowCoord(e,p),m=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=o===pt&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:f,shadowCoord:g,shadow:i,depthLayer:this.depthLayer});let b,x;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=$c(a.texture,g.xyz):(b=Kl(a.texture,g),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),x=b?gu(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():gu(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const T=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&x.toInspector(`${T} / Color`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture):Kl(this.shadowMap.texture)),x.toInspector(`${T} / Depth`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture).r.oneMinus():Ql(this.shadowMap.depthTexture,kl().mul(zl(Kl(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return cn(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let r=this._node;return this.setupShadowPosition(e),null===r&&(this._node=r=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(r=e.material.receivedShadowNode(r)),r})()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth);const a=n.name;n.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,i.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");Y_=D_(i,n,Y_),n.overrideMaterial=$_(r),i.setRenderObjectFunction(j_(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===pt&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,U_(i,n,Y_)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),Z_.material=this.vsmMaterialVertical,Z_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Z_.material=this.vsmMaterialHorizontal,Z_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,W_(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const ev=(e,t)=>new J_(e,t),tv=new e,rv=new a,sv=new r,iv=new r,nv=[new r(1,0,0),new r(-1,0,0),new r(0,-1,0),new r(0,1,0),new r(0,0,1),new r(0,0,-1)],av=[new r(0,-1,0),new r(0,-1,0),new r(0,0,-1),new r(0,0,1),new r(0,-1,0),new r(0,-1,0)],ov=[new r(1,0,0),new r(-1,0,0),new r(0,1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1)],uv=[new r(0,-1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1),new r(0,-1,0),new r(0,-1,0)],lv=cn(({depthTexture:e,bd3D:t,dp:r})=>$c(e,t).compare(r)),dv=cn(({depthTexture:e,bd3D:t,dp:r,shadow:s})=>{const i=qc("radius","float",s).setGroup(_a),n=qc("mapSize","vec2",s).setGroup(_a),a=i.div(n.x),o=Vo(t),u=Ro(au(t,o.x.greaterThan(o.z).select(Rn(0,1,0),Rn(1,0,0)))),l=au(t,u),d=_x(dd.xy).mul(6.28318530718),c=vx(0,5,d),h=vx(1,5,d),p=vx(2,5,d),g=vx(3,5,d),m=vx(4,5,d);return $c(e,t.add(u.mul(c.x).add(l.mul(c.y)).mul(a))).compare(r).add($c(e,t.add(u.mul(h.x).add(l.mul(h.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(p.x).add(l.mul(p.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(g.x).add(l.mul(g.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(m.x).add(l.mul(m.y)).mul(a))).compare(r)).mul(.2)}),cv=cn(({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s},i)=>{const n=r.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),u=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.near),l=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.far),d=qc("bias","float",s).setGroup(_a),c=yn(1).toVar();return gn(o.sub(l).lessThanEqual(0).and(o.sub(u).greaterThanEqual(0)),()=>{let r;i.renderer.reversedDepthBuffer?(r=rg(o.negate(),u,l),r.subAssign(d)):(r=tg(o.negate(),u,l),r.addAssign(d));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:r,shadow:s}))}),c});class hv extends J_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===gt?lv:dv}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i}){return cv({filterFn:t,depthTexture:r,shadowCoord:s,shadow:i})}setupRenderTarget(e,t){const r=new mt(e.mapSize.width);r.name="PointShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createCubeRenderTarget(e.mapSize.width);return s.texture.name="PointShadowMap",s.depthTexture=r,{shadowMap:s,depthTexture:r}}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.camera,o=t.matrix,u=i.coordinateSystem===h,l=u?nv:ov,d=u?av:uv;r.setSize(t.mapSize.width,t.mapSize.width);const c=i.autoClear,p=i.getClearColor(tv),g=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(r,e),i.clear();const u=s.distance||a.far;u!==a.far&&(a.far=u,a.updateProjectionMatrix()),sv.setFromMatrixPosition(s.matrixWorld),a.position.copy(sv),iv.copy(a.position),iv.add(l[e]),a.up.copy(d[e]),a.lookAt(iv),a.updateMatrixWorld(),o.makeTranslation(-sv.x,-sv.y,-sv.z),rv.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(rv,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${e+1}`,i.render(n,a),n.name=c}i.autoClear=c,i.setClearColor(p,g)}}const pv=(e,t)=>new hv(e,t);class gv extends Op{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Sa(this.color).setGroup(_a),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ri.FRAME,t&&t.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},t.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 __(this.light).sub(e.context.positionView||pc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return ev(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?tn(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(r=e.context.getShadow(this,e)),this.colorNode=r}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),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const mv=cn(({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)}),fv=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=mv({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class yv extends gv{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(2).setGroup(_a)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return pv(this.light)}setupDirect(e){return fv({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const bv=cn(([e=kl()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()}),xv=cn(([e=kl()],{renderer:t,material:r})=>{const s=pu(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.currentSamples>0){const e=yn(s.fwidth()).toVar();i=bu(e.oneMinus(),e.add(1),s).oneMinus()}else i=Au(s.greaterThan(1),0,1);return i}),Tv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=Tn(e).toVar();return Au(n,i,s)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),_v=cn(([e,t])=>{const r=Tn(t).toVar(),s=yn(e).toVar();return Au(r,s.negate(),s)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),vv=cn(([e])=>{const t=yn(e).toVar();return bn(No(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Nv=cn(([e,t])=>{const r=yn(e).toVar();return t.assign(vv(r)),r.sub(yn(t))}),Sv=Vb([cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=yn(s).toVar(),l=yn(r).toVar(),d=yn(t).toVar(),c=yn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=Rn(s).toVar(),l=Rn(r).toVar(),d=Rn(t).toVar(),c=Rn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),Rv=Vb([cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=yn(o).toVar(),m=yn(a).toVar(),f=yn(n).toVar(),y=yn(i).toVar(),b=yn(s).toVar(),x=yn(r).toVar(),T=yn(t).toVar(),_=yn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=Rn(o).toVar(),m=Rn(a).toVar(),f=Rn(n).toVar(),y=Rn(i).toVar(),b=Rn(s).toVar(),x=Rn(r).toVar(),T=Rn(t).toVar(),_=Rn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),Ev=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=xn(e).toVar(),a=xn(n.bitAnd(xn(7))).toVar(),o=yn(Tv(a.lessThan(xn(4)),i,s)).toVar(),u=yn(Da(2,Tv(a.lessThan(xn(4)),s,i))).toVar();return _v(o,Tn(a.bitAnd(xn(1)))).add(_v(u,Tn(a.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Av=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=xn(e).toVar(),u=xn(o.bitAnd(xn(15))).toVar(),l=yn(Tv(u.lessThan(xn(8)),a,n)).toVar(),d=yn(Tv(u.lessThan(xn(4)),n,Tv(u.equal(xn(12)).or(u.equal(xn(14))),a,i))).toVar();return _v(l,Tn(u.bitAnd(xn(1)))).add(_v(d,Tn(u.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),wv=Vb([Ev,Av]),Cv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=An(e).toVar();return Rn(wv(n.x,i,s),wv(n.y,i,s),wv(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Mv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=An(e).toVar();return Rn(wv(o.x,a,n,i),wv(o.y,a,n,i),wv(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),Bv=Vb([Cv,Mv]),Fv=cn(([e])=>{const t=yn(e).toVar();return Da(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Lv=cn(([e])=>{const t=yn(e).toVar();return Da(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Pv=Vb([Fv,cn(([e])=>{const t=Rn(e).toVar();return Da(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Dv=Vb([Lv,cn(([e])=>{const t=Rn(e).toVar();return Da(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Uv=cn(([e,t])=>{const r=bn(t).toVar(),s=xn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(bn(32).sub(r)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),Iv=cn(([e,t,r])=>{e.subAssign(r),e.bitXorAssign(Uv(r,bn(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Uv(e,bn(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Uv(t,bn(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(Uv(r,bn(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Uv(e,bn(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Uv(t,bn(4))),t.addAssign(e)}),Ov=cn(([e,t,r])=>{const s=xn(r).toVar(),i=xn(t).toVar(),n=xn(e).toVar();return s.bitXorAssign(i),s.subAssign(Uv(i,bn(14))),n.bitXorAssign(s),n.subAssign(Uv(s,bn(11))),i.bitXorAssign(n),i.subAssign(Uv(n,bn(25))),s.bitXorAssign(i),s.subAssign(Uv(i,bn(16))),n.bitXorAssign(s),n.subAssign(Uv(s,bn(4))),i.bitXorAssign(n),i.subAssign(Uv(n,bn(14))),s.bitXorAssign(i),s.subAssign(Uv(i,bn(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Vv=cn(([e])=>{const t=xn(e).toVar();return yn(t).div(yn(xn(bn(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),kv=cn(([e])=>{const t=yn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),Gv=Vb([cn(([e])=>{const t=bn(e).toVar(),r=xn(xn(1)).toVar(),s=xn(xn(bn(3735928559)).add(r.shiftLeft(xn(2))).add(xn(13))).toVar();return Ov(s.add(xn(t)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(xn(2)).toVar(),n=xn().toVar(),a=xn().toVar(),o=xn().toVar();return n.assign(a.assign(o.assign(xn(bn(3735928559)).add(i.shiftLeft(xn(2))).add(xn(13))))),n.addAssign(xn(s)),a.addAssign(xn(r)),Ov(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(xn(3)).toVar(),o=xn().toVar(),u=xn().toVar(),l=xn().toVar();return o.assign(u.assign(l.assign(xn(bn(3735928559)).add(a.shiftLeft(xn(2))).add(xn(13))))),o.addAssign(xn(n)),u.addAssign(xn(i)),l.addAssign(xn(s)),Ov(o,u,l)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),cn(([e,t,r,s])=>{const i=bn(s).toVar(),n=bn(r).toVar(),a=bn(t).toVar(),o=bn(e).toVar(),u=xn(xn(4)).toVar(),l=xn().toVar(),d=xn().toVar(),c=xn().toVar();return l.assign(d.assign(c.assign(xn(bn(3735928559)).add(u.shiftLeft(xn(2))).add(xn(13))))),l.addAssign(xn(o)),d.addAssign(xn(a)),c.addAssign(xn(n)),Iv(l,d,c),l.addAssign(xn(i)),Ov(l,d,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),cn(([e,t,r,s,i])=>{const n=bn(i).toVar(),a=bn(s).toVar(),o=bn(r).toVar(),u=bn(t).toVar(),l=bn(e).toVar(),d=xn(xn(5)).toVar(),c=xn().toVar(),h=xn().toVar(),p=xn().toVar();return c.assign(h.assign(p.assign(xn(bn(3735928559)).add(d.shiftLeft(xn(2))).add(xn(13))))),c.addAssign(xn(l)),h.addAssign(xn(u)),p.addAssign(xn(o)),Iv(c,h,p),c.addAssign(xn(a)),h.addAssign(xn(n)),Ov(c,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),zv=Vb([cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(Gv(s,r)).toVar(),n=An().toVar();return n.x.assign(i.bitAnd(bn(255))),n.y.assign(i.shiftRight(bn(8)).bitAnd(bn(255))),n.z.assign(i.shiftRight(bn(16)).bitAnd(bn(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(Gv(n,i,s)).toVar(),o=An().toVar();return o.x.assign(a.bitAnd(bn(255))),o.y.assign(a.shiftRight(bn(8)).bitAnd(bn(255))),o.z.assign(a.shiftRight(bn(16)).bitAnd(bn(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),$v=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=yn(Sv(wv(Gv(r,s),i,n),wv(Gv(r.add(bn(1)),s),i.sub(1),n),wv(Gv(r,s.add(bn(1))),i,n.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=yn(Rv(wv(Gv(r,s,i),n,a,o),wv(Gv(r.add(bn(1)),s,i),n.sub(1),a,o),wv(Gv(r,s.add(bn(1)),i),n,a.sub(1),o),wv(Gv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),wv(Gv(r,s,i.add(bn(1))),n,a,o.sub(1)),wv(Gv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),wv(Gv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Dv(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),Wv=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=Rn(Sv(Bv(zv(r,s),i,n),Bv(zv(r.add(bn(1)),s),i.sub(1),n),Bv(zv(r,s.add(bn(1))),i,n.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=Rn(Rv(Bv(zv(r,s,i),n,a,o),Bv(zv(r.add(bn(1)),s,i),n.sub(1),a,o),Bv(zv(r,s.add(bn(1)),i),n,a.sub(1),o),Bv(zv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),Bv(zv(r,s,i.add(bn(1))),n,a,o.sub(1)),Bv(zv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),Bv(zv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Dv(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),Hv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Vv(Gv(r))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Vv(Gv(r,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Vv(Gv(r,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Vv(Gv(r,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),qv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Rn(Vv(Gv(r,bn(0))),Vv(Gv(r,bn(1))),Vv(Gv(r,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Rn(Vv(Gv(r,s,bn(0))),Vv(Gv(r,s,bn(1))),Vv(Gv(r,s,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Rn(Vv(Gv(r,s,i,bn(0))),Vv(Gv(r,s,i,bn(1))),Vv(Gv(r,s,i,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Rn(Vv(Gv(r,s,i,n,bn(0))),Vv(Gv(r,s,i,n,bn(1))),Vv(Gv(r,s,i,n,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),jv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=yn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul($v(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Xv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul(Wv(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Kv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar();return _n(jv(o,a,n,i),jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Qv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(Xv(o,a,n,i)).toVar(),l=yn(jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i)).toVar();return Cn(u,l)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Yv=Vb([cn(([e,t,r,s,i,n,a])=>{const o=bn(a).toVar(),u=yn(n).toVar(),l=bn(i).toVar(),d=bn(s).toVar(),c=bn(r).toVar(),h=bn(t).toVar(),p=_n(e).toVar(),g=Rn(qv(_n(h.add(d),c.add(l)))).toVar(),m=_n(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=_n(_n(yn(h),yn(c)).add(m)).toVar(),y=_n(f.sub(p)).toVar();return gn(o.equal(bn(2)),()=>Vo(y.x).add(Vo(y.y))),gn(o.equal(bn(3)),()=>eu(Vo(y.x),Vo(y.y))),nu(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),cn(([e,t,r,s,i,n,a,o,u])=>{const l=bn(u).toVar(),d=yn(o).toVar(),c=bn(a).toVar(),h=bn(n).toVar(),p=bn(i).toVar(),g=bn(s).toVar(),m=bn(r).toVar(),f=bn(t).toVar(),y=Rn(e).toVar(),b=Rn(qv(Rn(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=Rn(Rn(yn(f),yn(m),yn(g)).add(b)).toVar(),T=Rn(x.sub(y)).toVar();return gn(l.equal(bn(2)),()=>Vo(T.x).add(Vo(T.y)).add(Vo(T.z))),gn(l.equal(bn(3)),()=>eu(Vo(T.x),Vo(T.y),Vo(T.z))),nu(T,T)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),Zv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();l.assign(Jo(l,r))})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Jv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.y.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),eN=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(r)}).ElseIf(r.lessThan(l.z),()=>{l.z.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),tN=Vb([Zv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();d.assign(Jo(d,n))})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),rN=Vb([Jv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.y.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),sN=Vb([eN,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.z.assign(d.y),d.y.assign(n)}).ElseIf(n.lessThan(d.z),()=>{d.z.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),iN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=_n(t).toVar(),p=_n(r).toVar(),g=_n(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(Rn(v,0),x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),nN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=Rn(t).toVar(),p=Rn(r).toVar(),g=Rn(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(v,x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),aN=cn(([e])=>{const t=e.y,r=e.z,s=Rn().toVar();return gn(t.lessThan(1e-4),()=>{s.assign(Rn(r,r,r))}).Else(()=>{let i=e.x;i=i.sub(No(i)).mul(6).toVar();const n=bn(Xo(i)),a=i.sub(yn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());gn(n.equal(bn(0)),()=>{s.assign(Rn(r,l,o))}).ElseIf(n.equal(bn(1)),()=>{s.assign(Rn(u,r,o))}).ElseIf(n.equal(bn(2)),()=>{s.assign(Rn(o,r,l))}).ElseIf(n.equal(bn(3)),()=>{s.assign(Rn(o,u,r))}).ElseIf(n.equal(bn(4)),()=>{s.assign(Rn(l,o,r))}).Else(()=>{s.assign(Rn(r,o,u))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),oN=cn(([e])=>{const t=Rn(e).toVar(),r=yn(t.x).toVar(),s=yn(t.y).toVar(),i=yn(t.z).toVar(),n=yn(Jo(r,Jo(s,i))).toVar(),a=yn(eu(r,eu(s,i))).toVar(),o=yn(a.sub(n)).toVar(),u=yn().toVar(),l=yn().toVar(),d=yn().toVar();return d.assign(a),gn(a.greaterThan(0),()=>{l.assign(o.div(a))}).Else(()=>{l.assign(0)}),gn(l.lessThanEqual(0),()=>{u.assign(0)}).Else(()=>{gn(r.greaterThanEqual(a),()=>{u.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{u.assign(La(2,i.sub(r).div(o)))}).Else(()=>{u.assign(La(4,r.sub(s).div(o)))}),u.mulAssign(1/6),gn(u.lessThan(0),()=>{u.addAssign(1)})}),Rn(u,l,d)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),uN=cn(([e])=>{const t=Rn(e).toVar(),r=wn(Ga(t,Rn(.04045))).toVar(),s=Rn(t.div(12.92)).toVar(),i=Rn(ou(eu(t.add(Rn(.055)),Rn(0)).div(1.055),Rn(2.4))).toVar();return gu(s,i,r)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lN=(e,t)=>{e=yn(e),t=yn(t);const r=_n(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return bu(e.sub(r),e.add(r),t)},dN=(e,t,r,s)=>gu(e,t,r[s].clamp()),cN=(e,t,r,s,i)=>gu(e,t,lN(r,s[i])),hN=cn(([e,t,r])=>{const s=Ro(e).toVar(),i=Pa(yn(.5).mul(t.sub(r)),cc).div(s).toVar(),n=Pa(yn(-.5).mul(t.sub(r)),cc).div(s).toVar(),a=Rn().toVar();a.x=s.x.greaterThan(yn(0)).select(i.x,n.x),a.y=s.y.greaterThan(yn(0)).select(i.y,n.y),a.z=s.z.greaterThan(yn(0)).select(i.z,n.z);const o=Jo(a.x,a.y,a.z).toVar();return cc.add(s.mul(o)).toVar().sub(r)}),pN=cn(([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(Da(r,r).sub(Da(s,s)))),n});var gN=Object.freeze({__proto__:null,BRDF_GGX:am,BRDF_Lambert:Hg,BasicPointShadowFilter:lv,BasicShadowFilter:V_,Break:Fp,Const:Ou,Continue:()=>Cl("continue").toStack(),DFGLUT:lm,D_GGX:sm,Discard:Ml,EPSILON:ao,F_Schlick:Wg,Fn:cn,HALF_PI:ho,INFINITY:oo,If:gn,Loop:Bp,NodeAccess:ii,NodeShaderStage:ti,NodeType:si,NodeUpdateType:ri,OnBeforeMaterialUpdate:e=>Rx(Sx.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>Rx(Sx.BEFORE_OBJECT,e),OnMaterialUpdate:e=>Rx(Sx.MATERIAL,e),OnObjectUpdate:e=>Rx(Sx.OBJECT,e),PCFShadowFilter:k_,PCFSoftShadowFilter:G_,PI:uo,PI2:lo,PointShadowFilter:dv,Return:()=>Cl("return").toStack(),Schlick_to_F0:hm,ShaderNode:en,Stack:mn,Switch:(...e)=>Si.Switch(...e),TBNViewMatrix:xh,TWO_PI:co,VSMShadowFilter:z_,V_GGX_SmithCorrelated:tm,Var:Iu,VarIntent:Vu,abs:Vo,acesFilmicToneMapping:dT,acos:Do,acosh:Uo,add:La,addMethodChaining:Ei,addNodeElement:function(e){d("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:gT,all:po,alphaT:Jn,and:Wa,anisotropy:ea,anisotropyB:ra,anisotropyT:ta,any:go,append:e=>(d("TSL: append() has been renamed to Stack().",new Is),mn(e)),array:Ea,arrayBuffer:e=>new vi(e,"ArrayBuffer"),asin:Lo,asinh:Po,assign:wa,atan:Io,atanh:Oo,atomicAdd:(e,t)=>zT(kT.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>zT(kT.ATOMIC_AND,e,t),atomicFunc:zT,atomicLoad:e=>zT(kT.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>zT(kT.ATOMIC_MAX,e,t),atomicMin:(e,t)=>zT(kT.ATOMIC_MIN,e,t),atomicOr:(e,t)=>zT(kT.ATOMIC_OR,e,t),atomicStore:(e,t)=>zT(kT.ATOMIC_STORE,e,t),atomicSub:(e,t)=>zT(kT.ATOMIC_SUB,e,t),atomicXor:(e,t)=>zT(kT.ATOMIC_XOR,e,t),attenuationColor:ma,attenuationDistance:ga,attribute:Vl,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ax(e,r,s);return Tp(i,t,e)},backgroundBlurriness:Bx,backgroundIntensity:Fx,backgroundRotation:Lx,batch:Ep,bentNormalView:_h,billboarding:Hb,bitAnd:Xa,bitNot:Ka,bitOr:Qa,bitXor:Ya,bitangentGeometry:mh,bitangentLocal:fh,bitangentView:yh,bitangentWorld:bh,bitcast:yb,blendBurn:mg,blendColor:xg,blendDodge:fg,blendOverlay:bg,blendScreen:yg,blur:pf,bool:Tn,buffer:Zl,bufferAttribute:ul,builtin:sd,builtinAOContext:Lu,builtinShadowContext:Fu,bumpMap:Ch,bvec2:Sn,bvec3:wn,bvec4:Fn,bypass:Rl,cache:Nl,call:Ma,cameraFar:Fd,cameraIndex:Md,cameraNear:Bd,cameraNormalMatrix:Id,cameraPosition:Od,cameraProjectionMatrix:Ld,cameraProjectionMatrixInverse:Pd,cameraViewMatrix:Dd,cameraViewport:Vd,cameraWorldMatrix:Ud,cbrt:hu,cdl:Qx,ceil:So,checker:bv,cineonToneMapping:uT,clamp:mu,clearcoat:qn,clearcoatNormalView:Ec,clearcoatRoughness:jn,clipSpace:oc,code:yT,color:fn,colorSpaceToWorking:Qu,colorToDirection:e=>tn(e).mul(2).sub(1),compute:Tl,computeKernel:xl,computeSkinning:(e,t=null)=>{const r=new wp(e);return r.positionNode=Tp(new q(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinIndexNode=Tp(new q(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinWeightNode=Tp(new q(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.bindMatrixNode=Sa(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Sa(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=Zl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,tn(r)},context:Cu,convert:In,convertColorSpace:(e,t,r)=>new Xu(tn(e),t,r),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():yx(e,...t),cos:Co,cosh:Mo,countLeadingZeros:vb,countOneBits:Nb,countTrailingZeros:_b,cross:au,cubeTexture:$c,cubeTextureBase:zc,dFdx:Wo,dFdy:Ho,dashSize:ua,debug:Pl,decrement:so,decrementBefore:to,defaultBuildStages:ai,defaultShaderStages:ni,defined:Zi,degrees:fo,deltaTime:Gb,densityFogFactor:vT,depth:ag,depthPass:(e,t,r)=>new iT(iT.DEPTH,e,t,r),determinant:Yo,difference:iu,diffuseColor:Gn,diffuseContribution:zn,directPointLight:fv,directionToColor:vh,directionToFaceDirection:bc,dispersion:fa,disposeShadowMaterial:W_,distance:su,div:Ua,dot:nu,drawIndex:yl,dynamicBufferAttribute:(e,t=null,r=0,s=0)=>ol(e,t,r,s,x),element:Un,emissive:$n,equal:Oa,equirectUV:Bg,exp:yo,exp2:bo,exponentialHeightFogFactor:NT,expression:Cl,faceDirection:yc,faceForward:xu,faceforward:Su,float:yn,floatBitsToInt:e=>new fb(e,"int","float"),floatBitsToUint:bb,floor:No,fog:ST,fract:Eo,frameGroup:Ta,frameId:zb,frontFacing:fc,fwidth:Ko,gain:(e,t)=>e.lessThan(.5)?Rb(e.mul(2),t).div(2):Pa(1,Rb(Da(Pa(1,e),2),t).div(2)),gapSize:la,getConstNodeType:Ji,getCurrentStack:pn,getDirection:lf,getDistanceAttenuation:mv,getGeometryRoughness:Jg,getNormalFromDepth:Tx,getParallaxCorrectNormal:hN,getRoughness:em,getScreenPosition:xx,getShIrradianceAt:pN,getShadowMaterial:$_,getShadowRenderObjectFunction:j_,getTextureIndex:pb,getViewPosition:bx,ggxConvolution:yf,globalId:LT,glsl:(e,t)=>yT(e,t,"glsl"),glslFn:(e,t)=>xT(e,t,"glsl"),grayscale:Hx,greaterThan:Ga,greaterThanEqual:$a,hash:Sb,highpModelNormalViewMatrix:ac,highpModelViewMatrix:nc,hue:Xx,increment:ro,incrementBefore:eo,inspector:Il,instance:vp,instanceIndex:pl,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ex(e,r,s);return Tp(i,t,i.count)},instancedBufferAttribute:ll,instancedDynamicBufferAttribute:dl,instancedMesh:Sp,int:bn,intBitsToFloat:e=>new fb(e,"float","int"),interleavedGradientNoise:_x,inverse:Zo,inverseSqrt:vo,inversesqrt:Ru,invocationLocalIndex:fl,invocationSubgroupIndex:ml,ior:ca,iridescence:Qn,iridescenceIOR:Yn,iridescenceThickness:Zn,isolate:vl,ivec2:vn,ivec3:En,ivec4:Mn,js:(e,t)=>yT(e,t,"js"),label:Pu,length:Go,lengthSq:pu,lessThan:ka,lessThanEqual:za,lightPosition:x_,lightProjectionUV:b_,lightShadowMatrix:y_,lightTargetDirection:v_,lightTargetPosition:T_,lightViewPosition:__,lightingContext:Gp,lights:(e=[])=>(new E_).setLights(e),linearDepth:og,linearToneMapping:aT,localId:PT,log:xo,log2:To,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(xo(r.div(t)));return yn(Math.E).pow(s).mul(t).negate()},luminance:Kx,mat2:Ln,mat3:Pn,mat4:Dn,matcapUV:ey,materialAO:gp,materialAlphaTest:Fh,materialAnisotropy:Yh,materialAnisotropyVector:mp,materialAttenuationColor:np,materialAttenuationDistance:ip,materialClearcoat:Hh,materialClearcoatNormal:jh,materialClearcoatRoughness:qh,materialColor:Lh,materialDispersion:hp,materialEmissive:Dh,materialEnvIntensity:Pc,materialEnvRotation:Dc,materialIOR:sp,materialIridescence:Zh,materialIridescenceIOR:Jh,materialIridescenceThickness:ep,materialLightMap:pp,materialLineDashOffset:dp,materialLineDashSize:op,materialLineGapSize:up,materialLineScale:ap,materialLineWidth:lp,materialMetalness:$h,materialNormal:Wh,materialOpacity:Uh,materialPointSize:cp,materialReference:Kc,materialReflectivity:Gh,materialRefractionRatio:Lc,materialRotation:Xh,materialRoughness:zh,materialSheen:Kh,materialSheenRoughness:Qh,materialShininess:Ph,materialSpecular:Ih,materialSpecularColor:Vh,materialSpecularIntensity:Oh,materialSpecularStrength:kh,materialThickness:rp,materialTransmission:tp,max:eu,maxMipLevel:Wl,mediumpModelViewMatrix:ic,metalness:Hn,min:Jo,mix:gu,mixElement:_u,mod:Ia,modInt:io,modelDirection:Kd,modelNormalMatrix:tc,modelPosition:Yd,modelRadius:ec,modelScale:Zd,modelViewMatrix:sc,modelViewPosition:Jd,modelViewProjection:fp,modelWorldMatrix:Qd,modelWorldMatrixInverse:rc,morphReference:Ip,mrt:mb,mul:Da,mx_aastep:lN,mx_add:(e,t=yn(0))=>La(e,t),mx_atan2:(e=yn(0),t=yn(1))=>Io(e,t),mx_cell_noise_float:(e=kl())=>Hv(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>yn(e).sub(r).mul(t).add(r),mx_divide:(e,t=yn(1))=>Ua(e,t),mx_fractal_noise_float:(e=kl(),t=3,r=2,s=.5,i=1)=>jv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec2:(e=kl(),t=3,r=2,s=.5,i=1)=>Kv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec3:(e=kl(),t=3,r=2,s=.5,i=1)=>Xv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec4:(e=kl(),t=3,r=2,s=.5,i=1)=>Qv(e,bn(t),r,s).mul(i),mx_frame:()=>zb,mx_heighttonormal:(e,t)=>(e=Rn(e),t=yn(t),Ch(e,t)),mx_hsvtorgb:aN,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=yn(1))=>Pa(t,e),mx_modulo:(e,t=yn(1))=>Ia(e,t),mx_multiply:(e,t=yn(1))=>Da(e,t),mx_noise_float:(e=kl(),t=1,r=0)=>$v(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=kl(),t=1,r=0)=>Wv(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=kl(),t=1,r=0)=>{e=e.convert("vec2|vec3");return Cn(Wv(e),$v(e.add(_n(19,73)))).mul(t).add(r)},mx_place2d:(e,t=_n(.5,.5),r=_n(1,1),s=yn(0),i=_n(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=_n(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=yn(1))=>ou(e,t),mx_ramp4:(e,t,r,s,i=kl())=>{const n=i.x.clamp(),a=i.y.clamp(),o=gu(e,t,n),u=gu(r,s,n);return gu(o,u,a)},mx_ramplr:(e,t,r=kl())=>dN(e,t,r,"x"),mx_ramptb:(e,t,r=kl())=>dN(e,t,r,"y"),mx_rgbtohsv:oN,mx_rotate2d:(e,t)=>{e=_n(e);const r=(t=yn(t)).mul(Math.PI/180);return iy(e,r)},mx_rotate3d:(e,t,r)=>{e=Rn(e),t=yn(t),r=Rn(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=yn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=yn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=kl())=>cN(e,t,r,s,"x"),mx_splittb:(e,t,r,s=kl())=>cN(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:uN,mx_subtract:(e,t=yn(0))=>Pa(e,t),mx_timer:()=>kb,mx_transform_uv:(e=1,t=0,r=kl())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>iN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>nN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=kl(),t=1)=>tN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec2:(e=kl(),t=1)=>rN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec3:(e=kl(),t=1)=>sN(e.convert("vec2|vec3"),t,bn(1)),negate:zo,neutralToneMapping:mT,nodeArray:nn,nodeImmutable:on,nodeObject:tn,nodeObjectIntent:rn,nodeObjects:sn,nodeProxy:an,nodeProxyIntent:un,normalFlat:_c,normalGeometry:xc,normalLocal:Tc,normalMap:Rh,normalView:Sc,normalViewGeometry:vc,normalWorld:Rc,normalWorldGeometry:Nc,normalize:Ro,not:qa,notEqual:Va,numWorkgroups:BT,objectDirection:zd,objectGroup:va,objectPosition:Wd,objectRadius:jd,objectScale:Hd,objectViewPosition:qd,objectWorldMatrix:$d,oneMinus:$o,or:Ha,orthographicDepthToViewZ:eg,oscSawtooth:(e=kb)=>e.fract(),oscSine:(e=kb)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=kb)=>e.fract().round(),oscTriangle:(e=kb)=>e.add(.5).fract().mul(2).sub(1).abs(),output:oa,outputStruct:lb,overloadingFn:Vb,packHalf2x16:Cb,packSnorm2x16:Ab,packUnorm2x16:wb,parabola:Rb,parallaxDirection:Th,parallaxUV:(e,t)=>e.sub(Th.mul(t)),parameter:(e,t)=>new sb(e,t),pass:(e,t,r)=>new iT(iT.COLOR,e,t,r),passTexture:(e,t)=>new rT(e,t),pcurve:(e,t,r)=>ou(Ua(ou(e,t),La(ou(e,t),ou(Pa(1,e),r))),1/t),perspectiveDepthToViewZ:sg,pmremTexture:Vf,pointShadow:pv,pointUV:Cx,pointWidth:da,positionGeometry:uc,positionLocal:lc,positionPrevious:dc,positionView:pc,positionViewDirection:gc,positionWorld:cc,positionWorldDirection:hc,posterize:Yx,pow:ou,pow2:uu,pow3:lu,pow4:du,premultiplyAlpha:Tg,property:Vn,quadBroadcast:g_,quadSwapDiagonal:u_,quadSwapX:a_,quadSwapY:o_,radians:mo,rand:Tu,range:wT,rangeFogFactor:_T,reciprocal:jo,reference:qc,referenceBuffer:jc,reflect:ru,reflectVector:Oc,reflectView:Uc,reflector:e=>new lx(e),refract:yu,refractVector:Vc,refractView:Ic,reinhardToneMapping:oT,remap:El,remapClamp:Al,renderGroup:_a,renderOutput:Fl,rendererReference:el,replaceDefaultUV:function(e,t=null){return Cu(t,{getUV:"function"==typeof e?e:()=>e})},rotate:iy,rotateUV:$b,roughness:Wn,round:qo,rtt:yx,sRGBTransferEOTF:Hu,sRGBTransferOETF:qu,sample:(e,t=null)=>new Nx(e,tn(t)),sampler:e=>(!0===e.isNode?e:Kl(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Kl(e)).convert("samplerComparison"),saturate:fu,saturation:qx,screenCoordinate:dd,screenDPR:od,screenSize:ld,screenUV:ud,select:Au,setCurrentStack:hn,setName:Bu,shaderStages:oi,shadow:ev,shadowPositionWorld:w_,shapeCircle:xv,sharedUniformGroup:xa,sheen:Xn,sheenRoughness:Kn,shiftLeft:Za,shiftRight:Ja,shininess:aa,sign:ko,sin:Ao,sinc:(e,t)=>Ao(uo.mul(t.mul(e).sub(1))).div(uo.mul(t.mul(e).sub(1))),sinh:wo,skinning:Cp,smoothstep:bu,smoothstepElement:vu,specularColor:sa,specularColorBlended:ia,specularF90:na,spherizeUV:Wb,split:(e,t)=>new yi(tn(e),t),spritesheetUV:jb,sqrt:_o,stack:nb,step:tu,stepElement:Nu,storage:Tp,storageBarrier:()=>IT("storage").toStack(),storageTexture:Dx,string:(e="")=>new vi(e,"string"),struct:(e,t=null)=>{const r=new ab(e,t),s=(...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;eOx(e,t).level(r),texture3DLoad:(...e)=>Ox(...e).setSampler(!1),textureBarrier:()=>IT("texture").toStack(),textureBicubic:Fm,textureBicubicLevel:Bm,textureCubeUV:df,textureLevel:(e,t,r)=>Kl(e,t).level(r),textureLoad:Ql,textureSize:zl,textureStore:(e,t,r)=>{let s;return!0===e.isStorageTextureNode?(s=e.clone(),s.uvNode=t,s.storeNode=r):s=Dx(e,t,r),null!==r&&s.toStack(),s},thickness:pa,time:kb,toneMapping:rl,toneMappingExposure:sl,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>new nT(t,r,tn(s),tn(i),tn(n)),transformDirection:cu,transformNormal:Ac,transformNormalToView:wc,transformedClearcoatNormalView:Bc,transformedNormalView:Cc,transformedNormalWorld:Mc,transmission:ha,transpose:Qo,triNoise3D:Ub,triplanarTexture:(...e)=>Xb(...e),triplanarTextures:Xb,trunc:Xo,uint:xn,uintBitsToFloat:e=>new fb(e,"float","uint"),uniform:Sa,uniformArray:td,uniformCubeTexture:(e=kc)=>zc(e),uniformFlow:Mu,uniformGroup:ba,uniformTexture:(e=ql)=>Kl(e),unpackHalf2x16:Lb,unpackNormal:Nh,unpackSnorm2x16:Bb,unpackUnorm2x16:Fb,unpremultiplyAlpha:_g,userData:(e,t,r)=>new Vx(e,t,r),uv:kl,uvec2:Nn,uvec3:An,uvec4:Bn,varying:$u,varyingProperty:kn,vec2:_n,vec3:Rn,vec4:Cn,vectorComponents:ui,velocity:Wx,vertexColor:gg,vertexIndex:hl,vertexStage:Wu,vibrance:jx,viewZToLogarithmicDepth:ig,viewZToOrthographicDepth:Jp,viewZToPerspectiveDepth:tg,viewZToReversedOrthographicDepth:(e,t,r)=>e.add(r).div(r.sub(t)),viewZToReversedPerspectiveDepth:rg,viewport:cd,viewportCoordinate:pd,viewportDepthTexture:Yp,viewportLinearDepth:ug,viewportMipTexture:qp,viewportOpaqueMipTexture:Xp,viewportResolution:md,viewportSafeUV:qb,viewportSharedTexture:eT,viewportSize:hd,viewportTexture:Hp,viewportUV:gd,vogelDiskSample:vx,wgsl:(e,t)=>yT(e,t,"wgsl"),wgslFn:(e,t)=>xT(e,t,"wgsl"),workgroupArray:(e,t)=>new VT("Workgroup",e,t),workgroupBarrier:()=>IT("workgroup").toStack(),workgroupId:FT,workingToColorSpace:Ku,xor:ja});const mN=new rb;class fN extends Ry{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,r){const s=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)s._clearColor.getRGB(mN),mN.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(mN),mN.a=1,n=!0;else if(!0===i.isNode){const u=this.get(e),l=i;mN.copy(s._clearColor);let d=u.backgroundMesh;if(void 0===d){const h=Cn(l).mul(Fx).context({getUV:()=>Lx.mul(Nc),getTextureLevel:()=>Bx}),p=Ld.element(3).element(3).equal(1),g=Ua(1,Ld.element(1).element(1)).mul(3),m=p.select(lc.mul(g),lc),f=sc.mul(Cn(m,0));let y=Ld.mul(Cn(f.xyz,1));y=y.setZ(y.w);const b=new vg;function x(){i.removeEventListener("dispose",x),d.material.dispose(),d.geometry.dispose()}b.name="Background.material",b.side=L,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=y,b.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=d=new oe(new ft(1,32,32),b),d.frustumCulled=!1,d.name="Background.mesh",i.addEventListener("dispose",x)}const c=l.getCacheKey();u.backgroundCacheKey!==c&&(u.backgroundMeshNode.node=Cn(l).mul(Fx),u.backgroundMeshNode.needsUpdate=!0,d.material.needsUpdate=!0,u.backgroundCacheKey=c),t.unshift(d,d.geometry,d.material,0,0,null,null)}else o("Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?mN.set(0,0,0,1):"alpha-blend"===a&&mN.set(0,0,0,0),!0===s.autoClear||!0===n){const T=r.clearColorValue;T.r=mN.r,T.g=mN.g,T.b=mN.b,T.a=mN.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(T.r*=T.a,T.g*=T.a,T.b*=T.a),r.depthClearValue=s.getClearDepth(),r.stencilClearValue=s.getClearStencil(),r.clearColor=!0===s.autoClearColor,r.clearDepth=!0===s.autoClearDepth,r.clearStencil=!0===s.autoClearStencil}else r.clearColor=!1,r.clearDepth=!1,r.clearStencil=!1}}let yN=0;class bN{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=yN++}}class xN{constructor(e,t,r,s,i,n,a,o,u,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=l,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new bN(t.name,[]);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class TN{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class _N{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}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 vN{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class NN extends vN{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class SN{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let RN=0;class EN{constructor(e=null){this.id=RN++,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 AN{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class wN{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 CN extends wN{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class MN extends wN{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class BN extends wN{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class FN extends wN{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class LN extends wN{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class PN extends wN{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class DN extends wN{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class UN extends wN{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class IN extends CN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ON extends MN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class VN extends BN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kN extends FN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GN extends LN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zN extends PN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $N extends DN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class WN extends UN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let HN=0;const qN=new WeakMap,jN=new WeakMap,XN=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),KN=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class QN{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=nb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new EN,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:HN++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&e.blending===tt&&!1===e.alphaToCoverage}createRenderTarget(e,t,r){return new ne(e,t,r)}createCubeRenderTarget(e,t){return new Fg(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=t[0].groupNode;let s,i=r.shared;if(i)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)r+=t.nodeUniform.node.id}else r+=e.nodeUniform.id;const i=this.renderer._currentRenderContext||this.renderer;let n=qN.get(i);void 0===n&&(n=new Map,qN.set(i,n));const a=Vs(r);s=n.get(a),void 0===s&&(s=new bN(e,t),n.set(a,s))}else s=new bN(e,t);return s}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of oi)for(const s in r[e]){const i=r[e][s],n=t[s]||(t[s]=[]);for(const e of i)!1===n.includes(e)&&n.push(e)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(n)}u`:"0u";if("bool"===i)return n?"true":"false";if("color"===i)return`${this.getType("vec3")}( ${KN(n.r)}, ${KN(n.g)}, ${KN(n.b)} )`;const a=this.getTypeLength(i),o=this.getComponentType(i),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==i)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(i)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(i)}()`;throw new Error(`NodeBuilder: Type '${i}' 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 r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new TN(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===R)return"int";if(t===S)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=Ws(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return XN.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof xt||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=nb(this.stack);const e=pn();return this.stacks.push(e),hn(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,hn(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const r=this.getDataFromNode(e,"vertex");let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new TN("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new AN(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new _N(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new vN(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new NN(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let i=1,n=s;for(;void 0!==r[n];)n=s+"_"+i++;i>1&&(e.name=n,d(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${n}'.`)),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new SN("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!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),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new bT,r=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=r,t}flowShaderNode(e){const t=e.layout,r={[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)r[e.name]=new sb(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new EN,this.stack=nb();for(const r of ai)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){d("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){d("Abstract function.")}getVaryings(){d("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e,t=!1){const r=[],s=this.vars[e];if(void 0!==s)for(const e of s)r.push(`${this.getVar(e.type,e.name,e.count)};`);return r.join(t?"\n":"\n\t")}getUniforms(){d("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}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(){d("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 r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}prebuild(){const{object:e,renderer:t,material:r}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:o('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),r&&r.contextNode&&(!0===r.contextNode.isContextNode?this.context={...this.context,...r.contextNode.getFlowContextData()}:o('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==r){let e=t.library.fromMaterial(r);null===e&&(o(`NodeBuilder: Material "${r.type}" is not compatible.`),e=new vg),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"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 ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this);await Tt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=jN.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const r=this.getSharedDataFromNode(e);let s=r.cache;if(void 0===s){if("float"===t||"int"===t||"uint"===t)s=new IN(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)s=new ON(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)s=new VN(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)s=new kN(e);else if("color"===t)s=new GN(e);else if("mat2"===t)s=new zN(e);else if("mat3"===t)s=new $N(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);s=new WN(e)}r.cache=s}return s}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${_t} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Ys(this.object).useVelocity}}class YN{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderId:0,frameId:0},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateBeforeMap,r);if(t.frameId!==this.frameId){const r=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=r)}}else if(t===ri.RENDER){const t=this._getMaps(this.updateBeforeMap,r);if(t.renderId!==this.renderId){const r=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=r)}}else t===ri.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateAfterMap,r);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateAfterMap,r);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateMap,r);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateMap,r);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&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 ZN{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}ZN.isNodeFunctionInput=!0;class JN extends gv{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class eS extends gv{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:v_(this.light),lightColor:e}}}class tS extends gv{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=x_(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Sa(new e).setGroup(_a)}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:r,lightDirectionNode:s}=this,i=Rc.dot(s).mul(.5).add(.5),n=gu(r,t,i);e.context.irradiance.addAssign(n)}}class rS extends gv{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Sa(0).setGroup(_a),this.penumbraCosNode=Sa(0).setGroup(_a),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(0).setGroup(_a),this.colorNode=Sa(this.color).setGroup(_a)}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:r,penumbraCosNode:s}=this;return bu(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=b_(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(v_(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=mv({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=Kl(i.map,h.xy).onRenderUpdate(()=>i.map)),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class sS extends rS{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);s=Kl(r,_n(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}class iS extends gv{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new r);this.lightProbe=td(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=pN(Rc,this.lightProbe);e.context.irradiance.addAssign(t)}}const nS=cn(([e,t])=>{const r=e.abs().sub(t);return Go(eu(r,0)).add(Jo(eu(r.x,r.y),0))});class aS extends rS{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=yn(0),r=this.penumbraCosNode,s=y_(this.light).mul(e.context.positionWorld||cc);return gn(s.w.greaterThan(0),()=>{const e=s.xyz.div(s.w),i=nS(e.xy.sub(_n(.5)),_n(.5)),n=Ua(-1,Pa(1,Do(r)).sub(1));t.assign(fu(i.mul(-2).mul(n)))}),t}}const oS=new a,uS=new a;let lS=null;class dS extends gv{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Sa(new r).setGroup(_a),this.halfWidth=Sa(new r).setGroup(_a),this.updateType=ri.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;uS.identity(),oS.copy(t.matrixWorld),oS.premultiply(r),uS.extractRotation(oS),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(uS),this.halfHeight.value.applyMatrix4(uS)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Kl(lS.LTC_FLOAT_1),r=Kl(lS.LTC_FLOAT_2)):(t=Kl(lS.LTC_HALF_1),r=Kl(lS.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:__(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){lS=e}}class cS{parseFunction(){d("Abstract function.")}}class hS{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){d("Abstract function.")}}hS.isNodeFunction=!0;const pS=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,gS=/[a-z_0-9]+/gi,mS="#pragma main";class fS extends hS{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(mS),r=-1!==t?e.slice(t+12):e,s=r.match(pS);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=gS.exec(i));)n.push(a);const o=[];let u=0;for(;u{let r=this._createNodeBuilder(e,e.material);try{t?await r.buildAsync():r.build()}catch(s){r=this._createNodeBuilder(e,new vg),t?await r.buildAsync():r.build(),o("TSL: "+s)}return r})().then(e=>(s=this._createNodeBuilderState(e),i.set(n,s),s.usedTimes++,r.nodeBuilderState=s,s));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(r){t=this._createNodeBuilder(e,new vg),t.build();let s=r.stackTrace;!s&&r.stack&&(s=new Is(r.stack)),o("TSL: "+r,s)}s=this._createNodeBuilderState(t),i.set(n,s)}}s.usedTimes++,r.nodeBuilderState=s}return s}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 r=this.getForRenderCacheKey(e),s=this.nodeBuilderCache.get(r);return void 0!==s?(s.usedTimes++,t.nodeBuilderState=s,s):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let r=t.nodeBuilderState;if(void 0===r){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),r=this._createNodeBuilderState(s),t.nodeBuilderState=r}return r}_createNodeBuilderState(e){return new xN(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const r=this.get(e);r.environmentNode&&(t=r.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const r=this.get(e);r.backgroundNode&&(t=r.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){bS[0]=e,bS[1]=t;const r=this.renderer.info.calls,s=this.callHashCache.get(bS)||{};if(s.callId!==r){const i=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&xS.push(t.getCacheKey(!0)),i&&xS.push(i.getCacheKey()),n&&xS.push(n.getCacheKey()),xS.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),xS.push(this.renderer.shadowMap.enabled?1:0),xS.push(this.renderer.shadowMap.type),s.callId=r,s.cacheKey=ks(xS),this.callHashCache.set(bS,s),xS.length=0}return bS[0]=null,bS[1]=null,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),r=e.background;if(r){const s=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,()=>{if(!0===r.isCubeTexture||r.mapping===ce||r.mapping===he||r.mapping===Ae){if(e.backgroundBlurriness>0||r.mapping===Ae)return Vf(r);{let e;return e=!0===r.isCubeTexture?$c(r):Kl(r),Ig(e)}}if(!0===r.isTexture)return Kl(r,ud.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&o("WebGPUNodes: Unsupported background configuration.",r)},s);t.backgroundNode=i,t.background=r,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(e){const t=this.get(e),r=e.fog;if(r){if(t.fog!==r){const e=this.getCacheNode("fog",r,()=>{if(r.isFogExp2){const e=qc("color","color",r).setGroup(_a),t=qc("density","float",r).setGroup(_a);return ST(e,vT(t))}if(r.isFog){const e=qc("color","color",r).setGroup(_a),t=qc("near","float",r).setGroup(_a),s=qc("far","float",r).setGroup(_a);return ST(e,_T(t,s))}o("Renderer: Unsupported fog configuration.",r)});t.fogNode=e,t.fog=r}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),r=e.environment;if(r){if(t.environment!==r){const e=this.getCacheNode("environment",r,()=>!0===r.isCubeTexture?$c(r):!0===r.isTexture?Kl(r):void o("Nodes: Unsupported environment configuration.",r));t.environmentNode=e,t.environment=r}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Kl(e,ud).depth(sd("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Kl(e,ud).renderOutput(t.toneMapping,t.currentColorSpace)}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new YN,this.nodeBuilderCache=new Map,this.cacheLib={}}}const _S=new ut;class vS{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,r){const s=e.length;for(let i=0;iFl(e,i.toneMapping,i.outputColorSpace)}),LS.set(r,n))}else n=r;i.contextNode=n,i.setRenderTarget(t.renderTarget),t.rendercall(),i.contextNode=r}i.setRenderTarget(o),i._setXRLayerSize(a.x,a.y),this.isPresenting=n}getSession(){return this._session}async setSession(e){const t=this._renderer,r=t.backend;this._gl=t.getContext();const s=this._gl,i=s.getContextAttributes();if(this._session=e,null!==e){if(!0===r.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await r.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let r=null,n=null,a=null;t.depth&&(a=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,r=t.stencil?qe:He,n=t.stencil?Ze:S);const o={colorFormat:s.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(o),l=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,c=new Z(u.textureWidth,u.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,r,d);if(this._xrRenderTarget=new MS(u.textureWidth,u.textureHeight,{format:Ee,type:Ve,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.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 fe({color:16777215,side:"cylinder"===e.type?L:St}),e.plane.material.blending=Rt,e.plane.material.blendEquation=it,e.plane.material.blendSrc=Et,e.plane.material.blendDst=Et,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{const r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,s,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new MS(i.framebufferWidth,i.framebufferHeight,{format:Ee,type:Ve,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=-5&i.layers.mask,a.layers.mask=-3&i.layers.mask;const o=e.parent,u=i.cameras;DS(i,o);for(let e=0;e=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function VS(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 kS(e,t){if(void 0===t)return;const r=this._cameraXR,i=this._renderer,n=i.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views;null!==this._glBaseLayer&&n.setXRTarget(a.framebuffer);let t=!1;e.length!==r.cameras.length&&(r.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const s=this._renderLists.get(e,t),i=this._renderContexts.get(this._renderTarget,this._mrt),n=e.overrideMaterial||r.material,a=this._objects.get(r,n,e,t,s.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:u}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:u}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new TS(this,r),this._animation=new xy(this,this._nodes,this.info),this._attributes=new By(r,this.info),this._background=new fN(this,this._nodes),this._geometries=new Dy(this._attributes,this.info),this._textures=new tb(this,r,this.info),this._pipelines=new zy(r,this._nodes,this.info),this._bindings=new $y(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Sy(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Ky(this.lighting),this._bundles=new RS,this._renderContexts=new Jy(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,u=this._compilationPromises;null===r&&(r=e);const l=!0===e.isScene?e:!0===r.isScene?r:$S,d=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(d,this._mrt),h=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,s.renderId++,s.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new vS),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const g=this._renderLists.get(l,t);if(g.begin(),this._projectObject(e,t,0,g,c.clippingContext),r!==e&&r.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&g.pushLight(e)}),g.finish(),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;r!==e?this._background.update(r,g,c):this._background.update(l,g,c);const m=g.opaque,f=g.transparent,y=g.transparentDoublePass,b=g.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,l,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,l,b),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=u;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,this._geometries.updateForRender(t),await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const r=[];this._pipelines.getForRender(t,r),r.length>0&&await Promise.all(r),this._nodes.updateAfter(t),await Tt()}}async renderAsync(e,t){v('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){o("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=nc,t.modelNormalViewMatrix=ac):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===nc&&e.modelNormalViewMatrix===ac}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return v('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}`),o(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i,a),u=this.backend.get(o),l=s.version!==u.version;if(l||void 0===u.bundleGPU){this.backend.beginBundle(a),(void 0===u.renderObjects||l)&&(u.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:d,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,i,t,r),!0===this.transparent&&d.length>0&&this._renderTransparents(d,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t{u.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(u)};u.addEventListener("dispose",e),this._frameBufferTargets.set(u,l)}const d=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==d?l.setSize(d.width,d.height,d.depth):l.setSize(i,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:u._viewport,h=this._outputRenderTarget?this._outputRenderTarget.scissor:u._scissor,g=this._outputRenderTarget?1:u._pixelRatio,f=this._outputRenderTarget?this._outputRenderTarget.scissorTest:u._scissorTest;return l.viewport.copy(c),l.scissor.copy(h),l.viewport.multiplyScalar(g),l.scissor.multiplyScalar(g),l.scissorTest=f,l.multiview=null!==d&&d.multiview,l.resolveDepthBuffer=null===d||d.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==d&&d._autoAllocateDepthBuffer,l}_renderScene(e,t,r=!0){if(!0===this._isDeviceLost)return;const s=r?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,u=this._handleObjectFunction;this._callDepth++;const l=!0===e.isScene?e:$S,d=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let p;if(null!==s?(p=s,this.setRenderTarget(p)):p=d,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p);const m=this.xr;if(!1===m.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const r=this.coordinateSystem;if(t.coordinateSystem!==r){if(t.coordinateSystem=r,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=r;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,x=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,x=1),this.getDrawingBufferSize(WS),HS.set(0,0,WS.width,WS.height);const T=void 0===y.minDepth?0:y.minDepth,_=void 0===y.maxDepth?1:y.maxDepth;g.viewportValue.copy(y).multiplyScalar(x).floor(),g.viewportValue.width>>=h,g.viewportValue.height>>=h,g.viewportValue.minDepth=T,g.viewportValue.maxDepth=_,g.viewport=!1===g.viewportValue.equals(HS),g.scissorValue.copy(b).multiplyScalar(x).floor(),g.scissor=f._scissorTest&&!1===g.scissorValue.equals(HS),g.scissorValue.width>>=h,g.scissorValue.height>>=h,g.clippingContext||(g.clippingContext=new vS),g.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const v=t.isArrayCamera?jS:qS;t.isArrayCamera||(XS.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(XS,t.coordinateSystem,t.reversedDepth));const N=this._renderLists.get(e,t);if(N.begin(),this._projectObject(e,t,0,N,g.clippingContext),N.finish(),!0===this.sortObjects&&N.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,h);const e=this._textures.get(p);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=WS.width,g.height=WS.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=h,g.height>>=h,g.activeCubeFace=c,g.activeMipmapLevel=h,g.occlusionQueryCount=N.occlusionQueryCount,g.scissorValue.max(KS.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(l,N,g),g.camera=t,this.backend.beginRender(g);const{bundles:S,lightsNode:R,transparentDoublePass:E,transparent:A,opaque:w}=N;return S.length>0&&this._renderBundles(S,l,R),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,R),!0===this.transparent&&A.length>0&&this._renderTransparents(A,E,t,l,R),this.backend.finishRender(g),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=u,this._callDepth--,null!==s&&(this.setRenderTarget(d,c,h),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_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 r,s=this._quadCache.get(e.texture);if(void 0===s){r=new gx(new vg),r.name="Output Color Transform",r.material.name="outputColorTransform",r.material.fragmentNode=this._nodes.getOutputNode(e.texture),s={quad:r,cacheKey:t},this._quadCache.set(e.texture,s);const i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",i)};e.texture.addEventListener("dispose",i)}else r=s.quad,s.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,s.cacheKey=t);const i=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(r,r.camera,!1),this.autoClear=i,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){let t=e;if(!0!==t.isReadbackBuffer){const r=e,s=this.backend.get(r);if(t=s.readbackBuffer,void 0===t){t=new zS(r);const e=()=>{r.removeEventListener("dispose",e),t.dispose(),delete s.readbackBuffer};r.addEventListener("dispose",e),s.readbackBuffer=t}}if(!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}return t.release(),await this.backend.getArrayBufferAsync(t)}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,r){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,r)}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,r)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,r,s){this._canvasTarget.setScissor(e,t,r,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,r,s,i=0,n=1){this._canvasTarget.setViewport(e,t,r,s,i,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.get(s,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer;const t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),!0===s.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){v('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,r)}async clearColorAsync(){v('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){v('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){v('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==m,t=this.currentColorSpace!==p.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:m}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:p.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!0===this._initialized){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}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 d("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.deleteForCompute(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s,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 v('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){v('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),r=this._renderContexts.get(e);r.textures=t.textures,r.depthTexture=t.depthTexture,r.width=t.width,r.height=t.height,r.renderTarget=e,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,this.backend.initRenderTarget(r)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=KS.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void o("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=KS.copy(t).floor()}else t=KS.set(0,0,e.image.width,e.image.height);let r,s=this._currentRenderContext;null!==s?r=s.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),null!==r&&(this._textures.updateRenderTarget(r),s=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,s,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(e,t,r,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)r=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?jS:qS;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&KS.setFromMatrixPosition(e.matrixWorld).applyMatrix4(XS);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,KS.z,null,i)}}else if(e.isLineLoop)o("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?jS:qS;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),KS.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(XS)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=L;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=St;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=P}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n(t.not().discard(),e))(u)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),r={version:t,colorNode:u,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,r)}return r}renderObject(e,t,r,s,i,n,a,o=null,u=null){let l,d,c,h,p=!1;if(e.onBeforeRender(this,t,r,s,i,n),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,l=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,h=t.overrideMaterial.side,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:r,positionNode:s}=this._getShadowNodes(i);this.shadowMap.type===pt?e.side=null!==i.shadowSide?i.shadowSide:i.side:e.side=null!==i.shadowSide?i.shadowSide:QS[i.side],null!==t&&(e.colorNode=t),null!==r&&(e.depthNode=r),null!==s&&(e.positionNode=s)}i=e}!0===i.transparent&&i.side===P&&!1===i.forceSinglePass?(i.side=L,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=St,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=P):this._handleObjectFunction(e,i,t,r,a,n,o,u),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=h),e.onAfterRender(this,t,r,s,i,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);if(u.drawRange=e.geometry.drawRange,u.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(u);l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),this._pipelines.isReady(u)&&(this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u))}_createObjectPipeline(e,t,r,s,i,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:r,camera:s,lightsNode:i,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class ZS{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class JS extends ZS{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(My-e%My)%My;var e}get buffer(){return this._buffer}update(){return!0}}class eR extends JS{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let tR=0;class rR extends eR{constructor(e,t){super("UniformBuffer_"+tR++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class sR extends eR{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const r=this.updateRanges,s={start:e.offset,count:e.itemSize};r.push(s),this._updateRangeCache.set(t,s)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let oR=0;class uR extends aR{constructor(e,t){super(e,t),this.id=oR++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class lR extends uR{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class dR extends lR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class cR extends lR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const hR={bitcast_int_uint:new fT("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new fT("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},pR={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},gR={low:"lowp",medium:"mediump",high:"highp"},mR={swizzleAssign:!0,storageBuffer:!1},fR={perspective:"smooth",linear:"noperspective"},yR={centroid:"centroid"},bR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class xR extends QN{constructor(e,t){super(e,t,new yS),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==T}_include(e){const t=hR[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==hR[e]&&this._include(e),pR[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?We:$e;2===s?n=i?je:$:3===s?n=i?Ke:Xe:4===s&&(n=i?Lt:Ee);const a={Float32Array:K,Uint8Array:Ve,Uint16Array:Ge,Uint32Array:S,Int8Array:Oe,Int16Array:ke,Int32Array:R,Uint8ClampedArray:Ve},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s0?i:"";t=`${r.name} {\n\t${s} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===s[t]){const e=this.uniformGroups[t];if(void 0!==e){const r=[];for(const t of e.uniforms){const e=t.getType(),s=this.getVectorType(e),i=t.nodeUniform.node.precision;let n=`${s} ${t.name};`;null!==i&&(n=gR[i]+" "+n),r.push("\t"+n)}s[t]=r}}i=!0}if(!i){const s=e.node.precision;null!==s&&(t=gR[s]+" "+t),t="uniform "+t,r.push(t)}}let i="";for(const e in s){const t=s[e];i+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==R){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return 0===s.length&&s.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${fR[s.interpolationType]||s.interpolationType} ${yR[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${fR[e.interpolationType]||e.interpolationType} ${yR[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){o("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){o("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){o("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,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.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 r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=mR[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}mR[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 r=0;r0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${s.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${s.result};`)))}const n=e[t];if(n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new lR(i.name,i.node,s),u.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new dR(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new cR(i.name,i.node,s),u.push(a);else if("buffer"===t){i.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let r=t.buffer;void 0===r&&(e.name=`NodeBuffer_${e.id}`,r=new rR(e,s),r.name=e.name,t.buffer=r),u.push(r),a=r}else{let e=this.uniformGroups[o];void 0===e?(e=new nR(o,s),this.uniformGroups[o]=e,u.push(e)):-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}}let TR=null,_R=null;class vR{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Pt.RENDER]:null,[Pt.COMPUTE]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),r=this.renderer.info.frame;let s;s=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+r}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:")?Pt.COMPUTE:Pt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void v("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return TR=TR||new t,this.renderer.getDrawingBufferSize(TR)}setScissorTest(){}getClearColor(){const e=this.renderer;return _R=_R||new rb,e.getClearColor(_R),_R.getRGB(_R),_R}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Dt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${_t} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let NR,SR,RR=0;class ER{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 AR{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===R,id:RR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new ER(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e{r.deleteBuffer(l),t.delete(e),e.removeEventListener("dispose",s)};e.addEventListener("dispose",s),u.writeBuffer=l}else r.bindBuffer(r.COPY_WRITE_BUFFER,l);r.copyBufferSubData(r.COPY_READ_BUFFER,r.COPY_WRITE_BUFFER,0,0,o),await t.utils._clientWaitAsync();const d=new s.array.constructor(a.length);return r.bindBuffer(r.COPY_WRITE_BUFFER,l),r.getBufferSubData(r.COPY_WRITE_BUFFER,0,d),r.bindBuffer(r.COPY_READ_BUFFER,null),r.bindBuffer(r.COPY_WRITE_BUFFER,null),d}_createBuffer(e,t,r,s){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,r,s),e.bindBuffer(t,null),i}}class wR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;NR={[it]:e.FUNC_ADD,[It]:e.FUNC_SUBTRACT,[Ut]:e.FUNC_REVERSE_SUBTRACT},SR={[Et]:e.ZERO,[Ht]:e.ONE,[Wt]:e.SRC_COLOR,[rt]:e.SRC_ALPHA,[$t]:e.SRC_ALPHA_SATURATE,[zt]:e.DST_COLOR,[Gt]:e.DST_ALPHA,[kt]:e.ONE_MINUS_SRC_COLOR,[st]:e.ONE_MINUS_SRC_ALPHA,[Vt]:e.ONE_MINUS_DST_COLOR,[Ot]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),r=e.getParameter(e.VIEWPORT);this.currentScissor=(new s).fromArray(t),this.currentViewport=(new s).fromArray(r),this._tempVec4=new s}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;e!==qt?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===jt?t.cullFace(t.BACK):e===Xt?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:r}=this;e!==t&&(r.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,r){const s=this.gl,i=this.backend.drawBuffersIndexedExt;if(i)for(let n=0;n0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()})}}let MR,BR,FR,LR=!1;class PR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===LR&&(this._init(),LR=!0)}_init(){const e=this.gl;MR={[kr]:e.REPEAT,[_e]:e.CLAMP_TO_EDGE,[Vr]:e.MIRRORED_REPEAT},BR={[B]:e.NEAREST,[Gr]:e.NEAREST_MIPMAP_NEAREST,[bt]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[yt]:e.LINEAR_MIPMAP_NEAREST,[Y]:e.LINEAR_MIPMAP_LINEAR},FR={[Hr]:e.NEVER,[Wr]:e.ALWAYS,[A]:e.LESS,[w]:e.LEQUAL,[$r]:e.EQUAL,[M]:e.GEQUAL,[C]:e.GREATER,[zr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!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,r}getInternalFormat(e,t,r,s,i,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];d("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let u=null;s&&(u=o.get("EXT_texture_norm16"),u||d("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(r===a.FLOAT&&(l=a.R32F),r===a.HALF_FLOAT&&(l=a.R16F),r===a.UNSIGNED_BYTE&&(l=a.R8),r===a.BYTE&&(l=a.R8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.R16_EXT),r===a.SHORT&&u&&(l=u.R16_SNORM_EXT)),t===a.RED_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.R8UI),r===a.UNSIGNED_SHORT&&(l=a.R16UI),r===a.UNSIGNED_INT&&(l=a.R32UI),r===a.BYTE&&(l=a.R8I),r===a.SHORT&&(l=a.R16I),r===a.INT&&(l=a.R32I)),t===a.RG&&(r===a.FLOAT&&(l=a.RG32F),r===a.HALF_FLOAT&&(l=a.RG16F),r===a.UNSIGNED_BYTE&&(l=a.RG8),r===a.BYTE&&(l=a.RG8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RG16_EXT),r===a.SHORT&&u&&(l=u.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RG8UI),r===a.UNSIGNED_SHORT&&(l=a.RG16UI),r===a.UNSIGNED_INT&&(l=a.RG32UI),r===a.BYTE&&(l=a.RG8I),r===a.SHORT&&(l=a.RG16I),r===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGB32F),r===a.HALF_FLOAT&&(l=a.RGB16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8:a.RGB8),r===a.BYTE&&(l=a.RGB8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGB16_EXT),r===a.SHORT&&u&&(l=u.RGB16_SNORM_EXT),r===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),r===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),r===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGB8UI),r===a.UNSIGNED_SHORT&&(l=a.RGB16UI),r===a.UNSIGNED_INT&&(l=a.RGB32UI),r===a.BYTE&&(l=a.RGB8I),r===a.SHORT&&(l=a.RGB16I),r===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGBA32F),r===a.HALF_FLOAT&&(l=a.RGBA16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8_ALPHA8:a.RGBA8),r===a.BYTE&&(l=a.RGBA8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGBA16_EXT),r===a.SHORT&&u&&(l=u.RGBA16_SNORM_EXT),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),r===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),r===a.UNSIGNED_INT&&(l=a.RGBA32UI),r===a.BYTE&&(l=a.RGBA8I),r===a.SHORT&&(l=a.RGBA16I),r===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(r===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),r===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),r===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&r===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,{state:n}=this.backend,a=p.getPrimaries(p.workingColorSpace),o=t.colorSpace===T?null:p.getPrimaries(t.colorSpace),u=t.colorSpace===T||a===o?r.NONE:r.BROWSER_DEFAULT_WEBGL;n.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,u),r.texParameteri(e,r.TEXTURE_WRAP_S,MR[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,MR[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,MR[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,BR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,d=t.minFilter===le&&l?Y:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,BR[d]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,FR[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===B)return;if(t.minFilter!==bt&&t.minFilter!==Y)return;if(t.type===K&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i})}createTexture(e,t){const{gl:r,backend:s}=this,{levels:i,width:n,height:a,depth:o}=t,u=s.utils.convert(e.format,e.colorSpace),l=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.normalized,e.colorSpace,e.isVideoTexture),c=r.createTexture(),h=this.getGLTextureType(e);s.state.bindTexture(h,c),this.setTextureParameters(h,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,i,d,n,a,o):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,i,d,n,a,o):e.isVideoTexture||r.texStorage2D(h,i,d,n,a),s.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{state:i}=s,{textureGPU:n,glTextureType:a,glFormat:o,glType:u}=s.get(t),{width:l,height:d}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(a,n),i.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(a,0,0,0,l,d,o,u,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t0){const t=jr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function DR(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 UR{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 IR{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 r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.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 OR={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 VR{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:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;sthis.maxQueries)return v(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){o("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){o("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,r]of this.queryOffsets){if("ended"===this.queryStates.get(r)){const s=this.queries[r];e.set(t,this.resolveQuery(s))}}if(0===e.size)return this.lastValue;const t={},r=[];for(const[s,i]of e){const e=s.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===r.includes(n)&&r.push(n),void 0===t[n]&&(t[n]=0);const a=await i;this.timestamps.set(s,a),t[n]+=a}const s=t[r[r.length-1]];return this.lastValue=s,this.frames=r,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return o("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 r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){o("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class zR extends vR{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,r={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new UR(this),this.capabilities=new IR(this),this.attributeUtils=new AR(this),this.textureUtils=new PR(this),this.bufferRenderer=new VR(this),this.state=new wR(this),this.utils=new CR(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:(d("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 c}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&d("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 GR(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.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,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.scissor(0,0,e,r)}this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e{let a=0;for(let t=0;t1?t.renderInstances(r,s,i):t.render(r,s)}draw(e){const{object:t,pipeline:r,material:s,context:i,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(r),{gl:o,state:u}=this,l=this.get(i),d=e.getDrawParameters();if(null===d)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;u.setMaterial(s,c,n),null!==i.mrt&&null!==i.textures&&u.setMRTBlending(i.textures,i.mrt,s),u.useProgram(a);const h=e.getAttributes(),p=this.get(h);let g=p.vaoGPU;if(void 0===g){const e=this._getVaoKey(h);g=this.vaoCache[e],void 0===g&&(g=this._createVao(h),this.vaoCache[e]=g,p.vaoGPU=g)}const m=e.getIndex(),f=null!==m?this.get(m).bufferGPU:null;u.setVertexState(g,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===s.wireframe?(u.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:x,instanceCount:T}=d;let{firstVertex:_}=d;if(b.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);b.index=m.count,b.type=e.type}else b.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()});return void t.push(i)}this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(e,t,r){if(this.renderer.debug.checkShaderErrors){const s=this.gl,i=(s.getProgramInfoLog(e)||"").trim();if(!1===s.getProgramParameter(e,s.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(s,e,r,t);else{const n=this._getShaderErrors(s,r,"vertex"),a=this._getShaderErrors(s,t,"fragment");o("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+n+"\n"+a)}else""!==i&&d("WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;eOR[t]===e),r=this.extensions;for(let e=0;e1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=Zy(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const $R="point-list",WR="line-list",HR="line-strip",qR="triangle-list",jR="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},XR="never",KR="less",QR="equal",YR="less-equal",ZR="greater",JR="not-equal",eE="greater-equal",tE="always",rE="store",sE="load",iE="clear",nE="ccw",aE="cw",oE="none",uE="back",lE="uint16",dE="uint32",cE="r8unorm",hE="r8snorm",pE="r8uint",gE="r8sint",mE="r16uint",fE="r16sint",yE="r16float",bE="rg8unorm",xE="rg8snorm",TE="rg8uint",_E="rg8sint",vE="r16unorm",NE="r16snorm",SE="r32uint",RE="r32sint",EE="r32float",AE="rg16uint",wE="rg16sint",CE="rg16float",ME="rgba8unorm",BE="rgba8unorm-srgb",FE="rgba8snorm",LE="rgba8uint",PE="rgba8sint",DE="bgra8unorm",UE="bgra8unorm-srgb",IE="rg16unorm",OE="rg16snorm",VE="rgb9e5ufloat",kE="rgb10a2unorm",GE="rg11b10ufloat",zE="rg32uint",$E="rg32sint",WE="rg32float",HE="rgba16uint",qE="rgba16sint",jE="rgba16float",XE="rgba16unorm",KE="rgba16snorm",QE="rgba32uint",YE="rgba32sint",ZE="rgba32float",JE="depth16unorm",eA="depth24plus",tA="depth24plus-stencil8",rA="depth32float",sA="depth32float-stencil8",iA="bc1-rgba-unorm",nA="bc1-rgba-unorm-srgb",aA="bc2-rgba-unorm",oA="bc2-rgba-unorm-srgb",uA="bc3-rgba-unorm",lA="bc3-rgba-unorm-srgb",dA="bc4-r-unorm",cA="bc4-r-snorm",hA="bc5-rg-unorm",pA="bc5-rg-snorm",gA="bc6h-rgb-ufloat",mA="bc6h-rgb-float",fA="bc7-rgba-unorm",yA="bc7-rgba-unorm-srgb",bA="etc2-rgb8unorm",xA="etc2-rgb8unorm-srgb",TA="etc2-rgb8a1unorm",_A="etc2-rgb8a1unorm-srgb",vA="etc2-rgba8unorm",NA="etc2-rgba8unorm-srgb",SA="eac-r11unorm",RA="eac-r11snorm",EA="eac-rg11unorm",AA="eac-rg11snorm",wA="astc-4x4-unorm",CA="astc-4x4-unorm-srgb",MA="astc-5x4-unorm",BA="astc-5x4-unorm-srgb",FA="astc-5x5-unorm",LA="astc-5x5-unorm-srgb",PA="astc-6x5-unorm",DA="astc-6x5-unorm-srgb",UA="astc-6x6-unorm",IA="astc-6x6-unorm-srgb",OA="astc-8x5-unorm",VA="astc-8x5-unorm-srgb",kA="astc-8x6-unorm",GA="astc-8x6-unorm-srgb",zA="astc-8x8-unorm",$A="astc-8x8-unorm-srgb",WA="astc-10x5-unorm",HA="astc-10x5-unorm-srgb",qA="astc-10x6-unorm",jA="astc-10x6-unorm-srgb",XA="astc-10x8-unorm",KA="astc-10x8-unorm-srgb",QA="astc-10x10-unorm",YA="astc-10x10-unorm-srgb",ZA="astc-12x10-unorm",JA="astc-12x10-unorm-srgb",ew="astc-12x12-unorm",tw="astc-12x12-unorm-srgb",rw="clamp-to-edge",sw="repeat",iw="mirror-repeat",nw="linear",aw="nearest",ow="zero",uw="one",lw="src",dw="one-minus-src",cw="src-alpha",hw="one-minus-src-alpha",pw="dst",gw="one-minus-dst",mw="dst-alpha",fw="one-minus-dst-alpha",yw="src-alpha-saturated",bw="constant",xw="one-minus-constant",Tw="add",_w="subtract",vw="reverse-subtract",Nw="min",Sw="max",Rw=0,Ew=15,Aw="keep",ww="zero",Cw="replace",Mw="invert",Bw="increment-clamp",Fw="decrement-clamp",Lw="increment-wrap",Pw="decrement-wrap",Dw="storage",Uw="read-only-storage",Iw="write-only",Ow="read-only",Vw="read-write",kw="non-filtering",Gw="comparison",zw="float",$w="unfilterable-float",Ww="depth",Hw="sint",qw="uint",jw="2d",Xw="3d",Kw="2d",Qw="2d-array",Yw="cube",Zw="3d",Jw="all",eC="vertex",tC="instance",rC={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"},sC={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class iC extends aR{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class nC extends JS{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let aC=0;class oC extends nC{constructor(e,t){super("StorageBuffer_"+aC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ii.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class uC extends Ry{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:nw}),this.flipYSampler=e.createSampler({minFilter:aw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const r=`${e}-${t=t||"2d-array"}`;let s=this.transferPipelines[r];return void 0===s&&(s=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[r]=s),s}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.device.createTexture({size:{width:i,height:n},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(s,e.textureBindingViewDimension),u=this.getTransferPipeline(s,a.textureBindingViewDimension),l=this.device.createCommandEncoder({}),d=(e,t,r,s,i,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),u=l.beginRenderPass({colorAttachments:[{view:s.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:i,arrayLayerCount:1}),loadOp:iE,storeOp:rE}]});u.setPipeline(e),u.setBindGroup(0,o),u.draw(3,1,0,r),u.end()};d(o,e,r,a,0,!1),d(u,a,0,e,r,!0),this.device.queue.submit([l.finish()]),a.destroy()}generateMipmaps(e,t=null){const r=this.get(e),s=r.layers||this._mipmapCreateBundles(e),i=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(i,s),null===t&&this.device.queue.submit([i.finish()]),r.layers=s}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",r=this.getTransferPipeline(e.format,t),s=r.getBindGroupLayout(0),i=[];for(let n=1;n0)for(let t=0,n=s.length;t0){for(const s of e.layerUpdates)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);e.clearLayerUpdates()}else for(let s=0;s0)for(let t=0,n=s.length;t{const t=e.changedElements;for(const e of r)t.includes(e.image)&&(e.needsUpdate=!0)}}dispose(){this._samplerCache.clear(),this._htmlTextures.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new N;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,format:e}),this.defaultTexture[e]=t=r}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const r=new D;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=r}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,r){const s=e.images,i=e.mipmaps;for(let n=0;n<6;n++){const a=s[n],o=!0===e.flipY?dC[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha);for(let s=0;s0?e.width:r.size.width,l=a>0?e.height:r.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:n},{width:u,height:l,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new uC(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},u,{offset:e.width*e.height*l*n,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r){const s=this.backend.device,i=this._getBlockData(r.format),n=r.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,gC=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,mC={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",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 fC extends hS{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(pC);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=gC.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class yC extends cS{parseFunction(e){return new fC(e)}}const bC={[ii.READ_ONLY]:"read",[ii.WRITE_ONLY]:"write",[ii.READ_WRITE]:"read_write"},xC={[kr]:"repeat",[_e]:"clamp",[Vr]:"mirror"},TC={vertex:jR.VERTEX,fragment:jR.FRAGMENT,compute:jR.COMPUTE},_C={instance:!0,swizzleAssign:!1,storageBuffer:!0},vC={"^^":"tsl_xor"},NC={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},SC={},RC={tsl_xor:new fT("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new fT("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new fT("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new fT("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new fT("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new fT("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new fT("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new fT("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new fT("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new fT("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new fT("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 fT("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new fT("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new fT("\nfn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},EC={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let AC="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(AC+="diagnostic( off, derivative_uniformity );\n");class wC extends QN{constructor(e,t){super(e,t,new yC),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${xC[e.wrapS]}S_${xC[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let r=SC[t];if(void 0===r){const s=[],i=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===kr?(s.push(RC.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===_e?(s.push(RC.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Vr?(s.push(RC.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,d(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",SC[t]=r=new fT(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Du(new wl(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Du(new wl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Du(new wl("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2(${s}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${r} ), ${o}, u32( ${n} ), u32( ${i} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${r} ), ${o}, u32( ${i} ) )`)}generateTextureLod(e,t,r,s,i,n="0u"){if(!0===e.isCubeTexture){i&&(r=`${r} + vec3(${i})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}(${i}) / ${u}( ${o} )`);return r=`${u}( clamp( floor( ${a}( ${r} ) * ${u}( ${o} ) ), ${`${u}( 0 )`}, ${`${u}( ${o} - ${"vec3"===u?"vec3( 1, 1, 1 )":"vec2( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,r,n,s,null)}generateStorageTextureLoad(e,t,r,s,i,n){let a;return n&&(r=`${r} + ${n}`),a=i?`textureLoad( ${t}, ${r}, ${i} )`:`textureLoad( ${t}, ${r} )`,a}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0u"),n&&(r=`${r} + ${n}`),i?a=`textureLoad( ${t}, ${r}, ${i}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(E.TEXTURE_COMPARE)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===K||!1===this.isSampleCompare(e)&&e.minFilter===B&&e.magFilter===B||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;o(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`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,r=e.type;return"texture"===r||"cubeTexture"===r||"cubeDepthTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=vC[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(d("WebGPURenderer: Atomic operations are only supported in compute shaders."),ii.READ_WRITE):ii.READ_ONLY:e.access}getStorageAccess(e,t){return bC[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);"texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new cR(i.name,i.node,o,n):new lR(i.name,i.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?s=new dR(i.name,i.node,o,n):"texture3D"===t&&(s=new cR(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(TC[r]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new iC(`${i.name}_sampler`,i.node,o);e.setVisibility(TC[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let u=n.buffer;if(void 0===u){u=new("buffer"===t?rR:oC)(e,o),n.buffer=u}u.setVisibility(u.getVisibility()|TC[r]),l.push(u),a=u,i.name=s||"NodeBuffer_"+i.id}else{let e=this.uniformGroups[u];void 0===e&&(e=new nR(u,o),e.setVisibility(jR.VERTEX|jR.FRAGMENT|jR.COMPUTE),this.uniformGroups[u]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),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,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null,s=""){let i=`var${s} ${t} : `;return i+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),i}getVars(e,t=!1){let r="";t&&(r="");const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count,r)};`);return t?s.join("\n"):`\n\t${s.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];let i=0;for(let n=0;nr.value.itemSize;return s&&!i}getUniforms(e){const t=this.renderer.backend,r=this.uniforms[e],s=[],i=[],n=[],a={};for(const n of r){const r=n.groupNode.name,o=this.bindingsIndexes[r];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const r=n.node.value;let i;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==n.node.isStorageTextureNode)&&(this.isSampleCompare(r)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let a="";const{primarySamples:u}=t.utils.getTextureSampleData(r);if(u>1&&(a="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)i="texture_depth_cube";else if(!0===r.isCubeTexture)i="texture_cube";else if(!0===r.isDepthTexture)i=t.compatibilityMode&&null===r.compareFunction?`texture${a}_2d`:`texture_depth${a}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const s=hC(r,t.device),a=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,u=n.node.value.isArrayTexture;i=`texture_storage_${o?"3d":"2d"+(u?"_array":"")}<${s}, ${a}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture)i="texture_2d_array";else if(!0===r.is3DTexture||!0===r.isData3DTexture)i="texture_3d";else{i=`texture${a}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${i};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,r=this.getType(t.getNodeType(this)),s=t.bufferCount,a=s>0&&"buffer"===n.type?", "+s:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${u}> ${n.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${a} >`;i.push(this._getWGSLStructBinding(n.name,e,u,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const r=[];for(const e of t.uniforms){const t=e.getType(),s=this.getType(this.getVectorType(t));r.push(`\t${e.name} : ${s}`)}let s=this.uniformGroupsBindings[e];void 0===s&&(s={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=s),a[e]={index:s.index,id:s.id,snippets:r}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=this.allowGlobalVariables,s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t,r),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,u=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const r=this.getFlowData(e),n=e.name;if(n&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${n}\n`),i+=`${r.code}\n\t`,e===a&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(u)s.returnType=o.getNodeType(this),s.structs+="var output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location( 0 ) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return NC[e]||e}isAvailable(e){let t=_C[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),_C[e]=t),t}_getWGSLMethod(e){return void 0!==RC[e]&&this._include(e),EC[e]}_include(e){const t=RC[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${AC}\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[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\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 * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * 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,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class CC{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?sA:tA:!0===this.backend.renderer.reversedDepthBuffer?rA:eA),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}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?$R:e.isLineSegments||e.isMesh&&!0===t.wireframe?WR:e.isLine?HR:e.isMesh?qR:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ve)return DE;if(e===Te)return jE;throw new Error("Unsupported output buffer type.")}}const MC=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&MC.set(Float16Array,["float16"]);const BC=new Map([[xt,["float16"]]]),FC=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class LC{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o=r.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e{o.unmap()},u=()=>{o.destroy(),t.delete(e),e.removeEventListener("release",i),e.removeEventListener("dispose",u)};e.addEventListener("release",i),e.addEventListener("dispose",u),a.readBufferGPU=o}const u=r.createCommandEncoder({label:`readback_encoder_${s.name}`});u.copyBufferToBuffer(i,0,o,0,n);const l=u.finish();r.queue.submit([l]),await o.mapAsync(GPUMapMode.READ);return o.getMappedRange()}_getVertexFormat(e){const{itemSize:t,normalized:r}=e,s=e.array.constructor,i=e.constructor;let n;if(1===t)n=FC.get(s);else{const e=(BC.get(i)||MC.get(s))[r?1:0];if(e){const r=s.BYTES_PER_ELEMENT*t,i=4*Math.floor((r+3)/4)/s.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${i}`}}return n||o("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class PC{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class DC{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,r=t.device,s=t.get(e);if(s.layout)return s.layout.layoutGPU;const i=this._createLayoutEntries(e),n=Vs(JSON.stringify(i));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new PC(r.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,s.layout=a,s.layoutKey=n,a.layoutGPU}createBindings(e,t,r,s=0){const{backend:i}=this,n=i.get(e),a=this.createBindingsLayout(e);let o;r>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[r]===s&&(o=n.groups[r])),void 0===o&&(o=this.createBindGroup(e,a),r>0&&(n.groups[r]=o,n.versions[r]=s)),n.group=o}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer,n=e.updateRanges;if(0===n.length)r.queue.writeBuffer(i,0,s,0);else{const e=Xr(s),t=e?1:s.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${r}-${s}`,a=e[i],void 0===a){const n=Jw;let o;o=t.isSampledCubeTexture?Yw:t.isSampledTexture3D?Zw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Qw:Kw,a=e[i]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:r,baseMipLevel:s})}}n.push({binding:i,resource:a})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let r=0;for(const s of e.bindings){const e=this.backend,i={binding:r,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const e={};s.isStorageBuffer&&(s.visibility&jR.COMPUTE&&(s.access===ii.READ_WRITE||s.access===ii.WRITE_ONLY)?e.type=Dw:e.type=Uw),i.buffer=e}else if(s.isSampledTexture&&s.store){const e={};e.format=this.backend.get(s.texture).texture.format;const t=s.access;e.access=t===ii.READ_WRITE?Vw:t===ii.WRITE_ONLY?Iw:Ow,s.texture.isArrayTexture?e.viewDimension=Qw:s.texture.is3DTexture&&(e.viewDimension=Zw),i.storageTexture=e}else if(s.isSampledTexture){const t={},{primarySamples:r}=e.utils.getTextureSampleData(s.texture);if(r>1&&(t.multisampled=!0,s.texture.isDepthTexture||(t.sampleType=$w)),s.texture.isDepthTexture)e.compatibilityMode&&null===s.texture.compareFunction?t.sampleType=$w:t.sampleType=Ww;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture||s.texture.isStorageTexture){const e=s.texture.type;e===R?t.sampleType=Hw:e===S?t.sampleType=qw:e===K&&(this.backend.hasFeature("float32-filterable")?t.sampleType=zw:t.sampleType=$w)}s.isSampledCubeTexture?t.viewDimension=Yw:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?t.viewDimension=Qw:s.isSampledTexture3D&&(t.viewDimension=Zw),i.texture=t}else if(s.isSampler){const t={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction&&e.hasCompatibility(E.TEXTURE_COMPARE)?t.type=Gw:t.type=kw),i.sampler=t}else o(`WebGPUBindingUtils: Unsupported binding "${s}".`);t.push(i),r++}return t}deleteBindGroupData(e){const{backend:t}=this,r=t.get(e);r.layout&&(r.layout.usedTimes--,0===r.layout.usedTimes&&this._bindGroupLayoutCache.delete(r.layoutKey),r.layout=void 0,r.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class UC{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class IC{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:r,material:s,geometry:i,pipeline:n}=e,{vertexProgram:a,fragmentProgram:u}=n,l=this.backend,d=l.device,c=l.utils,h=l.get(n),p=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:r}=e.layout;p.push(r)}const g=l.attributeUtils.createShaderVertexBuffers(e);let m;s.blending===re||s.blending===tt&&!1===s.transparent||(m=this._getBlending(s));let f={};!0===s.stencilWrite&&(f={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const y=this._getColorWriteMask(s),b=[];if(null!==e.context.textures){const t=e.context.textures,r=e.context.mrt;for(let e=0;e1},layout:d.createPipelineLayout({bindGroupLayouts:p})},A={},w=e.context.depth,C=e.context.stencil;if(!0!==w&&!0!==C||(!0===w&&(A.format=S,A.depthWriteEnabled=s.depthWrite,A.depthCompare=N),!0===C&&(A.stencilFront=f,A.stencilBack=f,A.stencilReadMask=s.stencilFuncMask,A.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(A.depthBias=s.polygonOffsetUnits,A.depthBiasSlopeScale=s.polygonOffsetFactor,A.depthBiasClamp=0),E.depthStencil=A),d.pushErrorScope("validation"),null===t)h.pipeline=d.createRenderPipeline(E),d.popErrorScope().then(e=>{null!==e&&(h.error=!0,o(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await d.createRenderPipelineAsync(E)}catch(e){}const t=await d.popErrorScope();null!==t&&(h.error=!0,o(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:s.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e),{layoutGPU:s}=t.layout;a.push(s)}n.pipeline=s.createComputePipeline({compute:i,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,r;const s=e.blending,i=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(s===Rt){const s=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,u=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},r={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(u)}}else{const i=(e,s,i,n)=>{t={srcFactor:e,dstFactor:s,operation:Tw},r={srcFactor:i,dstFactor:n,operation:Tw}};if(e.premultipliedAlpha)switch(s){case tt:i(uw,hw,uw,hw);break;case Yt:i(uw,uw,uw,uw);break;case Qt:i(ow,dw,ow,uw);break;case Kt:i(pw,hw,ow,uw)}else switch(s){case tt:i(cw,hw,uw,hw);break;case Yt:i(cw,uw,uw,uw);break;case Qt:o(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Kt:o(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};o("WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Et:t=ow;break;case Ht:t=uw;break;case Wt:t=lw;break;case kt:t=dw;break;case rt:t=cw;break;case st:t=hw;break;case zt:t=pw;break;case Vt:t=gw;break;case Gt:t=mw;break;case Ot:t=fw;break;case $t:t=yw;break;case 211:t=bw;break;case 212:t=xw;break;default:o("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case rs:t=XR;break;case ts:t=tE;break;case es:t=KR;break;case Jr:t=YR;break;case Zr:t=QR;break;case Yr:t=eE;break;case Qr:t=ZR;break;case Kr:t=JR;break;default:o("WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case ds:t=Aw;break;case ls:t=ww;break;case us:t=Cw;break;case os:t=Mw;break;case as:t=Bw;break;case ns:t=Fw;break;case is:t=Lw;break;case ss:t=Pw;break;default:o("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case it:t=Tw;break;case It:t=_w;break;case Ut:t=vw;break;case hs:t=Nw;break;case cs:t=Sw;break;default:o("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?lE:dE);let n=r.side===L;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),s.frontFace=!0===n?aE:nE,s.cullMode=r.side===P?oE:uE,s}_getColorWriteMask(e){return!0===e.colorWrite?Ew:Rw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=tE;else{const r=this.backend.parameters.reversedDepthBuffer?ar[e.depthFunc]:e.depthFunc;switch(r){case nr:t=XR;break;case ir:t=tE;break;case sr:t=KR;break;case rr:t=YR;break;case tr:t=QR;break;case er:t=eE;break;case Jt:t=ZR;break;case Zt:t=JR;break;default:o("WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class OC extends kR{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r)),a={},o=[];for(const[t,r]of e){const e=t.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===o.includes(s)&&o.push(s),void 0===a[s]&&(a[s]=0);const i=n[r],u=n[r+1],l=Number(u-i)/1e6;this.timestamps.set(t,l),a[s]+=l}const u=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=u,this.frames=o,u}catch(e){return o("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){o("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){o("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const VC={r:0,g:0,b:0,a:1};class kC extends vR{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 CC(this),this.attributeUtils=new LC(this),this.bindingUtils=new DC(this),this.capabilities=new UC(this),this.pipelineUtils=new IC(this),this.textureUtils=new cC(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[E.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},s="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===s)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(rC),n=[];for(const e of i)s.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};r=await s.requestDevice(a)}else r=t.device;this.compatibilityMode=!r.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),r.lost.then(t=>{if("destroyed"===t.reason)return;const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}),this.device=r,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(rC.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let r=t.context;if(void 0===r){const s=this.parameters;r=!0===e.isDefaultCanvasTarget&&void 0!==s.context?s.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${_t} webgpu`);const i=s.alpha?"premultiplied":"opaque",n=s.outputType===Te?"extended":"standard";r.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),t.context=r}return r}get coordinateSystem(){return h}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),r=this.get(t),s=e.currentSamples;let i=r.descriptor;if(void 0===i||r.samples!==s){i={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(i.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=i.colorAttachments[0];s>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,r.descriptor=i,r.samples=s}const n=i.colorAttachments[0];return s>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;void 0!==i&&s.width===r.width&&s.height===r.height&&s.samples===r.samples||(i={},s.descriptors=i);const n=e.getCacheKey();let a=i[n];if(void 0===a){const t=e.textures,o=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s1)if(!0===l){const t=e.camera.cameras;for(let e=0;e0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=r.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:sE}),this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(i=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,i));const n=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),n.dispatchSize=i}i=n.dispatchSize}a.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,r,s,i,n,a,o,u){const{object:l,material:d,context:c}=e,h=e.getIndex(),p=null!==h;this.pipelineUtils.setPipeline(o,s),u.pipeline=s;const g=u.bindingGroups;for(let e=0,t=i.length;e65535?4:2);for(let n=0;n0){const i=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===i.indexesGPU||i.indexesGPU.length!==a.length){const e=this.get(c),t=[],r=new Uint32Array([0,0,0,0]);for(let s=0,i=a.length;s(d("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new zR(e)));super(new t(e),e),this.library=new $C,this.isWebGPURenderer=!0}}class HC extends Es{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class qC{constructor(e,t=Cn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new vg;r.name="RenderPipeline",this._quadMesh=new gx(r),this._quadMesh.name="Render Pipeline",this._context=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){const e=this.renderer;this._update(),null!==this._context.onBeforeRenderPipeline&&this._context.onBeforeRenderPipeline();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=m,e.outputColorSpace=p.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterRenderPipeline&&this._context.onAfterRenderPipeline()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),!0===this.needsUpdate){const e=this._toneMapping,t=this._outputColorSpace,r={renderPipeline:this,onBeforeRenderPipeline:null,onAfterRenderPipeline:null};let s=this.outputNode;!0===this.outputColorTransform?(s=s.context(r),s=Fl(s,e,t)):(r.toneMapping=e,r.outputColorSpace=t,s=s.context(r)),this._context=r,this._quadMesh.material.fragmentNode=s,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){v('RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}}class jC extends qC{constructor(e,t){v('PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.'),super(e,t)}}class XC extends N{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class KC extends Ax{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class QC extends As{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new ws(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{try{t(this.parse(JSON.parse(r)))}catch(t){s?s(t):o(t),this.manager.itemError(e)}},r,s)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return void 0===this.nodes[e]?(o("NodeLoader: Node type not found:",e),yn()):new this.nodes[e]}}class YC extends Cs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class ZC extends Ms{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}parseNodes(e,t){if(void 0!==e){const r=new QC;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new YC;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={id:s.id,version:s.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=Ps.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Ps.set(e,t)),t}getMaterialData(e){let t=Ls.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:s.version}:t[r]=s.clone():t[r]=s)}Ls.set(e,t)}return t}equals(e,t,r){const{object:s,material:i,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(s.matrixWorld))return a.worldMatrix.copy(s.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==r){o._renderId=r;for(const e in o){const t=o[e],r=i[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),o._equal=!1,!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,o._equal=!1,!1}else if(t!==r)return o[e]=r,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:r}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==r)return a.bufferWidth=t,a.bufferHeight=r,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==r){u._renderId=r;const e=n.attributes,t=u.attributes;let s=0,i=0;for(const t in e)s++;for(const r in t){i++;const s=t[r],n=e[r];if(void 0===n)return delete t[r],u._equal=!1,!1;if(s.id!==n.id||s.version!==n.version)return s.id=n.id,s.version=n.version,u._equal=!1,!1}if(i!==s)return u.attributes=this.getAttributesData(e),u._equal=!1,!1;const a=n.index,o=u.indexId,l=u.indexVersion,d=a?a.id:null,c=a?a.version:null;if(o!==d||l!==c)return u.indexId=d,u.indexVersion=c,u._equal=!1,!1;if(u.drawRange.start!==n.drawRange.start||u.drawRange.count!==n.drawRange.count)return u.drawRange.start=n.drawRange.start,u.drawRange.count=n.drawRange.count,u._equal=!1,!1;u._equal=!0}else if(!1===u._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t{const r=e.match(t);if(!r)return null;const s=r[1]||r[2]||"",i=r[3].split("?")[0],n=parseInt(r[4],10),a=parseInt(r[5],10);return{fn:s,file:i.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Ds.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Os(e,t=0){let r=3735928559^t,s=1103547991^t;if(Array.isArray(e))for(let t,i=0;i>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const Vs=e=>Os(e),ks=e=>Os(e),Gs=(...e)=>Os(e),zs=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),$s=new WeakMap;function Ws(e){return zs.get(e)}function Hs(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function qs(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function js(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Xs(e){return/float|int|uint/.test(e)?4:/vec2/.test(e)?8:/vec3/.test(e)||/vec4/.test(e)?16:/mat2/.test(e)?8:/mat3/.test(e)||/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Is)}function Ks(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 Qs(o,...u){const l=o?o.slice(-4):void 0;return 1===u.length&&("vec2"===l?u=[u[0],u[0]]:"vec3"===l?u=[u[0],u[0],u[0]]:"vec4"===l&&(u=[u[0],u[0],u[0],u[0]])),"color"===o?new e(...u):"vec2"===l?new t(...u):"vec3"===l?new r(...u):"vec4"===l?new s(...u):"mat2"===l?new i(...u):"mat3"===l?new n(...u):"mat4"===l?new a(...u):"bool"===o?u[0]||!1:"float"===o||"int"===o||"uint"===o?u[0]||0:"string"===o?u[0]||"":"ArrayBuffer"===o?Js(u[0]):null}function Ys(e){let t=$s.get(e);return void 0===t&&(t={},$s.set(e,t)),t}function Zs(e){let t="";const r=new Uint8Array(e);for(let e=0;ee.charCodeAt(0)).buffer}var ei=Object.freeze({__proto__:null,arrayBufferToBase64:Zs,base64ToArrayBuffer:Js,getAlignmentFromType:Xs,getDataFromObject:Ys,getLengthFromType:qs,getMemoryLengthFromType:js,getTypeFromLength:Ws,getTypedArrayFromType:Hs,getValueFromType:Qs,getValueType:Ks,hash:Gs,hashArray:ks,hashString:Vs});const ti={VERTEX:"vertex",FRAGMENT:"fragment"},ri={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},si={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},ii={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ni=["fragment","vertex"],ai=["setup","analyze","generate"],oi=[...ni,"compute"],ui=["x","y","z","w"],li={analyze:"setup",generate:"analyze"};let di=0;class ci extends u{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ri.NONE,this.updateBeforeType=ri.NONE,this.updateAfterType=ri.NONE,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=di++,this.stackTrace=null,!0===ci.captureStackTrace&&(this.stackTrace=new Is)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=l.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,ri.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ri.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ri.OBJECT)}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 r of Object.getOwnPropertyNames(this)){const s=this[r];if(!0!==r.startsWith("_")&&!e.has(s))if(!0===Array.isArray(s))for(let e=0;e0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}ci.captureStackTrace=!1;class hi extends ci{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 pi extends ci{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class gi extends ci{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 r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class mi extends gi{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,r)=>t+e.getTypeLength(r.getNodeType(e)),0))}generate(e,t){const r=this.getNodeType(e),s=e.getTypeLength(r),i=this.nodes,n=e.getComponentType(r),a=[];let u=0;for(const t of i){if(u>=s){o(`TSL: Length of parameters exceeds maximum length of function '${r}()' type.`,this.stackTrace);break}let i,l=t.getNodeType(e),d=e.getTypeLength(l);u+d>s&&(o(`TSL: Length of '${r}()' data exceeds maximum length of output type.`,this.stackTrace),d=s-u,l=e.getTypeFromLength(d)),u+=d,i=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(d,n);i=e.format(i,l,t)}a.push(i)}const l=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(l,r,t)}}const fi=ui.join("");class yi extends ci{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(ui.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 r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===fi.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class bi extends gi{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");ci.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Si?Si.assign(this,...e):o("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Is),this;{const t=Ri.get("assign");return this.addToStack(t(...e))}},ci.prototype.toVarIntent=function(){return this},ci.prototype.get=function(e){return new Ni(this,e)};const wi={};function Ci(e,t,r){wi[e]=wi[t]=wi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new yi(this,e),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();ci.prototype["set"+s]=ci.prototype["set"+i]=ci.prototype["set"+n]=function(t){const r=Ei(e);return new bi(this,r,tn(t))},ci.prototype["flip"+s]=ci.prototype["flip"+i]=ci.prototype["flip"+n]=function(){const t=Ei(e);return new xi(this,t)}}const Mi=["x","y","z","w"],Bi=["r","g","b","a"],Fi=["s","t","p","q"];for(let e=0;e<4;e++){let t=Mi[e],r=Bi[e],s=Fi[e];Ci(t,r,s);for(let i=0;i<4;i++){t=Mi[e]+Mi[i],r=Bi[e]+Bi[i],s=Fi[e]+Fi[i],Ci(t,r,s);for(let n=0;n<4;n++){t=Mi[e]+Mi[i]+Mi[n],r=Bi[e]+Bi[i]+Bi[n],s=Fi[e]+Fi[i]+Fi[n],Ci(t,r,s);for(let a=0;a<4;a++)t=Mi[e]+Mi[i]+Mi[n]+Mi[a],r=Bi[e]+Bi[i]+Bi[n]+Bi[a],s=Fi[e]+Fi[i]+Fi[n]+Fi[a],Ci(t,r,s)}}}for(let e=0;e<32;e++)wi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new hi(this,new vi(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(tn(t))}};Object.defineProperties(ci.prototype,wi);const Li=new WeakMap,Pi=function(e,t=null){for(const r in e)e[r]=tn(e[r],t);return e},Ui=function(e,t=null){const r=e.length;for(let s=0;su?(o(`TSL: "${r}" parameter length exceeds limit.`,new Is),t.slice(0,u)):t}return null===t?n=(...t)=>i(new e(...nn(d(t)))):null!==r?(r=tn(r),n=(...s)=>i(new e(t,...nn(d(s)),r))):n=(...r)=>i(new e(t,...nn(d(r)))),n.setParameterLength=(...e)=>(1===e.length?a=u=e[0]:2===e.length&&([a,u]=e),n),n.setName=e=>(l=e,n),n},Ii=function(e,...t){return new e(...nn(t))};class Oi extends ci{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:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let u=null;if(t.layout){let s=Li.get(e.constructor);void 0===s&&(s=new WeakMap,Li.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=tn(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i);const n=r?function(e){let t;sn(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(r):null;u=tn(i.call(n))}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return sn(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield tn(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof ci&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=tn(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,o=n||a.length>1?a(i,s):a(s);u=tn(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(s[n]=u),u}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return e.fnCall=o,r}}class Vi extends ci{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 Oi(this,e)}setup(){return this.call()}}const ki=[!1,!0],Gi=[0,1,2,3],zi=[-1,-2],$i=[.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],Wi=new Map;for(const e of ki)Wi.set(e,new vi(e));const Hi=new Map;for(const e of Gi)Hi.set(e,new vi(e,"uint"));const qi=new Map([...Hi].map(e=>new vi(e.value,"int")));for(const e of zi)qi.set(e,new vi(e,"int"));const ji=new Map([...qi].map(e=>new vi(e.value)));for(const e of $i)ji.set(e,new vi(e));for(const e of $i)ji.set(-e,new vi(-e));const Xi={bool:Wi,uint:Hi,ints:qi,float:ji},Ki=new Map([...Wi,...ji]),Qi=(e,t)=>Ki.has(e)?Ki.get(e):!0===e.isNode?e:new vi(e,t),Yi=function(e,t=null){return(...r)=>{for(const t of r)if(void 0===t)return o(`TSL: Invalid parameter for the type "${e}".`,new Is),new vi(0,e);if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(r=[Qs(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return rn(t.get(r[0]));if(1===r.length){const t=Qi(r[0],e);return t.nodeType===e?rn(t):rn(new pi(t,e))}const s=r.map(e=>Qi(e));return rn(new mi(s,e))}};function Zi(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}const Ji=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function en(e,t){return new Vi(e,t)}const tn=(e,t=null)=>function(e,t=null){const r=Ks(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?tn(Qi(e,t)):"shader"===r?e.isFn?e:cn(e):e}(e,t),rn=(e,t=null)=>tn(e,t).toVarIntent(),sn=(e,t=null)=>new Pi(e,t),nn=(e,t=null)=>new Ui(e,t),an=(e,t=null,r=null,s=null)=>new Di(e,t,r,s),on=(e,...t)=>new Ii(e,...t),un=(e,t=null,r=null,s={})=>new Di(e,t,r,{...s,intent:!0});let ln=0;class dn extends ci{constructor(e,t=null){super();let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:o("TSL: Invalid layout type.",new Is),t=null)),this.shaderNode=new en(e,r),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+ln++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}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 o('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function cn(e,t=null){const r=new dn(e,t);return new Proxy(()=>{},{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const hn=e=>{Si=e},pn=()=>Si,gn=(...e)=>Si.If(...e);function mn(e){return Si&&Si.addToStack(e),e}Ai("toStack",mn);const fn=new Yi("color"),yn=new Yi("float",Xi.float),bn=new Yi("int",Xi.ints),xn=new Yi("uint",Xi.uint),Tn=new Yi("bool",Xi.bool),_n=new Yi("vec2"),vn=new Yi("ivec2"),Nn=new Yi("uvec2"),Sn=new Yi("bvec2"),Rn=new Yi("vec3"),An=new Yi("ivec3"),En=new Yi("uvec3"),wn=new Yi("bvec3"),Cn=new Yi("vec4"),Mn=new Yi("ivec4"),Bn=new Yi("uvec4"),Fn=new Yi("bvec4"),Ln=new Yi("mat2"),Pn=new Yi("mat3"),Un=new Yi("mat4");Ai("toColor",fn),Ai("toFloat",yn),Ai("toInt",bn),Ai("toUint",xn),Ai("toBool",Tn),Ai("toVec2",_n),Ai("toIVec2",vn),Ai("toUVec2",Nn),Ai("toBVec2",Sn),Ai("toVec3",Rn),Ai("toIVec3",An),Ai("toUVec3",En),Ai("toBVec3",wn),Ai("toVec4",Cn),Ai("toIVec4",Mn),Ai("toUVec4",Bn),Ai("toBVec4",Fn),Ai("toMat2",Ln),Ai("toMat3",Pn),Ai("toMat4",Un);const Dn=an(hi).setParameterLength(2),In=(e,t)=>new pi(tn(e),t);Ai("element",Dn),Ai("convert",In);Ai("append",e=>(d("TSL: .append() has been renamed to .toStack().",new Is),mn(e)));class On extends ci{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1){super(e),this.name=t,this.varying=r,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Vs(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Vn=(e,t)=>new On(e,t),kn=(e,t)=>new On(e,t,!0),Gn=on(On,"vec4","DiffuseColor"),zn=on(On,"vec3","DiffuseContribution"),$n=on(On,"vec3","EmissiveColor"),Wn=on(On,"float","Roughness"),Hn=on(On,"float","Metalness"),qn=on(On,"float","Clearcoat"),jn=on(On,"float","ClearcoatRoughness"),Xn=on(On,"vec3","Sheen"),Kn=on(On,"float","SheenRoughness"),Qn=on(On,"float","Iridescence"),Yn=on(On,"float","IridescenceIOR"),Zn=on(On,"float","IridescenceThickness"),Jn=on(On,"float","AlphaT"),ea=on(On,"float","Anisotropy"),ta=on(On,"vec3","AnisotropyT"),ra=on(On,"vec3","AnisotropyB"),sa=on(On,"color","SpecularColor"),ia=on(On,"color","SpecularColorBlended"),na=on(On,"float","SpecularF90"),aa=on(On,"float","Shininess"),oa=on(On,"vec4","Output"),ua=on(On,"float","dashSize"),la=on(On,"float","gapSize"),da=on(On,"float","pointWidth"),ca=on(On,"float","IOR"),ha=on(On,"float","Transmission"),pa=on(On,"float","Thickness"),ga=on(On,"float","AttenuationDistance"),ma=on(On,"color","AttenuationColor"),fa=on(On,"float","Dispersion");class ya extends ci{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1,s=null){super("string"),this.name=e,this.shared=t,this.order=r,this.updateType=s,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 ba=(e,t=1,r=null)=>new ya(e,!1,t,r),xa=(e,t=0,r=null)=>new ya(e,!0,t,r),Ta=xa("frame",0,ri.FRAME),_a=xa("render",0,ri.RENDER),va=ba("object",1,ri.OBJECT);class Na extends Ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=va}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const r=e(t,this);void 0!==r&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const Sa=(e,t)=>{const r=Ji(t||e);if(r===e&&(e=Qs(r)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new Na(e,r)};class Ra extends gi{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,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 Aa=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Ra(null,r.length,r)}else{const r=e[0],s=e[1];t=new Ra(r,s)}return tn(t)};Ai("toArray",(e,t)=>Aa(Array(t).fill(e)));class Ea extends gi{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 r=e.getTypeLength(t.node.getNodeType(e));return ui.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getDataFromNode(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t{const s=r.type;let i;return i="pointer"===s?"&"+t.build(e):t.build(e,s),i};if(Array.isArray(i)){if(i.length>s.length)o("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=s.length;else if(i.length(t=t.length>1||t[0]&&!0===t[0].isNode?nn(t):sn(t[0]),new Ca(tn(e),t));Ai("call",Ma);const Ba={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Fa extends gi{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new Fa(e,t,r);for(let t=0;t>"===r||"<<"===r)return e.getIntegerType(n);if("!"===r||"&&"===r||"||"===r||"^^"===r)return"bool";if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),l=i?i.build(e,o):null,d=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===c;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${r} ${l} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${l} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(d)return e.format(`${d}( ${u}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${l}`,n,t);{let i=`( ${u} ${r} ${l} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return d?e.format(`${d}( ${u}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${r} ${u}`,n,t):e.format(`${u} ${r} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const La=un(Fa,"+").setParameterLength(2,1/0).setName("add"),Pa=un(Fa,"-").setParameterLength(2,1/0).setName("sub"),Ua=un(Fa,"*").setParameterLength(2,1/0).setName("mul"),Da=un(Fa,"/").setParameterLength(2,1/0).setName("div"),Ia=un(Fa,"%").setParameterLength(2).setName("mod"),Oa=un(Fa,"==").setParameterLength(2).setName("equal"),Va=un(Fa,"!=").setParameterLength(2).setName("notEqual"),ka=un(Fa,"<").setParameterLength(2).setName("lessThan"),Ga=un(Fa,">").setParameterLength(2).setName("greaterThan"),za=un(Fa,"<=").setParameterLength(2).setName("lessThanEqual"),$a=un(Fa,">=").setParameterLength(2).setName("greaterThanEqual"),Wa=un(Fa,"&&").setParameterLength(2,1/0).setName("and"),Ha=un(Fa,"||").setParameterLength(2,1/0).setName("or"),qa=un(Fa,"!").setParameterLength(1).setName("not"),ja=un(Fa,"^^").setParameterLength(2).setName("xor"),Xa=un(Fa,"&").setParameterLength(2).setName("bitAnd"),Ka=un(Fa,"~").setParameterLength(1).setName("bitNot"),Qa=un(Fa,"|").setParameterLength(2).setName("bitOr"),Ya=un(Fa,"^").setParameterLength(2).setName("bitXor"),Za=un(Fa,"<<").setParameterLength(2).setName("shiftLeft"),Ja=un(Fa,">>").setParameterLength(2).setName("shiftRight"),eo=cn(([e])=>(e.addAssign(1),e)),to=cn(([e])=>(e.subAssign(1),e)),ro=cn(([e])=>{const t=bn(e).toConst();return e.addAssign(1),t}),so=cn(([e])=>{const t=bn(e).toConst();return e.subAssign(1),t});Ai("add",La),Ai("sub",Pa),Ai("mul",Ua),Ai("div",Da),Ai("mod",Ia),Ai("equal",Oa),Ai("notEqual",Va),Ai("lessThan",ka),Ai("greaterThan",Ga),Ai("lessThanEqual",za),Ai("greaterThanEqual",$a),Ai("and",Wa),Ai("or",Ha),Ai("not",qa),Ai("xor",ja),Ai("bitAnd",Xa),Ai("bitNot",Ka),Ai("bitOr",Qa),Ai("bitXor",Ya),Ai("shiftLeft",Za),Ai("shiftRight",Ja),Ai("incrementBefore",eo),Ai("decrementBefore",to),Ai("increment",ro),Ai("decrement",so);const io=(e,t)=>(d('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Is),Ia(bn(e),bn(t)));Ai("modInt",io);class no extends gi{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===no.MAX||e===no.MIN)&&arguments.length>3){let i=new no(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}generateNodeType(e){const t=this.method;return t===no.LENGTH||t===no.DISTANCE||t===no.DOT?"float":t===no.CROSS?"vec3":t===no.ALL||t===no.ANY?"bool":t===no.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===no.ONE_MINUS)i=Pa(1,t);else if(s===no.RECIPROCAL)i=Da(1,t);else if(s===no.DIFFERENCE)i=Vo(Pa(t,r));else if(s===no.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=Cn(Rn(n),0):s=Cn(Rn(s),0);const a=Ua(s,n).xyz;i=Ro(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===no.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const l=[];return r===no.CROSS?l.push(n.build(e,s),a.build(e,s)):u===c&&r===no.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==c||r!==no.MIN&&r!==no.MAX?r===no.REFRACT?l.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===no.MIX?l.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===h&&r===no.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==no.DFDX&&r!==no.DFDY||(d(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),r="/*"+r+"*/"),l.push(n.build(e,i)),null!==a&&l.push(a.build(e,i)),null!==o&&l.push(o.build(e,i))):l.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${l.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}no.ALL="all",no.ANY="any",no.RADIANS="radians",no.DEGREES="degrees",no.EXP="exp",no.EXP2="exp2",no.LOG="log",no.LOG2="log2",no.SQRT="sqrt",no.INVERSE_SQRT="inversesqrt",no.FLOOR="floor",no.CEIL="ceil",no.NORMALIZE="normalize",no.FRACT="fract",no.SIN="sin",no.SINH="sinh",no.COS="cos",no.COSH="cosh",no.TAN="tan",no.TANH="tanh",no.ASIN="asin",no.ASINH="asinh",no.ACOS="acos",no.ACOSH="acosh",no.ATAN="atan",no.ATANH="atanh",no.ABS="abs",no.SIGN="sign",no.LENGTH="length",no.NEGATE="negate",no.ONE_MINUS="oneMinus",no.DFDX="dFdx",no.DFDY="dFdy",no.ROUND="round",no.RECIPROCAL="reciprocal",no.TRUNC="trunc",no.FWIDTH="fwidth",no.TRANSPOSE="transpose",no.DETERMINANT="determinant",no.INVERSE="inverse",no.EQUALS="equals",no.MIN="min",no.MAX="max",no.STEP="step",no.REFLECT="reflect",no.DISTANCE="distance",no.DIFFERENCE="difference",no.DOT="dot",no.CROSS="cross",no.POW="pow",no.TRANSFORM_DIRECTION="transformDirection",no.MIX="mix",no.CLAMP="clamp",no.REFRACT="refract",no.SMOOTHSTEP="smoothstep",no.FACEFORWARD="faceforward";const ao=yn(1e-6),oo=yn(1e6),uo=yn(Math.PI),lo=yn(2*Math.PI),co=yn(2*Math.PI),ho=yn(.5*Math.PI),po=un(no,no.ALL).setParameterLength(1),go=un(no,no.ANY).setParameterLength(1),mo=un(no,no.RADIANS).setParameterLength(1),fo=un(no,no.DEGREES).setParameterLength(1),yo=un(no,no.EXP).setParameterLength(1),bo=un(no,no.EXP2).setParameterLength(1),xo=un(no,no.LOG).setParameterLength(1),To=un(no,no.LOG2).setParameterLength(1),_o=un(no,no.SQRT).setParameterLength(1),vo=un(no,no.INVERSE_SQRT).setParameterLength(1),No=un(no,no.FLOOR).setParameterLength(1),So=un(no,no.CEIL).setParameterLength(1),Ro=un(no,no.NORMALIZE).setParameterLength(1),Ao=un(no,no.FRACT).setParameterLength(1),Eo=un(no,no.SIN).setParameterLength(1),wo=un(no,no.SINH).setParameterLength(1),Co=un(no,no.COS).setParameterLength(1),Mo=un(no,no.COSH).setParameterLength(1),Bo=un(no,no.TAN).setParameterLength(1),Fo=un(no,no.TANH).setParameterLength(1),Lo=un(no,no.ASIN).setParameterLength(1),Po=un(no,no.ASINH).setParameterLength(1),Uo=un(no,no.ACOS).setParameterLength(1),Do=un(no,no.ACOSH).setParameterLength(1),Io=un(no,no.ATAN).setParameterLength(1,2),Oo=un(no,no.ATANH).setParameterLength(1),Vo=un(no,no.ABS).setParameterLength(1),ko=un(no,no.SIGN).setParameterLength(1),Go=un(no,no.LENGTH).setParameterLength(1),zo=un(no,no.NEGATE).setParameterLength(1),$o=un(no,no.ONE_MINUS).setParameterLength(1),Wo=un(no,no.DFDX).setParameterLength(1),Ho=un(no,no.DFDY).setParameterLength(1),qo=un(no,no.ROUND).setParameterLength(1),jo=un(no,no.RECIPROCAL).setParameterLength(1),Xo=un(no,no.TRUNC).setParameterLength(1),Ko=un(no,no.FWIDTH).setParameterLength(1),Qo=un(no,no.TRANSPOSE).setParameterLength(1),Yo=un(no,no.DETERMINANT).setParameterLength(1),Zo=un(no,no.INVERSE).setParameterLength(1),Jo=un(no,no.MIN).setParameterLength(2,1/0),eu=un(no,no.MAX).setParameterLength(2,1/0),tu=un(no,no.STEP).setParameterLength(2),ru=un(no,no.REFLECT).setParameterLength(2),su=un(no,no.DISTANCE).setParameterLength(2),iu=un(no,no.DIFFERENCE).setParameterLength(2),nu=un(no,no.DOT).setParameterLength(2),au=un(no,no.CROSS).setParameterLength(2),ou=un(no,no.POW).setParameterLength(2),uu=e=>Ua(e,e),lu=e=>Ua(e,e,e),du=e=>Ua(e,e,e,e),cu=un(no,no.TRANSFORM_DIRECTION).setParameterLength(2),hu=e=>Ua(ko(e),ou(Vo(e),1/3)),pu=e=>nu(e,e),gu=un(no,no.MIX).setParameterLength(3),mu=(e,t=0,r=1)=>new no(no.CLAMP,tn(e),tn(t),tn(r)),fu=e=>mu(e),yu=un(no,no.REFRACT).setParameterLength(3),bu=un(no,no.SMOOTHSTEP).setParameterLength(3),xu=un(no,no.FACEFORWARD).setParameterLength(3),Tu=cn(([e])=>{const t=nu(e.xy,_n(12.9898,78.233)),r=Ia(t,uo);return Ao(Eo(r).mul(43758.5453))}),_u=(e,t,r)=>gu(t,r,e),vu=(e,t,r)=>bu(t,r,e),Nu=(e,t)=>tu(t,e),Su=xu,Ru=vo;Ai("all",po),Ai("any",go),Ai("radians",mo),Ai("degrees",fo),Ai("exp",yo),Ai("exp2",bo),Ai("log",xo),Ai("log2",To),Ai("sqrt",_o),Ai("inverseSqrt",vo),Ai("floor",No),Ai("ceil",So),Ai("normalize",Ro),Ai("fract",Ao),Ai("sin",Eo),Ai("sinh",wo),Ai("cos",Co),Ai("cosh",Mo),Ai("tan",Bo),Ai("tanh",Fo),Ai("asin",Lo),Ai("asinh",Po),Ai("acos",Uo),Ai("acosh",Do),Ai("atan",Io),Ai("atanh",Oo),Ai("abs",Vo),Ai("sign",ko),Ai("length",Go),Ai("lengthSq",pu),Ai("negate",zo),Ai("oneMinus",$o),Ai("dFdx",Wo),Ai("dFdy",Ho),Ai("round",qo),Ai("reciprocal",jo),Ai("trunc",Xo),Ai("fwidth",Ko),Ai("min",Jo),Ai("max",eu),Ai("step",Nu),Ai("reflect",ru),Ai("distance",su),Ai("dot",nu),Ai("cross",au),Ai("pow",ou),Ai("pow2",uu),Ai("pow3",lu),Ai("pow4",du),Ai("transformDirection",cu),Ai("mix",_u),Ai("clamp",mu),Ai("refract",yu),Ai("smoothstep",vu),Ai("faceForward",xu),Ai("difference",iu),Ai("saturate",fu),Ai("cbrt",hu),Ai("transpose",Qo),Ai("determinant",Yo),Ai("inverse",Zo),Ai("rand",Tu);class Au extends ci{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}generateNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode,r=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?Vn(r).build(e):"";s.nodeProperty=l;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(c,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=n.build(e,r);if(h&&(u?h=l+" = "+h+";":(h="return "+h+";",null===o&&(d("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,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Eu=an(Au).setParameterLength(2,3);Ai("select",Eu);class wu extends ci{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const r=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(r),s}}const Cu=(e=null,t={})=>{let r=e;return null!==r&&!0===r.isNode||(t=r||t,r=null),new wu(r,t)},Mu=e=>Cu(e,{uniformFlow:!0}),Bu=(e,t)=>Cu(e,{nodeName:t});function Fu(e,t,r=null){return Cu(r,{getShadow:({light:r,shadowColorNode:s})=>t===r?s.mul(e):s})}function Lu(e,t=null){return Cu(t,{getAO:(t,{material:r})=>!0===r.transparent?t:null!==t?t.mul(e):e})}function Pu(e,t){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),Bu(e,t)}Ai("context",Cu),Ai("label",Pu),Ai("uniformFlow",Mu),Ai("setName",Bu),Ai("builtinShadowContext",(e,t,r)=>Fu(t,r,e)),Ai("builtinAOContext",(e,t)=>Lu(t,e));class Uu extends ci{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const r=t.getBaseStack();e?r.addToStackBefore(this):r.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,u=!1;s&&(a=e.isDeterministic(t),u=n?s:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&o('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const d=e.getVectorType(l),c=t.build(e,d),h=e.getVarFromNode(this,r,d,void 0,u),p=e.getPropertyName(h);let g=p;if(u)if(n)g=a?`const ${p}`:`let ${p}`;else{const r=t.getArrayCount(e);g=`const ${e.getVar(h.type,p,r)}`}return e.addLineFlowCode(`${g} = ${c}`,this),p}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Du=an(Uu),Iu=(e,t=null)=>Du(e,t).toStack(),Ou=(e,t=null)=>Du(e,t,!0).toStack(),Vu=e=>Du(e).setIntent(!0).toStack();Ai("toVar",Iu),Ai("toConst",Ou),Ai("toVarIntent",Vu);class ku extends ci{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),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 r=this.node.build(e,...t);return e.removeSubBuild(),r}}const Gu=(e,t,r=null)=>new ku(tn(e),t,r);class zu extends ci{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Gu(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 r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=Gu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(ti.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,ti.VERTEX);e.flowNodeFromShaderStage(ti.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const $u=an(zu).setParameterLength(1,2),Wu=e=>$u(e);Ai("toVarying",$u),Ai("toVertexStage",Wu);const Hu=cn(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return gu(t,r,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),qu=cn(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return gu(t,r,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ju="WorkingColorSpace";class Xu extends gi{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===ju?p.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==p.enabled&&r!==s&&r&&s?(p.getTransfer(r)===g&&(i=Cn(Hu(i.rgb),i.a)),p.getPrimaries(r)!==p.getPrimaries(s)&&(i=Cn(Pn(p._getMatrix(new n,r,s)).mul(i.rgb),i.a)),p.getTransfer(s)===g&&(i=Cn(qu(i.rgb),i.a)),i):i}}const Ku=(e,t)=>new Xu(tn(e),ju,t),Qu=(e,t)=>new Xu(tn(e),t,ju);Ai("workingToColorSpace",Ku),Ai("colorSpaceToWorking",Qu);let Yu=class extends hi{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),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class Zu extends ci{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=ri.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Yu(this,tn(e))}setNodeType(e){const t=Sa(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 r=e[t[0]];for(let e=1;enew Ju(e,t,r);class tl extends gi{static get type(){return"ToneMappingNode"}constructor(e,t=sl,r=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Gs(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,r=this._toneMapping;if(r===m)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=Cn(i(t.rgb,this.exposureNode),t.a):(o("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const rl=(e,t,r)=>new tl(e,tn(t),tn(r)),sl=el("toneMappingExposure","float");Ai("toneMapping",(e,t,r)=>rl(t,r,e));const il=new WeakMap;function nl(e,t){let r=il.get(e);return void 0===r&&(r=new b(e,t),il.set(e,r)),r}class al extends Ti{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=f,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.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),r=e.getTypeLength(t),s=this.value,i=this.bufferStride||r,n=this.bufferOffset;let a;a=!0===s.isInterleavedBuffer?s:!0===s.isBufferAttribute?nl(s.array,i):nl(s,i);const o=new y(a,r,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(r);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=s,i=s;else{i=$u(this).build(e,t)}return i}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 ol(e,t=null,r=0,s=0,i=f,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Pn(new al(e,"vec3",9,0).setUsage(i).setInstanced(n),new al(e,"vec3",9,3).setUsage(i).setInstanced(n),new al(e,"vec3",9,6).setUsage(i).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Un(new al(e,"vec4",16,0).setUsage(i).setInstanced(n),new al(e,"vec4",16,4).setUsage(i).setInstanced(n),new al(e,"vec4",16,8).setUsage(i).setInstanced(n),new al(e,"vec4",16,12).setUsage(i).setInstanced(n)):new al(e,t,r,s).setUsage(i)}const ul=(e,t=null,r=0,s=0)=>ol(e,t,r,s),ll=(e,t=null,r=0,s=0)=>ol(e,t,r,s,f,!0),dl=(e,t=null,r=0,s=0)=>ol(e,t,r,s,x,!0);Ai("toAttribute",e=>ul(e.value));class cl extends ci{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===cl.VERTEX)s=e.getVertexIndex();else if(r===cl.INSTANCE)s=e.getInstanceIndex();else if(r===cl.DRAW)s=e.getDrawIndex();else if(r===cl.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===cl.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==cl.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=$u(this).build(e,t)}return i}}cl.VERTEX="vertex",cl.INSTANCE="instance",cl.SUBGROUP="subgroup",cl.INVOCATION_LOCAL="invocationLocal",cl.INVOCATION_SUBGROUP="invocationSubgroup",cl.DRAW="draw";const hl=on(cl,cl.VERTEX),pl=on(cl,cl.INSTANCE),gl=on(cl,cl.SUBGROUP),ml=on(cl,cl.INVOCATION_SUBGROUP),fl=on(cl,cl.INVOCATION_LOCAL),yl=on(cl,cl.DRAW);class bl extends ci{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=ri.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=Sa(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:r}=e;if("compute"===r){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"),r=pl.build(e,"uint");e.flow.code=`${e.tab}if ( ${r} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const xl=(e,t=[64])=>{(0===t.length||t.length>3)&&o("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Is);for(let e=0;e{const s=xl(e,r);return"number"==typeof t?s.count=t:s.dispatchSize=t,s};Ai("compute",Tl),Ai("computeKernel",xl);class _l extends ci{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(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vl=e=>new _l(tn(e));function Nl(e,t=!0){return d('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vl(e).setParent(t)}Ai("cache",Nl),Ai("isolate",vl);class Sl extends ci{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)}}const Rl=an(Sl).setParameterLength(2);Ai("bypass",Rl);const Al=cn(([e,t,r,s=yn(0),i=yn(1),n=Tn(!1)])=>{let a=e.sub(t).div(r.sub(t));return Zi(n)&&(a=a.clamp()),a.mul(i.sub(s)).add(s)});function El(e,t,r,s=yn(0),i=yn(1)){return Al(e,t,r,s,i,!0)}Ai("remap",Al),Ai("remapClamp",El);class wl extends ci{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Cl=an(wl).setParameterLength(1,2),Ml=e=>(e?Eu(e,Cl("discard")):Cl("discard")).toStack();Ai("discard",Ml);class Bl extends gi{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||m,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||T;return r!==m&&(t=t.toneMapping(r)),s!==T&&s!==p.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Fl=(e,t=null,r=null)=>new Bl(tn(e),t,r);Ai("renderOutput",Fl);class Ll extends gi{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,r=this.node.build(e);if(null!==t)t(e,r);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(t.length);let i="";i+="// #"+t+"#\n",i+=e.flow.code.replace(/^\t/gm,"")+"\n",i+="/* ... */ "+r+" /* ... */\n",i+="// #"+s+"#\n",_(i)}return r}}const Pl=(e,t=null)=>new Ll(tn(e),t).toStack();Ai("debug",Pl);class Ul extends u{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Dl extends ci{static get type(){return"InspectorNode"}constructor(e,t="",r=null){super(),this.node=e,this.name=t,this.callback=r,this.updateType=ri.FRAME,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!==Ul&&v('TSL: ".toInspector()" is only available with WebGPU.'),t}}function Il(e,t="",r=null){return(e=tn(e)).before(new Dl(e,t,r))}Ai("toInspector",Il);class Ol extends ci{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 r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return $u(this).build(e,r)}return d(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Vl=(e,t=null)=>new Ol(e,t),kl=(e=0)=>Vl("uv"+(e>0?e:""),"vec2");class Gl extends ci{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const zl=an(Gl).setParameterLength(1,2);class $l extends Na{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ri.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const Wl=an($l).setParameterLength(1);class Hl extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const ql=new N;class jl extends Na{static get type(){return"TextureNode"}constructor(e=ql,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ri.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===S?"uvec4":this.value.type===R?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return kl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Sa(this.value.matrix)),this._matrixUniform.mul(Rn(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Sa(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(bn(zl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Hl("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const s=cn(()=>{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?ri.OBJECT:ri.NONE,t})();let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(A.TEXTURE_COMPARE))n=this.compareNode;else{const e=r.compareFunction;null===e||e===E||e===w||e===C||e===M?a=this.compareNode:(n=this.compareNode,v('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;let d;return d=i?e.generateTextureBias(l,t,r,i,n,u):o?e.generateTextureGrad(l,t,r,o,n,u):a?e.generateTextureCompare(l,t,r,a,n,u):!1===this.sampler?e.generateTextureLoad(l,t,r,s,n,u):s?e.generateTextureLevel(l,t,r,s,n,u):e.generateTexture(l,t,r,n,u),d}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:u,biasNode:l,compareNode:d,compareStepNode:c,depthNode:h,gradNode:p,offsetNode:g}=s,m=this.generateUV(e,t),f=u?u.build(e,"float"):null,y=l?l.build(e,"float"):null,b=h?h.build(e,"int"):null,x=d?d.build(e,"float"):null,T=c?c.build(e,"float"):null,_=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,v=g?this.generateOffset(e,g):null;let N=b;null===N&&r.isArrayTexture&&!0!==this.isTexture3DNode&&(N="0");const S=e.getVarFromNode(this);o=e.getPropertyName(S);let R=this.generateSnippet(e,i,m,f,y,N,x,_,v);if(null!==T){const t=r.compareFunction;R=t===C||t===M?tu(Cl(R,a),Cl(T,"float")).build(e,a):tu(Cl(T,"float"),Cl(R,a)).build(e,a)}e.addLineFlowCode(`${o} = ${R}`,this),n.snippet=R,n.propertyName=o}let u=o;return e.needsToWorkingColorSpace(r)&&(u=Qu(Cl(u,a),r.colorSpace).setup(e).build(e,a)),e.format(u,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=tn(e),t.referenceNode=this.getBase(),tn(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=tn(e).mul(Wl(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===B||r.magFilter===B)&&(d("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),tn(t)}level(e){const t=this.clone();return t.levelNode=tn(e),t.referenceNode=this.getBase(),tn(t)}size(e){return zl(this,e)}bias(e){const t=this.clone();return t.biasNode=tn(e),t.referenceNode=this.getBase(),tn(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=tn(e),t.referenceNode=this.getBase(),tn(t)}grad(e,t){const r=this.clone();return r.gradNode=[tn(e),tn(t)],r.referenceNode=this.getBase(),tn(r)}depth(e){const t=this.clone();return t.depthNode=tn(e),t.referenceNode=this.getBase(),tn(t)}offset(e){const t=this.clone();return t.offsetNode=tn(e),t.referenceNode=this.getBase(),tn(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 r=this._flipYUniform;null!==r&&(r.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const Xl=an(jl).setParameterLength(1,4).setName("texture"),Kl=(e=ql,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=tn(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=Xl(e,t,r,s),i},Ql=(...e)=>Kl(...e).setSampler(!1);class Yl extends Na{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r,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 Zl=(e,t,r)=>new Yl(e,t,r);class Jl extends hi{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(e),s=this.node.getPaddedType();return e.format(t,s,r)}}class ed extends Yl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ks(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ri.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rnew ed(e,t);class rd extends ci{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const sd=an(rd).setParameterLength(1);let id,nd;class ad extends ci{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===ad.DPR?"float":this.scope===ad.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ri.NONE;return this.scope!==ad.SIZE&&this.scope!==ad.VIEWPORT&&this.scope!==ad.DPR||(e=ri.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===ad.VIEWPORT?null!==t?nd.copy(t.viewport):(e.getViewport(nd),nd.multiplyScalar(e.getPixelRatio())):this.scope===ad.DPR?this._output.value=e.getPixelRatio():null!==t?(id.width=t.width,id.height=t.height):e.getDrawingBufferSize(id)}setup(){const e=this.scope;let r=null;return r=e===ad.SIZE?Sa(id||(id=new t)):e===ad.VIEWPORT?Sa(nd||(nd=new s)):e===ad.DPR?Sa(1):_n(dd.div(ld)),this._output=r,r}generate(e){if(this.scope===ad.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(ld).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}ad.COORDINATE="coordinate",ad.VIEWPORT="viewport",ad.SIZE="size",ad.UV="uv",ad.DPR="dpr";const od=on(ad,ad.DPR),ud=on(ad,ad.UV),ld=on(ad,ad.SIZE),dd=on(ad,ad.COORDINATE),cd=on(ad,ad.VIEWPORT),hd=cd.zw,pd=dd.sub(cd.xy),gd=pd.div(hd),md=cn(()=>(d('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new Is),ld),"vec2").once()();let fd=null,yd=null,bd=null,xd=null,Td=null,_d=null,vd=null,Nd=null,Sd=null,Rd=null,Ad=null,Ed=null,wd=null,Cd=null;const Md=Sa(0,"uint").setName("u_cameraIndex").setGroup(xa("cameraIndex")).toVarying("v_cameraIndex"),Bd=Sa("float").setName("cameraNear").setGroup(_a).onRenderUpdate(({camera:e})=>e.near),Fd=Sa("float").setName("cameraFar").setGroup(_a).onRenderUpdate(({camera:e})=>e.far),Ld=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);null===yd?yd=td(r).setGroup(_a).setName("cameraProjectionMatrices"):yd.array=r,t=yd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrix")}else null===fd&&(fd=Sa(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=fd;return t}).once()(),Pd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);null===xd?xd=td(r).setGroup(_a).setName("cameraProjectionMatricesInverse"):xd.array=r,t=xd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraProjectionMatrixInverse")}else null===bd&&(bd=Sa(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(_a).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=bd;return t}).once()(),Ud=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);null===_d?_d=td(r).setGroup(_a).setName("cameraViewMatrices"):_d.array=r,t=_d.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraViewMatrix")}else null===Td&&(Td=Sa(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=Td;return t}).once()(),Dd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);null===Nd?Nd=td(r).setGroup(_a).setName("cameraWorldMatrices"):Nd.array=r,t=Nd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraWorldMatrix")}else null===vd&&(vd=Sa(e.matrixWorld).setName("cameraWorldMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=vd;return t}).once()(),Id=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);null===Rd?Rd=td(r).setGroup(_a).setName("cameraNormalMatrices"):Rd.array=r,t=Rd.element(e.isMultiViewCamera?sd("gl_ViewID_OVR"):Md).toConst("cameraNormalMatrix")}else null===Sd&&(Sd=Sa(e.normalMatrix).setName("cameraNormalMatrix").setGroup(_a).onRenderUpdate(({camera:e})=>e.normalMatrix)),t=Sd;return t}).once()(),Od=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t{const r=e.cameras,s=t.array;for(let e=0,t=r.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=Ad;return t}).once()(),Vd=cn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);null===Cd?Cd=td(r,"vec4").setGroup(_a).setName("cameraViewports"):Cd.array=r,t=Cd.element(Md).toConst("cameraViewport")}else null===wd&&(wd=Cn(0,0,ld.x,ld.y).toConst("cameraViewport")),t=wd;return t}).once()(),kd=new F;class Gd extends ci{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ri.OBJECT,this.uniformNode=new Na(null)}generateNodeType(){const e=this.scope;return e===Gd.WORLD_MATRIX?"mat4":e===Gd.POSITION||e===Gd.VIEW_POSITION||e===Gd.DIRECTION||e===Gd.SCALE?"vec3":e===Gd.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Gd.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gd.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gd.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gd.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===Gd.VIEW_POSITION){const i=e.camera;s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Gd.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),kd.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=kd.radius}}generate(e){const t=this.scope;return t===Gd.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Gd.POSITION||t===Gd.VIEW_POSITION||t===Gd.DIRECTION||t===Gd.SCALE?this.uniformNode.nodeType="vec3":t===Gd.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}}Gd.WORLD_MATRIX="worldMatrix",Gd.POSITION="position",Gd.SCALE="scale",Gd.VIEW_POSITION="viewPosition",Gd.DIRECTION="direction",Gd.RADIUS="radius";const zd=an(Gd,Gd.DIRECTION).setParameterLength(1),$d=an(Gd,Gd.WORLD_MATRIX).setParameterLength(1),Wd=an(Gd,Gd.POSITION).setParameterLength(1),Hd=an(Gd,Gd.SCALE).setParameterLength(1),qd=an(Gd,Gd.VIEW_POSITION).setParameterLength(1),jd=an(Gd,Gd.RADIUS).setParameterLength(1);class Xd extends Gd{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Kd=on(Xd,Xd.DIRECTION),Qd=on(Xd,Xd.WORLD_MATRIX),Yd=on(Xd,Xd.POSITION),Zd=on(Xd,Xd.SCALE),Jd=on(Xd,Xd.VIEW_POSITION),ec=on(Xd,Xd.RADIUS),tc=Sa(new n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),rc=Sa(new a).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),sc=cn(e=>e.context.modelViewMatrix||ic).once()().toVar("modelViewMatrix"),ic=Ud.mul(Qd),nc=cn(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Sa("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),ac=cn(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Sa("mat3").onObjectUpdate(({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),oc=cn(e=>"fragment"!==e.shaderStage?(v("TSL: `clipSpace` is only available in fragment stage."),Cn()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),uc=Vl("position","vec3"),lc=uc.toVarying("positionLocal"),dc=uc.toVarying("positionPrevious"),cc=cn(e=>Qd.mul(lc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),hc=cn(()=>lc.transformDirection(Qd).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),pc=cn(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Pd.mul(oc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),gc=cn(e=>{let t;return t=e.camera.isOrthographicCamera?Rn(0,0,1):pc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class mc extends ci{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===L?"false":e.getFrontFacing()}}const fc=on(mc),yc=yn(fc).mul(2).sub(1),bc=cn(([e],{material:t})=>{const r=t.side;return r===L?e=e.mul(-1):r===P&&(e=e.mul(yc)),e}),xc=Vl("normal","vec3"),Tc=cn(e=>!1===e.geometry.hasAttribute("normal")?(d('TSL: Vertex attribute "normal" not found on geometry.'),Rn(0,1,0)):xc,"vec3").once()().toVar("normalLocal"),_c=pc.dFdx().cross(pc.dFdy()).normalize().toVar("normalFlat"),vc=cn(e=>{let t;return t=e.isFlatShading()?_c:wc(Tc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Nc=cn(e=>{let t=vc.transformDirection(Ud);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Sc=cn(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=vc,!0!==e.isFlatShading()&&(t=bc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Rc=Sc.transformDirection(Ud).toVar("normalWorld"),Ac=cn(({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Sc:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Ec=cn(([e,t=Qd])=>{const r=Pn(t),s=e.div(Rn(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz}),wc=cn(([e],t)=>{const r=t.context.modelNormalViewMatrix;if(r)return r.transformDirection(e);const s=tc.mul(e);return Ud.transformDirection(s)}),Cc=cn(()=>(d('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Sc)).once(["NORMAL","VERTEX"])(),Mc=cn(()=>(d('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Rc)).once(["NORMAL","VERTEX"])(),Bc=cn(()=>(d('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ac)).once(["NORMAL","VERTEX"])(),Fc=new a,Lc=Sa(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Pc=Sa(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Uc=Sa(new a).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const r=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?Fc.makeRotationFromEuler(r).transpose():Fc.identity(),Fc}),Dc=gc.negate().reflect(Sc),Ic=gc.negate().refract(Sc,Lc),Oc=Dc.transformDirection(Ud).toVar("reflectVector"),Vc=Ic.transformDirection(Ud).toVar("reflectVector"),kc=new U;class Gc extends jl{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===D?Oc:e.mapping===I?Vc:(o('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Rn(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!0===r.isDepthTexture?e.renderer.coordinateSystem===h?Rn(t.x,t.y.negate(),t.z):t:(t=Uc.mul(t),e.renderer.coordinateSystem!==h&&r.isRenderTargetTexture||(t=Rn(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const zc=an(Gc).setParameterLength(1,4).setName("cubeTexture"),$c=(e=kc,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=tn(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=tn(t)),null!==r&&(i.levelNode=tn(r)),null!==s&&(i.biasNode=tn(s))):i=zc(e,t,r,s),i};class Wc extends hi{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),r=this.referenceNode.getNodeType(e),s=this.getNodeType(e);return e.format(t,r,s)}}class Hc extends ci{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=ri.OBJECT}element(e){return new Wc(this,tn(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Zl(null,e,this.count):Array.isArray(this.getValueFromReference())?td(null,e):"texture"===e?Kl(null):"cubeTexture"===e?$c(null):Sa(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 r=e[t[0]];for(let e=1;enew Hc(e,t,r),jc=(e,t,r,s)=>new Hc(e,t,s,r);class Xc extends Hc{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Kc=(e,t,r=null)=>new Xc(e,t,r),Qc=kl(),Yc=pc.dFdx(),Zc=pc.dFdy(),Jc=Qc.dFdx(),eh=Qc.dFdy(),th=Sc,rh=Zc.cross(th),sh=th.cross(Yc),ih=rh.mul(Jc.x).add(sh.mul(eh.x)),nh=rh.mul(Jc.y).add(sh.mul(eh.y)),ah=ih.dot(ih).max(nh.dot(nh)),oh=ah.equal(0).select(0,ah.inverseSqrt()),uh=ih.mul(oh).toVar("tangentViewFrame"),lh=nh.mul(oh).toVar("bitangentViewFrame"),dh=Vl("tangent","vec4"),ch=dh.xyz.toVar("tangentLocal"),hh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?sc.mul(Cn(ch,0)).xyz.toVarying("v_tangentView").normalize():uh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ph=hh.transformDirection(Ud).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),gh=cn(([e,t],r)=>{let s=e.mul(dh.w).xyz;return"NORMAL"===r.subBuildFn&&!0!==r.isFlatShading()&&(s=s.toVarying(t)),s}).once(["NORMAL"]),mh=gh(xc.cross(dh),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),fh=gh(Tc.cross(ch),"v_bitangentLocal").normalize().toVar("bitangentLocal"),yh=cn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?gh(Sc.cross(hh),"v_bitangentView").normalize():lh,!0!==e.isFlatShading()&&(t=bc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),bh=gh(Rc.cross(ph),"v_bitangentWorld").normalize().toVar("bitangentWorld"),xh=Pn(hh,yh,Sc).toVar("TBNViewMatrix"),Th=gc.mul(xh),_h=cn(()=>{let e=ra.cross(gc);return e=e.cross(ra).normalize(),e=gu(e,Sc,ea.mul(Wn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),vh=e=>tn(e).mul(.5).add(.5),Nh=e=>Rn(e,_o(fu(yn(1).sub(nu(e,e)))));class Sh extends gi{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=O,this.unpackNormalMode=V}setup(e){const{normalMapType:t,scaleNode:r,unpackNormalMode:s}=this;let i=this.node.mul(2).sub(1);if(t===O?s===k?i=Nh(i.xy):s===G?i=Nh(i.yw):s!==V&&o(`THREE.NodeMaterial: Unexpected unpack normal mode: ${s}`):s!==V&&o(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${s}'`),null!==r){let t=r;!0===e.isFlatShading()&&(t=bc(t)),i=Rn(i.xy.mul(t),i.z)}let n=null;return t===z?n=wc(i):t===O?n=xh.mul(i).normalize():(o(`NodeMaterial: Unsupported normal map type: ${t}`),n=Sc),n}}const Rh=an(Sh).setParameterLength(1,2),Ah=cn(({textureNode:e,bumpScale:t})=>{const r=t=>e.isolate().context({getUV:e=>t(e.uvNode||kl()),forceUVContext:!0}),s=yn(r(e=>e));return _n(yn(r(e=>e.add(e.dFdx()))).sub(s),yn(r(e=>e.add(e.dFdy()))).sub(s)).mul(t)}),Eh=cn(e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(yc),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()});class wh extends gi{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Ah({textureNode:this.textureNode,bumpScale:e});return Eh({surf_pos:pc,surf_norm:Sc,dHdxy:t})}}const Ch=an(wh).setParameterLength(1,2),Mh=new Map;class Bh extends ci{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Mh.get(e);return void 0===r&&(r=Kc(e,t),Mh.set(e,r)),r}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,r=this.scope;let s=null;if(r===Bh.COLOR){const e=void 0!==t.color?this.getColor(r):Rn();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Bh.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Bh.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:yn(1);else if(r===Bh.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Bh.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Bh.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Bh.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Bh.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Bh.NORMAL)t.normalMap?(s=Rh(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType,t.normalMap.format!=$&&t.normalMap.format!=W&&t.normalMap.format!=H||(s.unpackNormalMode=k)):s=t.bumpMap?Ch(this.getTexture("bump").r,this.getFloat("bumpScale")):Sc;else if(r===Bh.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Bh.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Rh(this.getTexture(r),this.getCache(r+"Scale","vec2")):Sc;else if(r===Bh.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Bh.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(1e-4,1)}else if(r===Bh.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=Ln(mp.x,mp.y,mp.y.negate(),mp.x).mul(e.rg.mul(2).sub(_n(1)).normalize().mul(e.b))}else s=mp;else if(r===Bh.IRIDESCENCE_THICKNESS){const e=qc("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=qc("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Bh.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Bh.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Bh.IOR)s=this.getFloat(r);else if(r===Bh.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Bh.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Bh.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):yn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Bh.ALPHA_TEST="alphaTest",Bh.COLOR="color",Bh.OPACITY="opacity",Bh.SHININESS="shininess",Bh.SPECULAR="specular",Bh.SPECULAR_STRENGTH="specularStrength",Bh.SPECULAR_INTENSITY="specularIntensity",Bh.SPECULAR_COLOR="specularColor",Bh.REFLECTIVITY="reflectivity",Bh.ROUGHNESS="roughness",Bh.METALNESS="metalness",Bh.NORMAL="normal",Bh.CLEARCOAT="clearcoat",Bh.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Bh.CLEARCOAT_NORMAL="clearcoatNormal",Bh.EMISSIVE="emissive",Bh.ROTATION="rotation",Bh.SHEEN="sheen",Bh.SHEEN_ROUGHNESS="sheenRoughness",Bh.ANISOTROPY="anisotropy",Bh.IRIDESCENCE="iridescence",Bh.IRIDESCENCE_IOR="iridescenceIOR",Bh.IRIDESCENCE_THICKNESS="iridescenceThickness",Bh.IOR="ior",Bh.TRANSMISSION="transmission",Bh.THICKNESS="thickness",Bh.ATTENUATION_DISTANCE="attenuationDistance",Bh.ATTENUATION_COLOR="attenuationColor",Bh.LINE_SCALE="scale",Bh.LINE_DASH_SIZE="dashSize",Bh.LINE_GAP_SIZE="gapSize",Bh.LINE_WIDTH="linewidth",Bh.LINE_DASH_OFFSET="dashOffset",Bh.POINT_SIZE="size",Bh.DISPERSION="dispersion",Bh.LIGHT_MAP="light",Bh.AO="ao";const Fh=on(Bh,Bh.ALPHA_TEST),Lh=on(Bh,Bh.COLOR),Ph=on(Bh,Bh.SHININESS),Uh=on(Bh,Bh.EMISSIVE),Dh=on(Bh,Bh.OPACITY),Ih=on(Bh,Bh.SPECULAR),Oh=on(Bh,Bh.SPECULAR_INTENSITY),Vh=on(Bh,Bh.SPECULAR_COLOR),kh=on(Bh,Bh.SPECULAR_STRENGTH),Gh=on(Bh,Bh.REFLECTIVITY),zh=on(Bh,Bh.ROUGHNESS),$h=on(Bh,Bh.METALNESS),Wh=on(Bh,Bh.NORMAL),Hh=on(Bh,Bh.CLEARCOAT),qh=on(Bh,Bh.CLEARCOAT_ROUGHNESS),jh=on(Bh,Bh.CLEARCOAT_NORMAL),Xh=on(Bh,Bh.ROTATION),Kh=on(Bh,Bh.SHEEN),Qh=on(Bh,Bh.SHEEN_ROUGHNESS),Yh=on(Bh,Bh.ANISOTROPY),Zh=on(Bh,Bh.IRIDESCENCE),Jh=on(Bh,Bh.IRIDESCENCE_IOR),ep=on(Bh,Bh.IRIDESCENCE_THICKNESS),tp=on(Bh,Bh.TRANSMISSION),rp=on(Bh,Bh.THICKNESS),sp=on(Bh,Bh.IOR),ip=on(Bh,Bh.ATTENUATION_DISTANCE),np=on(Bh,Bh.ATTENUATION_COLOR),ap=on(Bh,Bh.LINE_SCALE),op=on(Bh,Bh.LINE_DASH_SIZE),up=on(Bh,Bh.LINE_GAP_SIZE),lp=on(Bh,Bh.LINE_WIDTH),dp=on(Bh,Bh.LINE_DASH_OFFSET),cp=on(Bh,Bh.POINT_SIZE),hp=on(Bh,Bh.DISPERSION),pp=on(Bh,Bh.LIGHT_MAP),gp=on(Bh,Bh.AO),mp=Sa(new t).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))}),fp=cn(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class yp extends hi{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 r=this.storageBufferNode.structTypeNode;return r?r.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 r;const s=e.context.assign;if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const bp=an(yp).setParameterLength(2);class xp extends Yl{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStruct?(s="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Ws(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=ii.READ_WRITE,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 r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return bp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ii.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=ul(this.value),this._varying=$u(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:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Tp=(e,t=null,r=0)=>new xp(e,t,r);class _p extends ci{static get type(){return"InstanceNode"}constructor(e,t,r=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=r,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=ri.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:r}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:s,isStorageColor:i}=this;if(s&&null===r){if(i)r=Tp(s,"vec3",Math.max(s.count,1)).element(pl);else{const e=new q(s.array,3),t=s.usage===x?dl:ll;this.bufferColor=e,r=Rn(t(e,"vec3",3,0))}this.instanceColorNode=r}const n=t.mul(lc).xyz;if(lc.assign(n),e.needsPreviousData()&&dc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=Ec(Tc,t);Tc.assign(e)}null!==this.instanceColorNode&&kn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(dc).xyz}_createInstanceMatrixNode(e,t){let r;const{instanceMatrix:s}=this,{count:i}=s;if(this.isStorageMatrix)r=Tp(s,"mat4",Math.max(i,1)).element(pl);else{if(16*i*4<=t.getUniformBufferLimit())r=Zl(s.array,"mat4",Math.max(i,1)).element(pl);else{const t=new j(s.array,16,1);!0===e&&(this.buffer=t);const i=s.usage===x?dl:ll,n=[i(t,"vec4",16,0),i(t,"vec4",16,4),i(t,"vec4",16,8),i(t,"vec4",16,12)];r=Un(...n)}}return r}}const vp=an(_p).setParameterLength(2,3);class Np extends _p{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Sp=an(Np).setParameterLength(1);class Rp extends ci{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=pl:this.batchingIdNode=yl);const t=cn(([e])=>{const t=bn(zl(Ql(this.batchMesh._indirectTexture),0).x).toConst(),r=bn(e).mod(t).toConst(),s=bn(e).div(t).toConst();return Ql(this.batchMesh._indirectTexture,vn(r,s)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(bn(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=bn(zl(Ql(s),0).x).toConst(),n=yn(r).mul(4).toInt().toConst(),a=n.mod(i).toConst(),o=n.div(i).toConst(),u=Un(Ql(s,vn(a,o)),Ql(s,vn(a.add(1),o)),Ql(s,vn(a.add(2),o)),Ql(s,vn(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=cn(([e])=>{const t=bn(zl(Ql(l),0).x).toConst(),r=e,s=r.mod(t).toConst(),i=r.div(t).toConst();return Ql(l,vn(s,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);kn("vec3","vBatchColor").assign(t)}const d=Pn(u);lc.assign(u.mul(lc));const c=Tc.div(Rn(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Tc.assign(h),e.hasGeometryAttribute("tangent")&&ch.mulAssign(d)}}const Ap=an(Rp).setParameterLength(1),Ep=new WeakMap;class wp extends ci{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=ri.OBJECT,this.skinIndexNode=Vl("skinIndex","uvec4"),this.skinWeightNode=Vl("skinWeight","vec4"),this.bindMatrixNode=qc("bindMatrix","mat4"),this.bindMatrixInverseNode=qc("bindMatrixInverse","mat4"),this.boneMatricesNode=jc("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=lc,this.toPositionNode=lc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w),d=i.mul(t),c=La(a.mul(s.x).mul(d),o.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=Tc,r=ch){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(s.x),u=e.element(s.y),l=e.element(s.z),d=e.element(s.w);let c=La(i.x.mul(o),i.y.mul(u),i.z.mul(l),i.w.mul(d));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(r).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=jc("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,dc)}setup(e){e.needsPreviousData()&&dc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:r}=this.getSkinnedNormalAndTangent();Tc.assign(t),e.hasGeometryAttribute("tangent")&&ch.assign(r)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Ep.get(t)!==e.frameId&&(Ep.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const Cp=e=>new wp(e);class Mp extends ci{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 r={};for(let e=0,t=this.params.length-1;eNumber(l)?">=":"<")),a)n=`while ( ${l} )`;else{const r={start:u,end:l},s=r.start,i=r.end;let a;const g=()=>h.includes("<")?"+=":"-=";if(null!=p)switch(typeof p){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=d+" "+g()+" "+e.generateConst(c,p);break;case"string":a=d+" "+p;break;default:p.isNode?a=d+" "+g()+" "+p.build(e):(o("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else p="int"===c||"uint"===c?h.includes("<")?"++":"--":g()+" 1.",a=d+" "+p;n=`for ( ${e.getVar(c,d)+" = "+s}; ${d+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tnew Mp(nn(e,"int")).toStack(),Fp=()=>Cl("break").toStack(),Lp=new WeakMap,Pp=new s,Up=cn(({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=bn(hl).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ql(e,vn(u,o)).depth(i).xyz.mul(t)});class Dp extends ci{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Sa(1),this.updateType=ri.OBJECT}setup(e){const{geometry:r}=e,s=void 0!==r.morphAttributes.position,i=r.hasAttribute("normal")&&void 0!==r.morphAttributes.normal,n=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,a=void 0!==n?n.length:0,{texture:o,stride:u,size:l}=function(e){const r=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=Lp.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===r&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new X(m,h,p,a);f.type=K,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=yn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ql(this.mesh.morphTexture,vn(bn(e).add(1),bn(pl))).r):t.assign(qc("morphTargetInfluences","float").element(e).toVar()),gn(t.notEqual(0),()=>{!0===s&&lc.addAssign(Up({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(0)})),!0===i&&Tc.addAssign(Up({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:bn(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const Ip=an(Dp).setParameterLength(1);class Op extends ci{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vp extends Op{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class kp extends wu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=null,s=null){super(e),this.lightingModel=t,this.backdropNode=r,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,r={directDiffuse:Rn().toVar("directDiffuse"),directSpecular:Rn().toVar("directSpecular"),indirectDiffuse:Rn().toVar("indirectDiffuse"),indirectSpecular:Rn().toVar("indirectSpecular")};return{radiance:Rn().toVar("radiance"),irradiance:Rn().toVar("irradiance"),iblIrradiance:Rn().toVar("iblIrradiance"),ambientOcclusion:yn(1).toVar("ambientOcclusion"),reflectedLight:r,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Gp=an(kp);class zp extends Op{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const $p=new t;class Wp extends jl{static get type(){return"ViewportTextureNode"}constructor(e=ud,t=null,r=null){let s=null;null===r?(s=new Q,s.minFilter=Y,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=ri.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;null===i?t.getDrawingBufferSize($p):i.getDrawingBufferSize?i.getDrawingBufferSize($p):$p.set(i.width,i.height);const n=this.getTextureForReference(i);n.image.width===$p.width&&n.image.height===$p.height||(n.image.width=$p.width,n.image.height=$p.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Hp=an(Wp).setParameterLength(0,3),qp=an(Wp,null,null,{generateMipmaps:!0}).setParameterLength(0,3),jp=qp(),Xp=(e=ud,t=null)=>jp.sample(e,t);let Kp=null;class Qp extends Wp{static get type(){return"ViewportDepthTextureNode"}constructor(e=ud,t=null,r=null){null===r&&(null===Kp&&(Kp=new Z),r=Kp),super(e,t,r)}}const Yp=an(Qp).setParameterLength(0,3);class Zp extends ci{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===Zp.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Zp.DEPTH_BASE)null!==r&&(s=ng().assign(r));else if(t===Zp.DEPTH)s=e.isPerspectiveCamera?tg(pc.z,Bd,Fd):Jp(pc.z,Bd,Fd);else if(t===Zp.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=sg(r,Bd,Fd);s=Jp(e,Bd,Fd)}else s=r;else s=Jp(pc.z,Bd,Fd);return s}}Zp.DEPTH_BASE="depthBase",Zp.DEPTH="depth",Zp.LINEAR_DEPTH="linearDepth";const Jp=(e,t,r)=>e.add(t).div(t.sub(r)),eg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?r.sub(t).mul(e).sub(r):t.sub(r).mul(e).sub(t)),tg=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),rg=(e,t,r)=>t.mul(e.add(r)).div(e.mul(t.sub(r))),sg=cn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?t.mul(r).div(t.sub(r).mul(e).sub(t)):t.mul(r).div(r.sub(t).mul(e).sub(r))),ig=(e,t,r)=>{t=t.max(1e-6).toVar();const s=To(e.negate().div(t)),i=To(r.div(t));return s.div(i)},ng=an(Zp,Zp.DEPTH_BASE),ag=on(Zp,Zp.DEPTH),og=an(Zp,Zp.LINEAR_DEPTH).setParameterLength(0,1),ug=og(Yp());ag.assign=e=>ng(e);class lg extends ci{static get type(){return"ClippingNode"}constructor(e=lg.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===lg.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===lg.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return cn(()=>{const r=yn().toVar("distanceToPlane"),s=yn().toVar("distanceToGradient"),i=yn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=td(t).setGroup(_a);Bp(n,({i:t})=>{const n=e.element(t);r.assign(pc.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(bu(s.negate(),s,r))})}const a=e.length;if(a>0){const t=td(e).setGroup(_a),n=yn(1).toVar("intersectionClipOpacity");Bp(a,({i:e})=>{const i=t.element(e);r.assign(pc.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(bu(s.negate(),s,r).oneMinus())}),i.mulAssign(n.oneMinus())}Gn.a.mulAssign(i),Gn.a.equal(0).discard()})()}setupDefault(e,t){return cn(()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=td(t).setGroup(_a);Bp(r,({i:t})=>{const r=e.element(t);pc.dot(r.xyz).greaterThan(r.w).discard()})}const s=e.length;if(s>0){const t=td(e).setGroup(_a),r=Tn(!0).toVar("clipped");Bp(s,({i:e})=>{const s=t.element(e);r.assign(pc.dot(s.xyz).greaterThan(s.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),cn(()=>{const s=td(e).setGroup(_a),i=sd(t.getClipDistance());Bp(r,({i:e})=>{const t=s.element(e),r=pc.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)})})()}}lg.ALPHA_TO_COVERAGE="alphaToCoverage",lg.DEFAULT="default",lg.HARDWARE="hardware";const dg=cn(([e])=>Ao(Ua(1e4,Eo(Ua(17,e.x).add(Ua(.1,e.y)))).mul(La(.1,Vo(Eo(Ua(13,e.y).add(e.x))))))),cg=cn(([e])=>dg(_n(dg(e.xy),e.z))),hg=cn(([e])=>{const t=eu(Go(Wo(e.xyz)),Go(Ho(e.xyz))),r=yn(1).div(yn(.05).mul(t)).toVar("pixScale"),s=_n(bo(No(To(r))),bo(So(To(r)))),i=_n(cg(No(s.x.mul(e.xyz))),cg(No(s.y.mul(e.xyz)))),n=Ao(To(r)),a=La(Ua(n.oneMinus(),i.x),Ua(n,i.y)),o=Jo(n,n.oneMinus()),u=Rn(a.mul(a).div(Ua(2,o).mul(Pa(1,o))),a.sub(Ua(.5,o)).div(Pa(1,o)),Pa(1,Pa(1,a).mul(Pa(1,a)).div(Ua(2,o).mul(Pa(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return mu(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class pg extends Ol{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 r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new s(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const gg=(e=0)=>new pg(e),mg=cn(([e,t])=>Jo(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),fg=cn(([e,t])=>Jo(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),yg=cn(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bg=cn(([e,t])=>gu(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),tu(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xg=cn(([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return Cn(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),Tg=cn(([e])=>Cn(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),_g=cn(([e])=>(gn(e.a.equal(0),()=>Cn(0)),Cn(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class vg extends J{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const r=this[t];r&&!0===r.isNode&&e.push({property:t,childNode:r})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:r}of this._getNodeChildren())e.push(Vs(t.slice(0,-4)),r.getCacheKey());return this.type+ks(e)}build(e){this.setup(e)}setupObserver(e){return new Us(e)}setup(e){e.context.setupNormal=()=>Gu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=this.setupVertex(e),i=Gu(this.vertexNode||s,"VERTEX");let n;e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const i=Cn(s,Gn.a).max(0);n=this.setupOutput(e,i),oa.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&oa.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Cn(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?s=new lg(lg.ALPHA_TO_COVERAGE):e.stack.addToStack(new lg)}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new lg(lg.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?ig(pc.z,Bd,Fd):Jp(pc.z,Bd,Fd))}null!==s&&ag.assign(s).toStack()}setupPositionView(){return sc.mul(lc).xyz}setupModelViewProjection(){return Ld.mul(pc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),fp}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&Ip(t).toStack(),!0===t.isSkinnedMesh&&Cp(t).toStack(),this.displacementMap){const e=Kc("displacementMap","texture"),t=Kc("displacementScale","float"),r=Kc("displacementBias","float");lc.addAssign(Tc.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Ap(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Sp(t).toStack(),null!==this.positionNode&&lc.assign(Gu(this.positionNode,"POSITION","vec3")),lc}setupDiffuseColor(e){const{object:t,geometry:r}=e;null!==this.maskNode&&Tn(this.maskNode).not().discard();let s=this.colorNode?Cn(this.colorNode):Lh;if(!0===this.vertexColors&&r.hasAttribute("color")&&(s=s.mul(gg())),t.instanceColor){s=kn("vec3","vInstanceColor").mul(s)}if(t.isBatchedMesh&&t._colorsTexture){s=kn("vec3","vBatchColor").mul(s)}Gn.assign(s);const i=this.opacityNode?yn(this.opacityNode):Dh;Gn.a.assign(Gn.a.mul(i));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?yn(this.alphaTestNode):Fh,!0===this.alphaToCoverage?(Gn.a=bu(n,n.add(Ko(Gn.a)),Gn.a),Gn.a.lessThanEqual(0).discard()):Gn.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Gn.a.lessThan(hg(lc)).discard(),e.isOpaque()&&Gn.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Rn(0):Gn.rgb}setupNormal(){return this.normalNode?Rn(this.normalNode):Wh}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Kc("envMap","cubeTexture"):Kc("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zp(pp)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);s&&s.isLightingNode&&t.push(s);let i=this.aoNode;null===i&&e.material.aoMap&&(i=gp),e.context.getAO&&(i=e.context.getAO(i,e)),i&&t.push(new Vp(i));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Gp(n,t,r,s)}else null!==r&&(a=Rn(null!==s?gu(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&($n.assign(Rn(i||Uh)),a=a.add($n)),a}setupFog(e,t){const r=e.fogNode;return r&&(oa.assign(t),t=Cn(r.toVar())),t}setupPremultipliedAlpha(e,t){return Tg(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 r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.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 r=J.prototype.toJSON.call(this,e);r.inputNodes={};for(const{property:t,childNode:s}of this._getNodeChildren())r.inputNodes[t]=s.toJSON(e).uuid;function s(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const Ng=new ee;class Sg extends vg{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Ng),this.setValues(e)}}const Rg=new te;class Ag extends vg{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Rg),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?yn(this.offsetNode):dp,t=this.dashScaleNode?yn(this.dashScaleNode):ap,r=this.dashSizeNode?yn(this.dashSizeNode):op,s=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(r),la.assign(s);const i=$u(Vl("lineDistance").mul(t));(e?i.add(e):i).mod(ua.add(la)).greaterThan(ua).discard()}}const Eg=new te;class wg extends vg{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Eg),this.vertexColors=e.vertexColors,this.dashOffset=0,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=re,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.vertexColors,i=this._useDash,n=this._useWorldUnits,a=cn(({start:e,end:t})=>{const r=Ld.element(2).element(2),s=Ld.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return Cn(gu(e.xyz,t.xyz,s),t.w)}).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=cn(()=>{const e=Vl("instanceStart"),t=Vl("instanceEnd"),r=Cn(sc.mul(Cn(e,1))).toVar("start"),s=Cn(sc.mul(Cn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?yn(this.dashScaleNode):ap,t=this.offsetNode?yn(this.offsetNode):dp,r=Vl("instanceDistanceStart"),s=Vl("instanceDistanceEnd");let i=uc.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),kn("float","lineDistance").assign(i)}n&&(kn("vec3","worldStart").assign(r.xyz),kn("vec3","worldEnd").assign(s.xyz));const o=cd.z.div(cd.w),u=Ld.element(2).element(3).equal(-1);gn(u,()=>{gn(r.z.lessThan(0).and(s.z.greaterThan(0)),()=>{s.assign(a({start:r,end:s}))}).ElseIf(s.z.lessThan(0).and(r.z.greaterThanEqual(0)),()=>{r.assign(a({start:s,end:r}))})});const l=Ld.mul(r),d=Ld.mul(s),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const g=Cn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=gu(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=kn("vec4","worldPos");o.assign(uc.y.lessThan(.5).select(r,s));const u=lp.mul(.5);o.addAssign(Cn(uc.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(Cn(uc.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(Cn(a.mul(u),0)),gn(uc.y.greaterThan(1).or(uc.y.lessThan(0)),()=>{o.subAssign(Cn(a.mul(2).mul(u),0))})),g.assign(Ld.mul(o));const l=Rn().toVar();l.assign(uc.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=_n(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(uc.x.lessThan(0).select(e.negate(),e)),gn(uc.y.lessThan(0),()=>{e.assign(e.sub(p))}).ElseIf(uc.y.greaterThan(1),()=>{e.assign(e.add(p))}),e.assign(e.mul(lp)),e.assign(e.div(cd.w.div(od))),g.assign(uc.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(Cn(e,0,0)))}return g})();const o=cn(({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return _n(h,p)});if(this.colorNode=cn(()=>{const e=kl();if(i){const t=this.dashSizeNode?yn(this.dashSizeNode):op,r=this.gapSizeNode?yn(this.gapSizeNode):up;ua.assign(t),la.assign(r);const s=kn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(ua.add(la)).greaterThan(ua).discard()}const a=yn(1).toVar("alpha");if(n){const e=kn("vec3","worldStart"),s=kn("vec3","worldEnd"),n=kn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:Rn(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(lp);if(!i)if(r&&t.currentSamples>0){const e=h.fwidth();a.assign(bu(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.currentSamples>0){const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1)),s=t.mul(t).add(r.mul(r)),i=yn(s.fwidth()).toVar("dlen");gn(e.y.abs().greaterThan(1),()=>{a.assign(bu(i.oneMinus(),i.add(1),s).oneMinus())})}else gn(e.y.abs().greaterThan(1),()=>{const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1));t.mul(t).add(r.mul(r)).greaterThan(1).discard()});let u;if(this.lineColorNode)u=this.lineColorNode;else if(s){const e=Vl("instanceColorStart"),t=Vl("instanceColorEnd");u=uc.y.lessThan(.5).select(e,t).mul(Lh)}else u=Lh;return Cn(u,a)})(),this.transparent){const e=this.opacityNode?yn(this.opacityNode):Dh;this.outputNode=Cn(this.colorNode.rgb.mul(e).add(Xp().rgb.mul(e.oneMinus())),this.colorNode.a)}super.setup(e)}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}copy(e){return super.copy(e),this.vertexColors=e.vertexColors,this.dashOffset=e.dashOffset,this.lineColorNode=e.lineColorNode,this.offsetNode=e.offsetNode,this.dashScaleNode=e.dashScaleNode,this.dashSizeNode=e.dashSizeNode,this.gapSizeNode=e.gapSizeNode,this._useDash=e._useDash,this._useAlphaToCoverage=e._useAlphaToCoverage,this._useWorldUnits=e._useWorldUnits,this}}const Cg=new se;class Mg extends vg{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Cg),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?yn(this.opacityNode):Dh;Gn.assign(Qu(Cn(vh(Sc),e),ie))}}const Bg=cn(([e=hc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return _n(t,r)});class Fg extends ne{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const r={width:e,height:e,depth:1},s=[r,r,r,r,r,r];this.texture=new U(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=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 i=new ae(5,5,5),n=Bg(hc),a=new vg;a.colorNode=Kl(t,n,0),a.side=L,a.blending=re;const o=new oe(i,a),u=new ue;u.add(o),t.minFilter===Y&&(t.minFilter=le);const l=new de(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.generateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,r=!0,s=!0){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,r,s);e.setRenderTarget(i)}}const Lg=new WeakMap;class Pg extends gi{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=$c(null);const t=new U;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ri.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===ce||r===he){if(Lg.has(e)){const t=Lg.get(e);Dg(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Fg(r.height);s.fromEquirectangularTexture(t,e),Dg(s.texture,e.mapping),this._cubeTexture=s.texture,Lg.set(e,s.texture),e.addEventListener("dispose",Ug)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Ug(e){const t=e.target;t.removeEventListener("dispose",Ug);const r=Lg.get(t);void 0!==r&&(Lg.delete(t),r.dispose())}function Dg(e,t){t===ce?e.mapping=D:t===he&&(e.mapping=I)}const Ig=an(Pg).setParameterLength(1);class Og extends Op{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Ig(this.envNode)}}class Vg extends Op{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=yn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class kg{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Gg extends kg{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(Cn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(Cn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(Gn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case me:s.rgb.assign(gu(s.rgb,s.rgb.mul(i.rgb),kh.mul(Gh)));break;case ge:s.rgb.assign(gu(s.rgb,i.rgb,kh.mul(Gh)));break;case pe:s.rgb.addAssign(i.rgb.mul(kh.mul(Gh)));break;default:d("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const zg=new fe;class $g extends vg{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(zg),this.setValues(e)}setupNormal(){return bc(vc)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Vg(pp)),t}setupOutgoingLight(){return Gn.rgb}setupLightingModel(){return new Gg}}const Wg=cn(({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))}),Hg=cn(e=>e.diffuseColor.mul(1/Math.PI)),qg=cn(({dotNH:e})=>aa.mul(yn(.5)).add(1).mul(yn(1/Math.PI)).mul(e.pow(aa))),jg=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(t).clamp(),s=gc.dot(t).clamp(),i=Wg({f0:sa,f90:1,dotVH:s}),n=yn(.25),a=qg({dotNH:r});return i.mul(n).mul(a)});class Xg extends Gg{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:Gn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(jg({lightDirection:e})).mul(kh))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Kg=new ye;class Qg extends vg{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Kg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg(!1)}}const Yg=new be;class Zg extends vg{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Yg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Og(t):null}setupLightingModel(){return new Xg}setupVariants(){const e=(this.shininessNode?yn(this.shininessNode):Ph).max(1e-4);aa.assign(e);const t=this.specularNode||Ih;sa.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Jg=cn(e=>{if(!1===e.geometry.hasAttribute("normal"))return yn(0);const t=vc.dFdx().abs().max(vc.dFdy().abs());return t.x.max(t.y).max(t.z)}),em=cn(e=>{const{roughness:t}=e,r=Jg();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s}),tm=cn(({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return Da(.5,i.add(n).max(ao))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),rm=cn(({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(Rn(e.mul(r),t.mul(s),a).length()),l=a.mul(Rn(e.mul(i),t.mul(n),o).length());return Da(.5,u.add(l).max(ao))}).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"}]}),sm=cn(({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),im=yn(1/Math.PI),nm=cn(({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=Rn(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return im.mul(n.mul(u.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"}]}),am=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Sc,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(gc).normalize(),d=n.dot(e).clamp(),c=n.dot(gc).clamp(),h=n.dot(l).clamp(),p=gc.dot(l).clamp();let g,m,f=Wg({f0:t,f90:r,dotVH:p});if(Zi(a)&&(f=Qn.mix(f,i)),Zi(o)){const t=ta.dot(e),r=ta.dot(gc),s=ta.dot(l),i=ra.dot(e),n=ra.dot(gc),a=ra.dot(l);g=rm({alphaT:Jn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=nm({alphaT:Jn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=tm({alpha:u,dotNL:d,dotNV:c}),m=sm({alpha:u,dotNH:h});return f.mul(g).mul(m)}),om=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 um=null;const lm=cn(({roughness:e,dotNV:t})=>{null===um&&(um=new xe(om,16,16,$,Te),um.name="DFG_LUT",um.minFilter=le,um.magFilter=le,um.wrapS=_e,um.wrapT=_e,um.generateMipmaps=!1,um.needsUpdate=!0);const r=_n(e,t);return Kl(um,r).rg}),dm=cn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=am({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),u=Sc.dot(e).clamp(),l=Sc.dot(gc).clamp(),d=lm({roughness:s,dotNV:l}),c=lm({roughness:s,dotNV:u}),h=t.mul(d.x).add(r.mul(d.y)),p=t.mul(c.x).add(r.mul(c.y)),g=d.x.add(d.y),m=c.x.add(c.y),f=yn(1).sub(g),y=yn(1).sub(m),b=t.add(t.oneMinus().mul(.047619)),x=h.mul(p).mul(b).div(yn(1).sub(f.mul(y).mul(b).mul(b)).add(ao)),T=f.mul(y),_=x.mul(T);return o.add(_)}),cm=cn(e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=lm({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))}),hm=cn(({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(Rn(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),pm=cn(({roughness:e,dotNH:t})=>{const r=e.pow2(),s=yn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return yn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),gm=cn(({dotNV:e,dotNL:t})=>yn(1).div(yn(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),mm=cn(({lightDirection:e})=>{const t=e.add(gc).normalize(),r=Sc.dot(e).clamp(),s=Sc.dot(gc).clamp(),i=Sc.dot(t).clamp(),n=pm({roughness:Kn,dotNH:i}),a=gm({dotNV:s,dotNL:r});return Xn.mul(n).mul(a)}),fm=cn(({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=_n(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),ym=cn(({f:e})=>{const t=e.length();return eu(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),bm=cn(({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,eu(r.mul(r).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"}]}),xm=cn(({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=Rn().toVar();return gn(d.dot(r.sub(i)).greaterThanEqual(0),()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(Pn(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=Rn(0).toVar();f.addAssign(bm({v1:h,v2:p})),f.addAssign(bm({v1:p,v2:g})),f.addAssign(bm({v1:g,v2:m})),f.addAssign(bm({v1:m,v2:h})),c.assign(Rn(ym({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Tm=cn(({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=Rn().toVar();return gn(o.dot(e.sub(t)).greaterThanEqual(0),()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=Rn(0).toVar();d.addAssign(bm({v1:n,v2:a})),d.addAssign(bm({v1:a,v2:o})),d.addAssign(bm({v1:o,v2:l})),d.addAssign(bm({v1:l,v2:n})),u.assign(Rn(ym({f:d.abs()})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),_m=1/6,vm=e=>Ua(_m,Ua(e,Ua(e,e.negate().add(3)).sub(3)).add(1)),Nm=e=>Ua(_m,Ua(e,Ua(e,Ua(3,e).sub(6))).add(4)),Sm=e=>Ua(_m,Ua(e,Ua(e,Ua(-3,e).add(3)).add(3)).add(1)),Rm=e=>Ua(_m,ou(e,3)),Am=e=>vm(e).add(Nm(e)),Em=e=>Sm(e).add(Rm(e)),wm=e=>La(-1,Nm(e).div(vm(e).add(Nm(e)))),Cm=e=>La(1,Rm(e).div(Sm(e).add(Rm(e)))),Mm=(e,t,r)=>{const s=e.uvNode,i=Ua(s,t.zw).add(.5),n=No(i),a=Ao(i),o=Am(a.x),u=Em(a.x),l=wm(a.x),d=Cm(a.x),c=wm(a.y),h=Cm(a.y),p=_n(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=_n(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=_n(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=_n(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Am(a.y).mul(La(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Em(a.y).mul(La(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},Bm=cn(([e,t])=>{const r=_n(e.size(bn(t))),s=_n(e.size(bn(t.add(1)))),i=Da(1,r),n=Da(1,s),a=Mm(e,Cn(i,r),No(t)),o=Mm(e,Cn(n,s),So(t));return Ao(t).mix(a,o)}),Fm=cn(([e,t])=>{const r=t.mul(Wl(e));return Bm(e,r)}),Lm=cn(([e,t,r,s,i])=>{const n=Rn(yu(t.negate(),Ro(e),Da(1,s))),a=Rn(Go(i[0].xyz),Go(i[1].xyz),Go(i[2].xyz));return Ro(n).mul(r.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"}]}),Pm=cn(([e,t])=>e.mul(mu(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Um=qp(),Dm=Xp(),Im=cn(([e,t,r],{material:s})=>{const i=(s.side===L?Um:Dm).sample(e),n=To(ld.x).mul(Pm(t,r));return Bm(i,n)}),Om=cn(([e,t,r])=>(gn(r.notEqual(0),()=>{const s=xo(t).negate().div(r);return yo(s.negate().mul(e))}),Rn(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Vm=cn(([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=Cn().toVar(),f=Rn().toVar();const i=d.sub(1).mul(g.mul(.025)),n=Rn(d.sub(i),d,d.add(i));Bp({start:0,end:3},({i:i})=>{const d=n.element(i),g=Lm(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(Cn(y,1))),x=_n(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(_n(x.x,x.y.oneMinus()));const T=Im(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(Om(Go(g),h,p).element(i)))}),m.a.divAssign(3)}else{const i=Lm(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(Cn(n,1))),y=_n(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(_n(y.x,y.y.oneMinus())),m=Im(y,r,d),f=s.mul(Om(Go(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=Rn(cm({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return Cn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())}),km=Pn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Gm=(e,t)=>e.sub(t).div(e.add(t)).pow2(),zm=cn(({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=gu(e,t,bu(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();gn(a.lessThan(0),()=>Rn(1));const o=a.sqrt(),u=Gm(n,e),l=Wg({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=yn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Rn(1).add(t).div(Rn(1).sub(t))})(i.clamp(0,.9999)),g=Gm(p,n.toVec3()),m=Wg({f0:g,f90:1,dotVH:o}),f=Rn(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=Rn(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(Rn(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Bp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=Rn(54856e-17,44201e-17,52481e-17),i=Rn(1681e3,1795300,2208400),n=Rn(43278e5,93046e5,66121e5),a=yn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=Rn(o.x.add(a),o.y,o.z).div(1.0685e-7),km.mul(o)})(yn(e).mul(y),yn(e).mul(b)).mul(2);v.addAssign(N.mul(t))}),v.max(Rn(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"}]}),$m=cn(({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.mul(r),n=r.add(.1).reciprocal(),a=yn(-1.9362).add(r.mul(1.0678)).add(i.mul(.4573)).sub(n.mul(.8469)),o=yn(-.6014).add(r.mul(.5538)).sub(i.mul(.467)).sub(n.mul(.1255));return a.mul(s).add(o).exp().saturate()}),Wm=Rn(.04),Hm=yn(1);class qm extends kg{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Rn().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Rn().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Rn().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Rn().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Rn().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Sc.dot(gc).clamp(),t=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:sa}),r=zm({outsideIOR:yn(1),eta2:Yn,cosTheta1:e,thinFilmThickness:Zn,baseF0:Gn.rgb});this.iridescenceFresnel=gu(t,r,Hn),this.iridescenceF0Dielectric=hm({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=hm({f:r,f90:1,dotVH:e}),this.iridescenceF0=gu(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Hn)}if(!0===this.transmission){const t=cc,r=Od.sub(cc).normalize(),s=Rc,i=e.context;i.backdrop=Vm(s,r,Wn,zn,ia,na,t,Qd,Ud,Ld,ca,pa,ma,ga,this.dispersion?fa:null),i.backdropAlpha=ha,Gn.a.mulAssign(gu(1,i.backdrop.a,ha))}super.start(e)}computeMultiscattering(e,t,r,s,i=null){const n=Sc.dot(gc).clamp(),a=lm({roughness:Wn,dotNV:n}),o=i?Qn.mix(s,i):s,u=o.mul(a.x).add(r.mul(a.y)),l=a.x.add(a.y).oneMinus(),d=o.add(o.oneMinus().mul(.047619)),c=u.mul(d).div(l.mul(d).oneMinus());e.addAssign(u),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sc.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(s.mul(mm({lightDirection:e})));const t=$m({normal:Sc,viewDir:gc,roughness:Kn}),r=$m({normal:Sc,viewDir:e,roughness:Kn}),i=Xn.r.max(Xn.g).max(Xn.b).mul(t.max(r)).oneMinus();s.mulAssign(i)}if(!0===this.clearcoat){const r=Ac.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(am({lightDirection:e,f0:Wm,f90:Hm,roughness:jn,normalView:Ac})))}r.directDiffuse.addAssign(s.mul(Hg({diffuseColor:zn}))),r.directSpecular.addAssign(s.mul(dm({lightDirection:e,f0:ia,f90:1,roughness:Wn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Sc,h=gc,p=pc.toVar(),g=fm({N:c,V:h,roughness:Wn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=Pn(Rn(m.x,0,m.y),Rn(0,1,0),Rn(m.z,0,m.w)).toVar(),b=ia.mul(f.x).add(na.sub(ia).mul(f.y)).toVar();if(i.directSpecular.addAssign(e.mul(b).mul(xm({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(zn).mul(xm({N:c,V:h,P:p,mInv:Pn(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d}))),!0===this.clearcoat){const t=Ac,r=fm({N:t,V:h,roughness:jn}),s=n.sample(r),i=a.sample(r),c=Pn(Rn(s.x,0,s.y),Rn(0,1,0),Rn(s.z,0,s.w)),g=Wm.mul(i.x).add(Hm.sub(Wm).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(g).mul(xm({N:t,V:h,P:p,mInv:c,p0:o,p1:u,p2:l,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context,s=t.mul(Hg({diffuseColor:zn})).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();s.mulAssign(t)}r.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Xn,$m({normal:Sc,viewDir:gc,roughness:Kn}))),!0===this.clearcoat){const e=Ac.dot(gc).clamp(),t=cm({dotNV:e,specularColor:Wm,specularF90:Hm,roughness:jn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=Rn().toVar("singleScatteringDielectric"),n=Rn().toVar("multiScatteringDielectric"),a=Rn().toVar("singleScatteringMetallic"),o=Rn().toVar("multiScatteringMetallic");this.computeMultiscattering(i,n,na,sa,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,na,Gn.rgb,this.iridescenceF0Metallic);const u=gu(i,a,Hn),l=gu(n,o,Hn),d=i.add(n),c=zn.mul(d.oneMinus()),h=r.mul(1/Math.PI),p=t.mul(u).add(l.mul(h)).toVar(),g=c.mul(h).toVar();if(!0===this.sheen){const e=$m({normal:Sc,viewDir:gc,roughness:Kn}),t=Xn.r.max(Xn.g).max(Xn.b).mul(e).oneMinus();p.mulAssign(t),g.mulAssign(t)}s.indirectSpecular.addAssign(p),s.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Sc.dot(gc).clamp().add(t),i=Wn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ac.dot(gc).clamp(),r=Wg({dotVH:e,f0:Wm,f90:Hm}),s=t.mul(qn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(qn));t.assign(s)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const jm=yn(1),Xm=yn(-2),Km=yn(.8),Qm=yn(-1),Ym=yn(.4),Zm=yn(2),Jm=yn(.305),ef=yn(3),tf=yn(.21),rf=yn(4),sf=yn(4),nf=yn(16),af=cn(([e])=>{const t=Rn(Vo(e)).toVar(),r=yn(-1).toVar();return gn(t.x.greaterThan(t.z),()=>{gn(t.x.greaterThan(t.y),()=>{r.assign(Eu(e.x.greaterThan(0),0,3))}).Else(()=>{r.assign(Eu(e.y.greaterThan(0),1,4))})}).Else(()=>{gn(t.z.greaterThan(t.y),()=>{r.assign(Eu(e.z.greaterThan(0),2,5))}).Else(()=>{r.assign(Eu(e.y.greaterThan(0),1,4))})}),r}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),of=cn(([e,t])=>{const r=_n().toVar();return gn(t.equal(0),()=>{r.assign(_n(e.z,e.y).div(Vo(e.x)))}).ElseIf(t.equal(1),()=>{r.assign(_n(e.x.negate(),e.z.negate()).div(Vo(e.y)))}).ElseIf(t.equal(2),()=>{r.assign(_n(e.x.negate(),e.y).div(Vo(e.z)))}).ElseIf(t.equal(3),()=>{r.assign(_n(e.z.negate(),e.y).div(Vo(e.x)))}).ElseIf(t.equal(4),()=>{r.assign(_n(e.x.negate(),e.z).div(Vo(e.y)))}).Else(()=>{r.assign(_n(e.x,e.y).div(Vo(e.z)))}),Ua(.5,r.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),uf=cn(([e])=>{const t=yn(0).toVar();return gn(e.greaterThanEqual(Km),()=>{t.assign(jm.sub(e).mul(Qm.sub(Xm)).div(jm.sub(Km)).add(Xm))}).ElseIf(e.greaterThanEqual(Ym),()=>{t.assign(Km.sub(e).mul(Zm.sub(Qm)).div(Km.sub(Ym)).add(Qm))}).ElseIf(e.greaterThanEqual(Jm),()=>{t.assign(Ym.sub(e).mul(ef.sub(Zm)).div(Ym.sub(Jm)).add(Zm))}).ElseIf(e.greaterThanEqual(tf),()=>{t.assign(Jm.sub(e).mul(rf.sub(ef)).div(Jm.sub(tf)).add(ef))}).Else(()=>{t.assign(yn(-2).mul(To(Ua(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),lf=cn(([e,t])=>{const r=e.toVar();r.assign(Ua(2,r).sub(1));const s=Rn(r,1).toVar();return gn(t.equal(0),()=>{s.assign(s.zyx)}).ElseIf(t.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),df=cn(([e,t,r,s,i,n])=>{const a=yn(r),o=Rn(t),u=mu(uf(a),Xm,n),l=Ao(u),d=No(u),c=Rn(cf(e,o,d,s,i,n)).toVar();return gn(l.notEqual(0),()=>{const t=Rn(cf(e,o,d.add(1),s,i,n)).toVar();c.assign(gu(c,t,l))}),c}),cf=cn(([e,t,r,s,i,n])=>{const a=yn(r).toVar(),o=Rn(t),u=yn(af(o)).toVar(),l=yn(eu(sf.sub(a),0)).toVar();a.assign(eu(a,sf));const d=yn(bo(a)).toVar(),c=_n(of(o,u).mul(d.sub(2)).add(1)).toVar();return gn(u.greaterThan(2),()=>{c.y.addAssign(d),u.subAssign(3)}),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(Ua(3,nf))),c.y.addAssign(Ua(4,bo(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(_n(),_n())}),hf=cn(({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Co(s),l=r.mul(u).add(i.cross(r).mul(Eo(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return cf(e,l,t,n,a,o)}),pf=cn(({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=Rn(Eu(t,r,au(r,s))).toVar();gn(h.equal(Rn(0)),()=>{h.assign(Rn(s.z,0,s.x.negate()))}),h.assign(Ro(h));const p=Rn().toVar();return p.addAssign(i.element(0).mul(hf({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Bp({start:bn(1),end:e},({i:e})=>{gn(e.greaterThanEqual(n),()=>{Fp()});const t=yn(a.mul(yn(e))).toVar();p.addAssign(i.element(e).mul(hf({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(hf({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))}),Cn(p,1)}),gf=cn(([e])=>{const t=xn(e).toVar();return t.assign(t.shiftLeft(xn(16)).bitOr(t.shiftRight(xn(16)))),t.assign(t.bitAnd(xn(1431655765)).shiftLeft(xn(1)).bitOr(t.bitAnd(xn(2863311530)).shiftRight(xn(1)))),t.assign(t.bitAnd(xn(858993459)).shiftLeft(xn(2)).bitOr(t.bitAnd(xn(3435973836)).shiftRight(xn(2)))),t.assign(t.bitAnd(xn(252645135)).shiftLeft(xn(4)).bitOr(t.bitAnd(xn(4042322160)).shiftRight(xn(4)))),t.assign(t.bitAnd(xn(16711935)).shiftLeft(xn(8)).bitOr(t.bitAnd(xn(4278255360)).shiftRight(xn(8)))),yn(t).mul(2.3283064365386963e-10)}),mf=cn(([e,t])=>_n(yn(e).div(yn(t)),gf(e))),ff=cn(([e,t,r])=>{const s=r.mul(r).toConst(),i=Rn(1,0,0).toConst(),n=au(t,i).toConst(),a=_o(e.x).toConst(),o=Ua(2,3.14159265359).mul(e.y).toConst(),u=a.mul(Co(o)).toConst(),l=a.mul(Eo(o)).toVar(),d=Ua(.5,t.z.add(1)).toConst();l.assign(d.oneMinus().mul(_o(u.mul(u).oneMinus())).add(d.mul(l)));const c=i.mul(u).add(n.mul(l)).add(t.mul(_o(eu(0,u.mul(u).add(l.mul(l)).oneMinus()))));return Ro(Rn(s.mul(c.x),s.mul(c.y),eu(0,c.z)))}),yf=cn(({roughness:e,mipInt:t,envMap:r,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Rn(s).toVar(),l=Rn(0).toVar(),d=yn(0).toVar();return gn(e.lessThan(.001),()=>{l.assign(cf(r,u,t,n,a,o))}).Else(()=>{const s=Eu(Vo(u.z).lessThan(.999),Rn(0,0,1),Rn(1,0,0)),c=Ro(au(s,u)).toVar(),h=au(u,c).toVar();Bp({start:xn(0),end:i},({i:s})=>{const p=mf(s,i),g=ff(p,Rn(0,0,1),e),m=Ro(c.mul(g.x).add(h.mul(g.y)).add(u.mul(g.z))),f=Ro(m.mul(nu(u,m).mul(2)).sub(u)),y=eu(nu(u,f),0);gn(y.greaterThan(0),()=>{const e=cf(r,f,t,n,a,o);l.addAssign(e.mul(y)),d.addAssign(y)})}),gn(d.greaterThan(0),()=>{l.assign(l.div(d))})}),Cn(l,1)}),bf=[.125,.215,.35,.446,.526,.582],xf=20,Tf=new Ne(-1,1,1,-1,0,1),_f=new Se(90,1),vf=new e;let Nf=null,Sf=0,Rf=0;const Af=new r,Ef=new WeakMap,wf=[3,1,5,0,4,2],Cf=lf(kl(),Vl("faceIndex")).normalize(),Mf=Rn(Cf.x,Cf.y,Cf.z);class Bf{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Af,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){d('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}Nf=this._renderer.getRenderTarget(),Sf=this._renderer.getActiveCubeFace(),Rf=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget();return u.depthBuffer=!0,this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return v('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){d('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return v('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){d("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return v('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Uf(),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===D||e.mapping===I?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;ee-4?o=bf[a-e+4-1]:0===a&&(o=0),r.push(o);const u=1/(n-2),l=-u,d=1+u,c=[l,l,d,l,d,d,l,l,d,d,l,d],h=6,p=6,g=3,m=2,f=1,y=new Float32Array(g*p*h),b=new Float32Array(m*p*h),x=new Float32Array(f*p*h);for(let e=0;e2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=wf[e];y.set(s,g*p*i),b.set(c,m*p*i);const n=[i,i,i,i,i,i];x.set(n,f*p*i)}const T=new ve;T.setAttribute("position",new we(y,g)),T.setAttribute("uv",new we(b,m)),T.setAttribute("faceIndex",new we(x,f)),s.push(new oe(T,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t,sigmas:r}}(t)),this._blurMaterial=function(e,t,s){const i=td(new Array(xf).fill(0)),n=Sa(new r(0,1,0)),a=Sa(0),o=yn(xf),u=Sa(0),l=Sa(1),d=Kl(),c=Sa(0),h=yn(1/t),p=yn(1/s),g=yn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:Mf,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Lf("blur");return f.fragmentNode=pf({...m,latitudinal:u.equal(1)}),Ef.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,r){const s=Kl(),i=Sa(0),n=Sa(0),a=yn(1/t),o=yn(1/r),u=yn(e),l={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:u},d=Lf("ggx");return d.fragmentNode=yf({...l,N_immutable:Mf,GGX_SAMPLES:xn(512)}),Ef.set(d,l),d}(t,e.width,e.height)}}async _compileMaterial(e){const t=new oe(new ve,e);await this._renderer.compile(t,Tf)}_sceneToCubeUV(e,t,r,s,i){const n=_f;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(vf),u.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new oe(new ae,new fe({name:"PMREM.Background",side:L,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,c=d.material;let h=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,h=!0):(c.color.copy(vf),h=!0),u.setRenderTarget(s),u.clear(),h&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;this._setViewport(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=p}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===D||e.mapping===I;s?null===this._cubemapMaterial&&(this._cubemapMaterial=Pf(e)):null===this._equirectMaterial&&(this._equirectMaterial=Uf(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,Tf)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let t=1;tc-4?r-c+4:0),g=4*(this._cubeSize-h);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=d,o.mipInt.value=c-t,this._setViewport(i,p,g,3*h,2*h),s.setRenderTarget(i),s.render(a,Tf),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=c-r,this._setViewport(e,p,g,3*h,2*h),s.setRenderTarget(e),s.render(a,Tf)}_blur(e,t,r,s,i){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,r,s,"latitudinal",i),this._halfBlur(n,e,r,r,s,"longitudinal",i)}_halfBlur(e,t,r,s,i,n,a){const u=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&o("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[s];c.material=l;const h=Ef.get(l),p=this._sizeLods[r]-1,g=isFinite(i)?Math.PI/(2*p):2*Math.PI/39,m=i/g,f=isFinite(i)?1+Math.floor(3*m):xf;f>xf&&d(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const y=[];let b=0;for(let e=0;ex-4?s-x+4:0),v=4*(this._cubeSize-T);this._setViewport(t,_,v,3*T,2*T),u.setRenderTarget(t),u.render(c,Tf)}_setViewport(e,t,r,s,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-r,s,i),e.scissor.set(t,e.height-i-r,s,i)):(e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i))}}function Ff(e,t){const r=new ne(e,t,{magFilter:le,minFilter:le,generateMipmaps:!1,type:Te,format:Ae,colorSpace:Re});return r.texture.mapping=Ee,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Lf(e){const t=new vg;return t.depthTest=!1,t.depthWrite=!1,t.blending=re,t.name=`PMREM_${e}`,t}function Pf(e){const t=Lf("cubemap");return t.fragmentNode=$c(e,Mf),t}function Uf(e){const t=Lf("equirect");return t.fragmentNode=Kl(e,Bg(Mf),0),t}const Df=new WeakMap;function If(e,t,r){const s=function(e){let t=Df.get(e);void 0===t&&(t=new WeakMap,Df.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s0}(t))return null;i=r.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,s.set(e,i)}return i.texture}class Of extends gi{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new N;s.isRenderTargetTexture=!0,this._texture=Kl(s),this._width=Sa(0),this._height=Sa(0),this._maxMip=Sa(0),this.updateBeforeType=ri.RENDER}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,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,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 r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture?s:If(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Bf(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Uc.mul(Rn(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),df(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Vf=an(Of).setParameterLength(1,3),kf=new WeakMap;class Gf extends Op{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const s=r.isTextureNode?r.value:t[r.property],i=this._getPMREMNodeCache(e.renderer);let n=i.get(s);void 0===n&&(n=Vf(s),i.set(s,n)),r=n}const s=!0===t.useAnisotropy||t.anisotropy>0?_h:Sc,i=r.context(zf(Wn,s)).mul(Pc),n=r.context($f(Rc)).mul(Math.PI).mul(Pc),a=vl(i),o=vl(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(zf(jn,Ac)).mul(Pc),t=vl(e);u.addAssign(t)}}_getPMREMNodeCache(e){let t=kf.get(e);return void 0===t&&(t=new WeakMap,kf.set(e,t)),t}}const zf=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=gc.negate().reflect(t),r=du(e).mix(r,t).normalize(),r=r.transformDirection(Ud)),r),getTextureLevel:()=>e}},$f=e=>({getUV:()=>e,getTextureLevel:()=>yn(1)}),Wf=new Ce;class Hf extends vg{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(Wf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Gf(t):null}setupLightingModel(){return new qm}setupSpecular(){const e=gu(Rn(.04),Gn.rgb,Hn);sa.assign(Rn(.04)),ia.assign(e),na.assign(1)}setupVariants(){const e=this.metalnessNode?yn(this.metalnessNode):$h;Hn.assign(e);let t=this.roughnessNode?yn(this.roughnessNode):zh;t=em({roughness:t}),Wn.assign(t),this.setupSpecular(),zn.assign(Gn.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const qf=new Me;class jf extends Hf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(qf),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?yn(this.iorNode):sp;ca.assign(e),sa.assign(Jo(uu(ca.sub(1).div(ca.add(1))).mul(Vh),Rn(1)).mul(Oh)),ia.assign(gu(sa,Gn.rgb,Hn)),na.assign(gu(Oh,1,Hn))}setupLightingModel(){return new qm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?yn(this.clearcoatNode):Hh,t=this.clearcoatRoughnessNode?yn(this.clearcoatRoughnessNode):qh;qn.assign(e),jn.assign(em({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Rn(this.sheenNode):Kh,t=this.sheenRoughnessNode?yn(this.sheenRoughnessNode):Qh;Xn.assign(e),Kn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?yn(this.iridescenceNode):Zh,t=this.iridescenceIORNode?yn(this.iridescenceIORNode):Jh,r=this.iridescenceThicknessNode?yn(this.iridescenceThicknessNode):ep;Qn.assign(e),Yn.assign(t),Zn.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?_n(this.anisotropyNode):Yh).toVar();ea.assign(e.length()),gn(ea.equal(0),()=>{e.assign(_n(1,0))}).Else(()=>{e.divAssign(_n(ea)),ea.assign(ea.saturate())}),Jn.assign(ea.pow2().mix(Wn.pow2(),1)),ta.assign(xh[0].mul(e.x).add(xh[1].mul(e.y))),ra.assign(xh[1].mul(e.x).sub(xh[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?yn(this.transmissionNode):tp,t=this.thicknessNode?yn(this.thicknessNode):rp,r=this.attenuationDistanceNode?yn(this.attenuationDistanceNode):ip,s=this.attenuationColorNode?Rn(this.attenuationColorNode):np;if(ha.assign(e),pa.assign(t),ga.assign(r),ma.assign(s),this.useDispersion){const e=this.dispersionNode?yn(this.dispersionNode):hp;fa.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Rn(this.clearcoatNormalNode):jh}setup(e){e.context.setupClearcoatNormal=()=>Gu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}class Xf extends qm{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Sc.mul(a)).normalize(),h=yn(gc.dot(c.negate()).saturate().pow(l).mul(d)),p=Rn(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Kf extends jf{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=yn(.1),this.thicknessAmbientNode=yn(0),this.thicknessAttenuationNode=yn(.1),this.thicknessPowerNode=yn(2),this.thicknessScaleNode=yn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Xf(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}copy(e){return this.thicknessColorNode=e.thicknessColorNode,this.thicknessDistortionNode=e.thicknessDistortionNode,this.thicknessAmbientNode=e.thicknessAmbientNode,this.thicknessAttenuationNode=e.thicknessAttenuationNode,this.thicknessPowerNode=e.thicknessPowerNode,this.thicknessScaleNode=e.thicknessScaleNode,super.copy(e)}}const Qf=cn(({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=_n(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Kc("gradientMap","texture").context({getUV:()=>i});return Rn(e.r)}{const e=i.fwidth().mul(.5);return gu(Rn(.7),Rn(1),bu(yn(.7).sub(e.x),yn(.7).add(e.x),i.x))}});class Yf extends kg{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Qf({normal:xc,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Hg({diffuseColor:Gn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Hg({diffuseColor:Gn}))),s.indirectDiffuse.mulAssign(t)}}const Zf=new Be;class Jf extends vg{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Zf),this.setValues(e)}setupLightingModel(){return new Yf}}const ey=cn(()=>{const e=Rn(gc.z,0,gc.x.negate()).normalize(),t=gc.cross(e);return _n(e.dot(Sc),t.dot(Sc)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),ty=new Fe;class ry extends vg{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupVariants(e){const t=ey;let r;r=e.material.matcap?Kc("matcap","texture").context({getUV:()=>t}):Rn(gu(.2,.8,t.y)),Gn.rgb.mulAssign(r.rgb)}}class sy extends gi{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return Ln(e,s,s.negate(),e).mul(r)}{const e=t,s=Un(Cn(1,0,0,0),Cn(0,Co(e.x),Eo(e.x).negate(),0),Cn(0,Eo(e.x),Co(e.x),0),Cn(0,0,0,1)),i=Un(Cn(Co(e.y),0,Eo(e.y),0),Cn(0,1,0,0),Cn(Eo(e.y).negate(),0,Co(e.y),0),Cn(0,0,0,1)),n=Un(Cn(Co(e.z),Eo(e.z).negate(),0,0),Cn(Eo(e.z),Co(e.z),0,0),Cn(0,0,1,0),Cn(0,0,0,1));return s.mul(i).mul(n).mul(Cn(r,1)).xyz}}}const iy=an(sy).setParameterLength(2),ny=new Le;class ay extends vg{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ny),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=sc.mul(Rn(s||0));let u=_n(Qd[0].xyz.length(),Qd[1].xyz.length());null!==n&&(u=u.mul(_n(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=uc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>new Zu(e,t,r))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=yn(i||Xh),c=iy(l,d);return Cn(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const oy=new Pe,uy=new t;class ly extends ay{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(oy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return sc.mul(Rn(e||lc)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?_n(n):cp;u=u.mul(od),r.isPerspectiveCamera&&!0===a&&(u=u.mul(dy.div(pc.z.negate()))),i&&i.isNode&&(u=u.mul(_n(i)));let l=uc.xy;if(s&&s.isNode){const e=yn(s);l=iy(l,e)}return l=l.mul(u),l=l.div(hd.div(2)),l=l.mul(o.w),o=o.add(Cn(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const dy=Sa(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(uy);this.value=.5*t.y});class cy extends kg{constructor(){super(),this.shadowNode=yn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Gn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Gn.rgb)}}const hy=new Ue;class py extends vg{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(hy),this.setValues(e)}setupLightingModel(){return new cy}}const gy=Vn("vec3"),my=Vn("vec3"),fy=Vn("vec3");class yy extends kg{constructor(){super()}start(e){const{material:t}=e,r=Vn("vec3"),s=Vn("vec3");gn(Od.sub(cc).length().greaterThan(ec.mul(2)),()=>{r.assign(Od),s.assign(cc)}).Else(()=>{r.assign(cc),s.assign(Od)});const i=s.sub(r),n=Sa("int").onRenderUpdate(({material:e})=>e.steps),a=i.length().div(n).toVar(),o=i.normalize().toVar(),u=yn(0).toVar(),l=Rn(1).toVar();t.offsetNode&&u.addAssign(t.offsetNode.mul(a)),Bp(n,()=>{const s=r.add(o.mul(u)),i=Ud.mul(Cn(s,1)).xyz;let n;null!==t.depthNode&&(my.assign(og(tg(i.z,Bd,Fd))),e.context.sceneDepthNode=og(t.depthNode).toVar()),e.context.positionWorld=s,e.context.shadowPositionWorld=s,e.context.positionView=i,gy.assign(0),t.scatteringNode&&(n=t.scatteringNode({positionRay:s})),super.start(e),n&&gy.mulAssign(n);const d=gy.mul(.01).negate().mul(a).exp();l.mulAssign(d),u.addAssign(a)}),fy.addAssign(l.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?gn(r.greaterThanEqual(my),()=>{gy.addAssign(e)}):gy.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(void 0===e.light.distance)return;const s=t.xyz.toVar();s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul(Tm({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(fy)}}class by extends vg{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=L,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new yy}}class xy{constructor(e,t,r){this.renderer=e,this.nodes=t,this.info=r,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,r),this.renderer._inspector.finish()};e()}stop(){null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Ty{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let r=this.weakMaps[t];return void 0===r&&(r=new WeakMap,this.weakMaps[t]=r),r}get(e){let t=this._getWeakMap(e);for(let r=0;r{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),i[n.name]=e.id),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e1||Array.isArray(e.morphTargetInfluences))&&(s+=e.uuid+","),s+=this.context.id+",",s+=e.receiveShadow+",",Vs(s)}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 r=this.geometry.getAttribute(t);if(void 0===r||e[t]!==r.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Gs(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Gs(e,1)),e=Gs(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Ny=[];class Sy{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);Ny[0]=e,Ny[1]=t,Ny[2]=n,Ny[3]=i;let l=u.get(Ny);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Ny,l)):(l.camera=s,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Ny[0]=null,Ny[1]=null,Ny[2]=null,Ny[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Ty)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new vy(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.deleteForRender(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Ry{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 Ay=1,Ey=2,wy=3,Cy=4,My=16;class By extends Ry{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 r=this.get(e);if(void 0===r.version)t===Ay?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ey?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===wy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Cy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version=65535?De:Ie)(t,1);return i.version=Fy(e),i.__id=Ly(e),i}class Uy extends Ry{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 r=()=>{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,wy):this.updateAttribute(e,Ay);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,Ey);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,Cy)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=Py(t),e.set(t,r)):r.version===Fy(t)&&r.__id===Ly(t)||(this.attributes.delete(r),r=Py(t),e.set(t,r)),s=r}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Dy{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,r){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=r*(t/3):e.isPoints?this.render.points+=r*t:e.isLineSegments?this.render.lines+=r*(t/2):e.isLine?this.render.lines+=r*(t-1):o("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const r=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:r,type:t}),this.memory[t]++,this.memory.total+=r,this.memory[t+"Size"]+=r}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Oe||e.type===Ve?t=1:e.type===ke||e.type===Ge||e.type===Te?t=2:e.type!==R&&e.type!==S&&e.type!==K||(t=4);let r=4;e.format===ze||e.format===$e||e.format===We||e.format===He||e.format===qe?r=1:e.format===$||e.format===je?r=2:e.format!==Xe&&e.format!==Ke||(r=3);let s=t*r;e.type===Qe||e.type===Ye?s=2:e.type!==Ze&&e.type!==Je&&e.type!==et||(s=4);const i=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=i*n*a*s;const u=e.mipmaps;if(u&&u.length>0){let e=0;for(let t=0;t>t))*(r.height||Math.max(1,n>>t))*a*s}}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 Iy{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Oy extends Iy{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Vy extends Iy{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let ky=0;class Gy{constructor(e,t,r,s=null,i=null){this.id=ky++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class zy extends Ry{constructor(e,t,r){super(),this.backend=e,this.nodes=t,this.info=r,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new Gy(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new Gy(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o),this.info.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new Gy(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u),this.info.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const r=this.backend.get(t);return void 0!==r.pipeline&&null!==r.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,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new Vy(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new Oy(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].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 $y extends Ry{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?Cy:wy;this.attributes.update(e,r)}}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,i=e.isIndirectStorageBufferAttribute?Cy:wy,n=r.get(t);this.attributes.update(e,i),n.attribute!==e&&(n.attribute=e,s=!0)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),u=t.texture,l=this.textures.get(u);o&&(this.textures.updateTexture(u),t.generation!==l.generation&&(t.generation=l.generation,s=!0),l.bindGroups.add(e));if(void 0!==r.get(u).externalTexture||l.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===u.isStorageTexture&&!0===u.mipmapsAutoUpdate){const e=this.get(u);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(u)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(u),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,s=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function Wy(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 Hy(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 qy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===P&&!1===e.forceSinglePass}class jy{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,r),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(qy(r)&&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||Wy),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Hy),this.transparent.length>1&&this.transparent.sort(t||Hy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&d&&(l=new Z,l.format=e.stencilBuffer?qe:He,l.type=e.stencilBuffer?Ze:S,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=l),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=l.isArrayTexture?l.image.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const h={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener("dispose",r.onDispose))}updateTexture(e,t={}){const r=this.get(e);if(!0===r.initialized&&r.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(s&&!0===r.initialized&&i.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:Ve}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;"requestPaint"in t&&(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image))}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),r.generation=e.version;else if(e.version>0){const s=e.image;if(void 0===s)d("Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)d("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version;!0!==r.initialized&&(r.initialized=!0,r.generation=e.version,r.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===p.enabled&&p.getTransfer(e.colorSpace)!==g&&d("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),r.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",r.onDispose)),r.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=eb){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),e.isHTMLTexture?(t.width=r.offsetWidth||1,t.height=r.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),r=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e=2)for(let r=0;r{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===s)t.build(e);else if("analyze"===s)t.build(e,this);else if("generate"===s){const r=e.getDataFromNode(t,"any").stages,s=r&&r[e.shaderStage];if(t.isVarNode&&s&&1===s.length&&s[0]&&s[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)i(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)i(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),hn(r),e.removeActiveStack(this),o}}const nb=an(ib).setParameterLength(0,1);class ab extends ci{static get type(){return"StructTypeNode"}constructor(e,t=null){var r;super("struct"),this.membersLayout=(r=e,Object.entries(r).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,r=0;for(const s of this.membersLayout){const i=s.type,n=js(i),a=Xs(i)/e;t=Math.max(t,a);const o=r%t%a;0!==o&&(r+=a-o),r+=n}return Math.ceil(r/t)*t}getMemberType(e,t){const r=this.membersLayout.find(e=>e.name===t);return r?r.type:"void"}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class ob extends ci{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){const e=super._getChildren(),t=e.find(e=>e.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class ub extends ci{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}generateNodeType(){return"OutputType"}generate(e){const t=e.getDataFromNode(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;tnew fb(e,"uint","float"),xb={};class Tb extends no{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,r){"int"===r?t.assign(yb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return xn;case"int":return bn;case"uvec2":return Nn;case"uvec3":return En;case"uvec4":return Bn;case"ivec2":return vn;case"ivec3":return An;case"ivec4":return Mn}}_createTrailingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t);const i=yn(s.bitAnd(zo(s))),n=bb(i).shiftRight(23).sub(127);return r(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{gn(e.equal(xn(0)),()=>xn(32));const s=xn(0),i=xn(0);return this._resolveElementType(e,s,t),gn(s.shiftRight(16).equal(0),()=>{i.addAssign(16),s.shiftLeftAssign(16)}),gn(s.shiftRight(24).equal(0),()=>{i.addAssign(8),s.shiftLeftAssign(8)}),gn(s.shiftRight(28).equal(0),()=>{i.addAssign(4),s.shiftLeftAssign(4)}),gn(s.shiftRight(30).equal(0),()=>{i.addAssign(2),s.shiftLeftAssign(2)}),gn(s.shiftRight(31).equal(0),()=>{i.addAssign(1)}),r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const r=this._returnDataNode(t);return cn(([e])=>{const s=xn(0);this._resolveElementType(e,s,t),s.assign(s.sub(s.shiftRight(xn(1)).bitAnd(xn(1431655765)))),s.assign(s.bitAnd(xn(858993459)).add(s.shiftRight(xn(2)).bitAnd(xn(858993459))));const i=s.add(s.shiftRight(xn(4))).bitAnd(xn(252645135)).mul(xn(16843009)).shiftRight(xn(24));return r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,r,s){const i=this._returnDataNode(t);return cn(([e])=>{if(1===r)return i(s(e));{const t=i(0),n=["x","y","z","w"];for(let i=0;id(r))()}}Tb.COUNT_TRAILING_ZEROS="countTrailingZeros",Tb.COUNT_LEADING_ZEROS="countLeadingZeros",Tb.COUNT_ONE_BITS="countOneBits";const _b=un(Tb,Tb.COUNT_TRAILING_ZEROS).setParameterLength(1),vb=un(Tb,Tb.COUNT_LEADING_ZEROS).setParameterLength(1),Nb=un(Tb,Tb.COUNT_ONE_BITS).setParameterLength(1),Sb=cn(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)}),Rb=(e,t)=>ou(Ua(4,e.mul(Pa(1,e))),t);class Ab extends gi{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}generateNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const Eb=un(Ab,"snorm").setParameterLength(1),wb=un(Ab,"unorm").setParameterLength(1),Cb=un(Ab,"float16").setParameterLength(1);class Mb extends gi{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}generateNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const Bb=un(Mb,"snorm").setParameterLength(1),Fb=un(Mb,"unorm").setParameterLength(1),Lb=un(Mb,"float16").setParameterLength(1),Pb=cn(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Ub=cn(([e])=>Rn(Pb(e.z.add(Pb(e.y.mul(1)))),Pb(e.z.add(Pb(e.x.mul(1)))),Pb(e.y.add(Pb(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Db=cn(([e,t,r])=>{const s=Rn(e).toVar(),i=yn(1.4).toVar(),n=yn(0).toVar(),a=Rn(s).toVar();return Bp({start:yn(0),end:yn(3),type:"float",condition:"<="},()=>{const e=Rn(Ub(a.mul(2))).toVar();s.addAssign(e.add(r.mul(yn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=yn(Pb(s.z.add(Pb(s.x.add(Pb(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class Ib extends ci{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let r=this._candidateFn;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;ri&&(s=r,i=n)}}this._candidateFn=r=s}return r}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const Ob=an(Ib),Vb=e=>(...t)=>Ob(e,...t),kb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.time),Gb=Sa(0).setGroup(_a).onRenderUpdate(e=>e.deltaTime),zb=Sa(0,"uint").setGroup(_a).onRenderUpdate(e=>e.frameId);const $b=cn(([e,t,r=_n(.5)])=>iy(e.sub(r),t).add(r)),Wb=cn(([e,t,r=_n(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))}),Hb=cn(({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=Qd.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=Qd;const i=Ud.mul(s);return Zi(t)&&(i[0][0]=Qd[0].length(),i[0][1]=0,i[0][2]=0),Zi(r)&&(i[1][0]=0,i[1][1]=Qd[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,Ld.mul(i).mul(lc)}),qb=cn(([e=null])=>{const t=og();return og(Yp(e)).sub(t).lessThan(0).select(ud,e)}),jb=cn(([e,t=kl(),r=yn(0)])=>{const s=e.x,i=e.y,n=r.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=e.reciprocal(),l=_n(a,o);return t.add(l).mul(u)}),Xb=cn(([e,t=null,r=null,s=yn(1),i=lc,n=Tc])=>{let a=n.abs().normalize();a=a.div(a.dot(Rn(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=Kl(d,o).mul(a.x),g=Kl(c,u).mul(a.y),m=Kl(h,l).mul(a.z);return La(p,g,m)}),Kb=new ut,Qb=new r,Yb=new r,Zb=new r,Jb=new a,ex=new r(0,0,-1),tx=new s,rx=new r,sx=new r,ix=new s,nx=new t,ax=new ne,ox=ud.flipX();ax.depthTexture=new Z(1,1);let ux=!1;class lx extends jl{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||ax.texture,ox),this._reflectorBaseNode=e.reflector||new dx(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new lx({defaultTexture:ax.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class dx extends ci{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new at,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(v('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?ri.RENDER:ri.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(nx),e.setSize(Math.round(nx.width*r),Math.round(nx.height*r))}setup(e){return this._updateResolution(ax,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new ne(0,0,{type:Te,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=ot,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Z),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&ux)return!1;ux=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(nx),this._updateResolution(o,s),Yb.setFromMatrixPosition(n.matrixWorld),Zb.setFromMatrixPosition(r.matrixWorld),Jb.extractRotation(n.matrixWorld),Qb.set(0,0,1),Qb.applyMatrix4(Jb),rx.subVectors(Yb,Zb);let u=!1;if(!0===rx.dot(Qb)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(ux=!1);u=!0}rx.reflect(Qb).negate(),rx.add(Yb),Jb.extractRotation(r.matrixWorld),ex.set(0,0,-1),ex.applyMatrix4(Jb),ex.add(Zb),sx.subVectors(Yb,ex),sx.reflect(Qb).negate(),sx.add(Yb),a.coordinateSystem=r.coordinateSystem,a.position.copy(rx),a.up.set(0,1,0),a.up.applyMatrix4(Jb),a.up.reflect(Qb),a.lookAt(sx),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Kb.setFromNormalAndCoplanarPoint(Qb,Yb),Kb.applyMatrix4(a.matrixWorldInverse),tx.set(Kb.normal.x,Kb.normal.y,Kb.normal.z,Kb.constant);const l=a.projectionMatrix;ix.x=(Math.sign(tx.x)+l.elements[8])/l.elements[0],ix.y=(Math.sign(tx.y)+l.elements[9])/l.elements[5],ix.z=-1,ix.w=(1+l.elements[10])/l.elements[14],tx.multiplyScalar(1/tx.dot(ix));l.elements[2]=tx.x,l.elements[6]=tx.y,l.elements[10]=s.coordinateSystem===h?tx.z-0:tx.z+1-0,l.elements[14]=tx.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const d=s.getRenderTarget(),c=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0;const g=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),t.name=g,s.setMRT(c),s.setRenderTarget(d),s.autoClear=p,i.visible=!0,ux=!1,this.forceUpdate=!1}get resolution(){return v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const cx=new Ne(-1,1,1,-1,0,1);class hx extends ve{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lt(t,2))}}const px=new hx;class gx extends oe{constructor(e=null){super(px,e),this.camera=cx,this.isQuadMesh=!0}async renderAsync(e){v('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,cx)}render(e){e.render(this,cx)}}const mx=new t;class fx extends jl{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:Te}){const i=new ne(t,r,s);super(i.texture,kl()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.pixelRatio=1,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new gx(new vg),this.updateBeforeType=ri.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const r=e*this.pixelRatio,s=t*this.pixelRatio;this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),r=e.getSize(mx),s=Math.floor(r.width*t),i=Math.floor(r.height*t);s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const r=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(r)}clone(){const e=new jl(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const yx=(e,...t)=>new fx(tn(e),...t),bx=cn(([e,t,r],s)=>{let i;s.renderer.coordinateSystem===h?(e=_n(e.x,e.y.oneMinus()).mul(2).sub(1),i=Cn(Rn(e,t),1)):i=Cn(Rn(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Cn(r.mul(i));return n.xyz.div(n.w)}),xx=cn(([e,t])=>{const r=t.mul(Cn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return _n(s.x,s.y.oneMinus())}),Tx=cn(([e,t,r])=>{const s=zl(Ql(t)),i=vn(e.mul(s)).toVar(),n=Ql(t,i).toVar(),a=Ql(t,i.sub(vn(2,0))).toVar(),o=Ql(t,i.sub(vn(1,0))).toVar(),u=Ql(t,i.add(vn(1,0))).toVar(),l=Ql(t,i.add(vn(2,0))).toVar(),d=Ql(t,i.add(vn(0,2))).toVar(),c=Ql(t,i.add(vn(0,1))).toVar(),h=Ql(t,i.sub(vn(0,1))).toVar(),p=Ql(t,i.sub(vn(0,2))).toVar(),g=Vo(Pa(yn(2).mul(o).sub(a),n)).toVar(),m=Vo(Pa(yn(2).mul(u).sub(l),n)).toVar(),f=Vo(Pa(yn(2).mul(c).sub(d),n)).toVar(),y=Vo(Pa(yn(2).mul(h).sub(p),n)).toVar(),b=bx(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(bx(e.sub(_n(yn(1).div(s.x),0)),o,r)),b.negate().add(bx(e.add(_n(yn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(bx(e.add(_n(0,yn(1).div(s.y))),c,r)),b.negate().add(bx(e.sub(_n(0,yn(1).div(s.y))),h,r)));return Ro(au(x,T))}),_x=cn(([e])=>Ao(yn(52.9829189).mul(Ao(nu(e,_n(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),vx=cn(([e,t,r])=>{const s=yn(2.399963229728653),i=_o(yn(e).add(.5).div(yn(t))),n=yn(e).mul(s).add(r);return _n(Co(n),Eo(n)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class Nx extends ci{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(kl())}sample(e){return this.callback(e)}}class Sx extends ci{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Sx.OBJECT?this.updateType=ri.OBJECT:e===Sx.MATERIAL?this.updateType=ri.RENDER:e===Sx.FRAME?this.updateType=ri.FRAME:e===Sx.BEFORE_OBJECT?this.updateBeforeType=ri.OBJECT:e===Sx.BEFORE_MATERIAL?this.updateBeforeType=ri.RENDER:e===Sx.BEFORE_FRAME&&(this.updateBeforeType=ri.FRAME)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}Sx.OBJECT="object",Sx.MATERIAL="material",Sx.FRAME="frame",Sx.BEFORE_OBJECT="beforeObject",Sx.BEFORE_MATERIAL="beforeMaterial",Sx.BEFORE_FRAME="beforeFrame";const Rx=(e,t)=>new Sx(e,t).toStack();class Ax extends q{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Ex extends we{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class wx extends ci{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Cx=on(wx),Mx=new a,Bx=Sa(0).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Fx=Sa(1).setGroup(_a).onRenderUpdate(({scene:e})=>e.backgroundIntensity),Lx=Sa(new a).setGroup(_a).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&t.mapping!==dt?Mx.makeRotationFromEuler(e.backgroundRotation).transpose():Mx.identity(),Mx});class Px extends jl{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=ii.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return null!==this.storeNode?(this.generateStore(e),""):super.generate(e,t)}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;return e.generateStorageTextureLoad(l,t,r,s,n,u)}toReadWrite(){return this.setAccess(ii.READ_WRITE)}toReadOnly(){return this.setAccess(ii.READ_ONLY)}toWriteOnly(){return this.setAccess(ii.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(this.value,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}}const Ux=an(Px).setParameterLength(1,3),Dx=cn(({texture:e,uv:t})=>{const r=1e-4,s=Rn().toVar();return gn(t.x.lessThan(r),()=>{s.assign(Rn(1,0,0))}).ElseIf(t.y.lessThan(r),()=>{s.assign(Rn(0,1,0))}).ElseIf(t.z.lessThan(r),()=>{s.assign(Rn(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{s.assign(Rn(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{s.assign(Rn(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{s.assign(Rn(0,0,-1))}).Else(()=>{const r=.01,i=e.sample(t.add(Rn(-.01,0,0))).r.sub(e.sample(t.add(Rn(r,0,0))).r),n=e.sample(t.add(Rn(0,-.01,0))).r.sub(e.sample(t.add(Rn(0,r,0))).r),a=e.sample(t.add(Rn(0,0,-.01))).r.sub(e.sample(t.add(Rn(0,0,r))).r);s.assign(Rn(i,n,a))}),s.normalize()});class Ix extends jl{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Rn(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return Dx({texture:this,uv:e})}}const Ox=an(Ix).setParameterLength(1,3);class Vx extends Hc{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const kx=new WeakMap;class Gx extends gi{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=ri.OBJECT,this.updateAfterType=ri.OBJECT,this.previousModelWorldMatrix=Sa(new a),this.previousProjectionMatrix=Sa(new a).setGroup(_a),this.previousCameraViewMatrix=Sa(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=$x(r);this.previousModelWorldMatrix.value.copy(s);const i=zx(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new a,i.previousCameraViewMatrix=new a,i.currentProjectionMatrix=new a,i.currentCameraViewMatrix=new a,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){$x(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Ld:Sa(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(sc).mul(lc),s=this.previousProjectionMatrix.mul(t).mul(dc),i=r.xy.div(r.w),n=s.xy.div(s.w);return Pa(i,n)}}function zx(e){let t=kx.get(e);return void 0===t&&(t={},kx.set(e,t)),t}function $x(e,t=0){const r=zx(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const Wx=on(Gx),Hx=cn(([e])=>Kx(e.rgb)),qx=cn(([e,t=yn(1)])=>t.mix(Kx(e.rgb),e.rgb)),jx=cn(([e,t=yn(1)])=>{const r=La(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return gu(e.rgb,s,i)}),Xx=cn(([e,t=yn(1)])=>{const r=Rn(.57735,.57735,.57735),s=t.cos();return Rn(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(nu(r,e.rgb).mul(s.oneMinus())))))}),Kx=(e,t=Rn(p.getLuminanceCoefficients(new r)))=>nu(e,t),Qx=cn(([e,t=Rn(1),s=Rn(0),i=Rn(1),n=yn(1),a=Rn(p.getLuminanceCoefficients(new r,Re))])=>{const o=e.rgb.dot(Rn(a)),u=eu(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return gn(u.r.greaterThan(0),()=>{u.r.assign(l.r)}),gn(u.g.greaterThan(0),()=>{u.g.assign(l.g)}),gn(u.b.greaterThan(0),()=>{u.b.assign(l.b)}),u.assign(o.add(u.sub(o).mul(n))),Cn(u.rgb,e.a)}),Yx=cn(([e,t])=>e.mul(t).floor().div(t));let Zx=null;class Jx extends Wp{static get type(){return"ViewportSharedTextureNode"}constructor(e=ud,t=null){null===Zx&&(Zx=new Q),super(e,t,Zx)}getTextureForReference(){return Zx}updateReference(){return this}}const eT=an(Jx).setParameterLength(0,2),tT=new t;class rT extends jl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class sT extends rT{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class iT extends gi{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const i=new Z;i.isRenderTargetTexture=!0,i.name="depth";const n=new ne(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Te,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Sa(0),this._cameraFar=Sa(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=ri.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return d("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return d("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new sT(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new sT(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=sg(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=Jp(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),!0===e.reversedDepthBuffer&&(this.renderTarget.depthTexture.type=K),this.scope===iT.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s,i;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(i=1,s=t.xr.getCamera(),t.xr.updateCamera(s),tT.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(tT)),this._pixelRatio=i,this.setSize(tT.width,tT.height);const a=t.getRenderTarget(),o=t.getMRT(),u=t.autoClear,l=t.transparent,d=t.opaque,c=s.layers.mask,h=t.contextNode,p=r.overrideMaterial;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(r.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Cu({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const g=r.name;r.name=this.name?this.name:r.name,t.render(r,s),r.name=g,r.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=u,t.transparent=l,t.opaque=d,t.contextNode=h,s.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const r=Math.floor(this._width*this._pixelRatio*this._resolutionScale),s=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(r,s),null!==this._scissor?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,r,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new s),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,i))}setViewport(e,t,r,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new s),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}iT.COLOR="color",iT.DEPTH="depth";class nT extends iT{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(iT.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)}),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new vg;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=L;const t=Tc.negate(),r=Ld.mul(sc),s=yn(1),i=r.mul(Cn(lc,1)),n=r.mul(Cn(lc.add(t),1)),a=Ro(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=Cn(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const aT=cn(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),oT=cn(([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"}]}),uT=cn(([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lT=cn(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)}),dT=cn(([e,t])=>{const r=Pn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Pn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=lT(e),(e=s.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),cT=Pn(Rn(1.6605,-.1246,-.0182),Rn(-.5876,1.1329,-.1006),Rn(-.0728,-.0083,1.1187)),hT=Pn(Rn(.6274,.0691,.0164),Rn(.3293,.9195,.088),Rn(.0433,.0113,.8956)),pT=cn(([e])=>{const t=Rn(e).toVar(),r=Rn(t.mul(t)).toVar(),s=Rn(r.mul(r)).toVar();return yn(15.5).mul(s.mul(r)).sub(Ua(40.14,s.mul(t))).add(Ua(31.96,s).sub(Ua(6.868,r.mul(t))).add(Ua(.4298,r).add(Ua(.1191,t).sub(.00232))))}),gT=cn(([e,t])=>{const r=Rn(e).toVar(),s=Pn(Rn(.856627153315983,.137318972929847,.11189821299995),Rn(.0951212405381588,.761241990602591,.0767994186031903),Rn(.0482516061458583,.101439036467562,.811302368396859)),i=Pn(Rn(1.1271005818144368,-.1413297634984383,-.14132976349843826),Rn(-.11060664309660323,1.157823702216272,-.11060664309660294),Rn(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=yn(-12.47393),a=yn(4.026069);return r.mulAssign(t),r.assign(hT.mul(r)),r.assign(s.mul(r)),r.assign(eu(r,1e-10)),r.assign(To(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(mu(r,0,1)),r.assign(pT(r)),r.assign(i.mul(r)),r.assign(ou(eu(Rn(0),r),Rn(2.2))),r.assign(cT.mul(r)),r.assign(mu(r,0,1)),r}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),mT=cn(([e,t])=>{const r=yn(.76),s=yn(.15);e=e.mul(t);const i=Jo(e.r,Jo(e.g,e.b)),n=Eu(i.lessThan(.08),i.sub(Ua(6.25,i.mul(i))),.04);e.subAssign(n);const a=eu(e.r,eu(e.g,e.b));gn(a.lessThan(r),()=>e);const o=Pa(1,r),u=Pa(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=Pa(1,Da(1,s.mul(a.sub(u)).add(1)));return gu(e,Rn(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class fT extends ci{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.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}}const yT=an(fT).setParameterLength(1,3);class bT extends fT{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const xT=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};function TT(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||pc.z).negate()}const _T=cn(([e,t],r)=>{const s=TT(r);return bu(e,t,s)}),vT=cn(([e],t)=>{const r=TT(t);return e.mul(e,r,r).negate().exp().oneMinus()}),NT=cn(([e,t],r)=>{const s=TT(r),i=t.sub(cc.y).max(0).toConst().mul(s).toConst();return e.mul(e,i,i).negate().exp().oneMinus()}),ST=cn(([e,t])=>Cn(t.toFloat().mix(oa.rgb,e.toVec3()),oa.a));let RT=null,AT=null;class ET extends ci{static get type(){return"RangeNode"}constructor(e=yn(),t=yn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),s=e.getTypeLength(Ks(t.value)),i=e.getTypeLength(Ks(r.value));return s>i?s:i}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Hl('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=i.value,o=n.value,u=e.getTypeLength(Ks(a)),d=e.getTypeLength(Ks(o));RT=RT||new s,AT=AT||new s,RT.setScalar(0),AT.setScalar(0),1===u?RT.setScalar(a):a.isColor?RT.set(a.r,a.g,a.b,1):RT.set(a.x,a.y,a.z||0,a.w||0),1===d?AT.setScalar(o):o.isColor?AT.set(o.r,o.g,o.b,1):AT.set(o.x,o.y,o.z||0,o.w||0);const c=4,h=c*t.count,p=new Float32Array(h);for(let e=0;enew CT(e,t),BT=MT("numWorkgroups","uvec3"),FT=MT("workgroupId","uvec3"),LT=MT("globalId","uvec3"),PT=MT("localId","uvec3"),UT=MT("subgroupSize","uint");class DT extends ci{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}const IT=an(DT);class OT extends hi{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.context.assign;if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class VT extends ci{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Is),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new OT(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class kT extends ci{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Cl(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}kT.ATOMIC_LOAD="atomicLoad",kT.ATOMIC_STORE="atomicStore",kT.ATOMIC_ADD="atomicAdd",kT.ATOMIC_SUB="atomicSub",kT.ATOMIC_MAX="atomicMax",kT.ATOMIC_MIN="atomicMin",kT.ATOMIC_AND="atomicAnd",kT.ATOMIC_OR="atomicOr",kT.ATOMIC_XOR="atomicXor";const GT=an(kT),zT=(e,t,r)=>GT(e,t,r).toStack();class $T extends gi{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}generateNodeType(e){const t=this.method;return t===$T.SUBGROUP_ELECT?"bool":t===$T.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===$T.SUBGROUP_BROADCAST||r===$T.SUBGROUP_SHUFFLE||r===$T.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===$T.SUBGROUP_SHUFFLE_XOR||r===$T.SUBGROUP_SHUFFLE_DOWN||r===$T.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}$T.SUBGROUP_ELECT="subgroupElect",$T.SUBGROUP_BALLOT="subgroupBallot",$T.SUBGROUP_ADD="subgroupAdd",$T.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",$T.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",$T.SUBGROUP_MUL="subgroupMul",$T.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",$T.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",$T.SUBGROUP_AND="subgroupAnd",$T.SUBGROUP_OR="subgroupOr",$T.SUBGROUP_XOR="subgroupXor",$T.SUBGROUP_MIN="subgroupMin",$T.SUBGROUP_MAX="subgroupMax",$T.SUBGROUP_ALL="subgroupAll",$T.SUBGROUP_ANY="subgroupAny",$T.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",$T.QUAD_SWAP_X="quadSwapX",$T.QUAD_SWAP_Y="quadSwapY",$T.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",$T.SUBGROUP_BROADCAST="subgroupBroadcast",$T.SUBGROUP_SHUFFLE="subgroupShuffle",$T.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",$T.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",$T.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",$T.QUAD_BROADCAST="quadBroadcast";const WT=un($T,$T.SUBGROUP_ELECT).setParameterLength(0),HT=un($T,$T.SUBGROUP_BALLOT).setParameterLength(1),qT=un($T,$T.SUBGROUP_ADD).setParameterLength(1),jT=un($T,$T.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),XT=un($T,$T.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),KT=un($T,$T.SUBGROUP_MUL).setParameterLength(1),QT=un($T,$T.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),YT=un($T,$T.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),ZT=un($T,$T.SUBGROUP_AND).setParameterLength(1),JT=un($T,$T.SUBGROUP_OR).setParameterLength(1),e_=un($T,$T.SUBGROUP_XOR).setParameterLength(1),t_=un($T,$T.SUBGROUP_MIN).setParameterLength(1),r_=un($T,$T.SUBGROUP_MAX).setParameterLength(1),s_=un($T,$T.SUBGROUP_ALL).setParameterLength(0),i_=un($T,$T.SUBGROUP_ANY).setParameterLength(0),n_=un($T,$T.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),a_=un($T,$T.QUAD_SWAP_X).setParameterLength(1),o_=un($T,$T.QUAD_SWAP_Y).setParameterLength(1),u_=un($T,$T.QUAD_SWAP_DIAGONAL).setParameterLength(1),l_=un($T,$T.SUBGROUP_BROADCAST).setParameterLength(2),d_=un($T,$T.SUBGROUP_SHUFFLE).setParameterLength(2),c_=un($T,$T.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),h_=un($T,$T.SUBGROUP_SHUFFLE_UP).setParameterLength(2),p_=un($T,$T.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),g_=un($T,$T.QUAD_BROADCAST).setParameterLength(1);let m_;function f_(e){m_=m_||new WeakMap;let t=m_.get(e);return void 0===t&&m_.set(e,t={}),t}function y_(e){const t=f_(e);return t.shadowMatrix||(t.shadowMatrix=Sa("mat4").setGroup(_a).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 b_(e,t=cc){const r=y_(e).mul(t);return r.xyz.div(r.w)}function x_(e){const t=f_(e);return t.position||(t.position=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld)))}function T_(e){const t=f_(e);return t.targetPosition||(t.targetPosition=Sa(new r).setGroup(_a).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld)))}function __(e){const t=f_(e);return t.viewPosition||(t.viewPosition=Sa(new r).setGroup(_a).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const v_=e=>Ud.transformDirection(x_(e).sub(T_(e))),N_=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},S_=new WeakMap,R_=[];class A_ extends ci{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Vn("vec3","totalDiffuse"),this.totalSpecularNode=Vn("vec3","totalSpecular"),this.outgoingLightNode=Vn("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(tn(e));else{let s=null;if(null!==r&&(s=N_(e.id,r)),null===s){const t=i.getLightNodeClass(e.constructor);if(null===t){d(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===S_.has(e)&&S_.set(e,new t(e)),s=S_.get(e)}t.push(s)}this._lightNodes=t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=Rn(null!==l?l.mix(g,u):u)),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class E_ extends ci{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ri.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){w_.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||cc)}}const w_=Vn("vec3","shadowPositionWorld");function C_(t,r={}){return r.toneMapping=t.toneMapping,r.toneMappingExposure=t.toneMappingExposure,r.outputColorSpace=t.outputColorSpace,r.renderTarget=t.getRenderTarget(),r.activeCubeFace=t.getActiveCubeFace(),r.activeMipmapLevel=t.getActiveMipmapLevel(),r.renderObjectFunction=t.getRenderObjectFunction(),r.pixelRatio=t.getPixelRatio(),r.mrt=t.getMRT(),r.clearColor=t.getClearColor(r.clearColor||new e),r.clearAlpha=t.getClearAlpha(),r.autoClear=t.autoClear,r.scissorTest=t.getScissorTest(),r}function M_(e,t){return t=C_(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function B_(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)}function F_(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function L_(e,t){return t=F_(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function P_(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function U_(e,t,r){return r=L_(t,r=M_(e,r))}function D_(e,t,r){B_(e,r),P_(t,r)}var I_=Object.freeze({__proto__:null,resetRendererAndSceneState:U_,resetRendererState:M_,resetSceneState:L_,restoreRendererAndSceneState:D_,restoreRendererState:B_,restoreSceneState:P_,saveRendererAndSceneState:function(e,t,r={}){return r=F_(t,r=C_(e,r))},saveRendererState:C_,saveSceneState:F_});const O_=new WeakMap,V_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Kl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)}),k_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=qc("radius","float",r).setGroup(_a),o=_n(1).div(n),u=a.mul(o.x),l=_x(dd.xy).mul(6.28318530718);return La(i(t.xy.add(vx(0,5,l).mul(u)),t.z),i(t.xy.add(vx(1,5,l).mul(u)),t.z),i(t.xy.add(vx(2,5,l).mul(u)),t.z),i(t.xy.add(vx(3,5,l).mul(u)),t.z),i(t.xy.add(vx(4,5,l).mul(u)),t.z)).mul(.2)}),G_=cn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Kl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=qc("mapSize","vec2",r).setGroup(_a),a=_n(1).div(n),o=a.x,u=a.y,l=t.xy,d=Ao(l.mul(n).add(.5));return l.subAssign(d.mul(a)),La(i(l,t.z),i(l.add(_n(o,0)),t.z),i(l.add(_n(0,u)),t.z),i(l.add(a),t.z),gu(i(l.add(_n(o.negate(),0)),t.z),i(l.add(_n(o.mul(2),0)),t.z),d.x),gu(i(l.add(_n(o.negate(),u)),t.z),i(l.add(_n(o.mul(2),u)),t.z),d.x),gu(i(l.add(_n(0,u.negate())),t.z),i(l.add(_n(0,u.mul(2))),t.z),d.y),gu(i(l.add(_n(o,u.negate())),t.z),i(l.add(_n(o,u.mul(2))),t.z),d.y),gu(gu(i(l.add(_n(o.negate(),u.negate())),t.z),i(l.add(_n(o.mul(2),u.negate())),t.z),d.x),gu(i(l.add(_n(o.negate(),u.mul(2))),t.z),i(l.add(_n(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)}),z_=cn(({depthTexture:e,shadowCoord:t,depthLayer:r},s)=>{let i=Kl(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=i.x,a=eu(1e-7,i.y.mul(i.y)),o=s.renderer.reversedDepthBuffer?tu(n,t.z):tu(t.z,n),u=yn(1).toVar();return gn(o.notEqual(1),()=>{const e=t.z.sub(n);let r=a.div(a.add(e.mul(e)));r=mu(Pa(r,.3).div(.65)),u.assign(eu(o,r))}),u}),$_=e=>{let t=O_.get(e);return void 0===t&&(t=new vg,t.colorNode=Cn(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=re,t.fog=!1,O_.set(e,t)),t},W_=e=>{const t=O_.get(e);void 0!==t&&(t.dispose(),O_.delete(e))},H_=new Ty,q_=[],j_=(e,t,r,s)=>{q_[0]=e,q_[1]=t;let i=H_.get(q_);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===pt)&&(s&&(Ys(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,...d),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,H_.set(q_,i)),q_[0]=null,q_[1]=null,i},X_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanVertical"),a=yn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(La(dd.xy,_n(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),K_=cn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=yn(0).toVar("meanHorizontal"),a=yn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(yn(1)).select(yn(0),yn(2).div(e.sub(1))),u=e.lessThanEqual(yn(1)).select(yn(0),yn(-1));Bp({start:bn(0),end:bn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(yn(e).mul(o));let d=s.sample(La(dd.xy,_n(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(La(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(e),a.divAssign(e);const l=_o(a.sub(n.mul(n)).max(0));return _n(n,l)}),Q_=[V_,k_,G_,z_];let Y_;const Z_=new gx;class J_ extends E_{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:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,yn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=r.biasNode||qc("bias","float",r).setGroup(_a);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=qc("near","float",r.camera).setGroup(_a),s=qc("far","float",r.camera).setGroup(_a);n=ig(e.negate(),t,s)}return a=Rn(a.x,a.y.oneMinus(),s.reversedDepthBuffer?n.sub(i):n.add(i)),a}getShadowFilterFn(e){return Q_[e]}setupRenderTarget(e,t){const r=new Z(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t,camera:r}=e,{light:s,shadow:i}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(i,e),o=t.shadowMap.type,u=t.hasCompatibility(A.TEXTURE_COMPARE);if(o!==ct&&o!==ht||!u?(n.minFilter=B,n.magFilter=B):(n.minFilter=le,n.magFilter=le),i.camera.coordinateSystem=r.coordinateSystem,i.camera.updateProjectionMatrix(),o===pt&&!0!==i.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}));let t=Kl(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Kl(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const s=qc("blurSamples","float",i).setGroup(_a),o=qc("radius","float",i).setGroup(_a),u=qc("mapSize","vec2",i).setGroup(_a);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new vg);l.fragmentNode=X_({samples:s,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new vg),l.fragmentNode=K_({samples:s,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=qc("intensity","float",i).setGroup(_a),d=qc("normalBias","float",i).setGroup(_a),c=y_(s),h=Rc.mul(d);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(w_.add(h));else{p=Sa("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(lc).add(c.mul(Cn(h,0)))}const g=this.setupShadowCoord(e,p),m=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=o===pt&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:f,shadowCoord:g,shadow:i,depthLayer:this.depthLayer});let b,x;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=$c(a.texture,g.xyz):(b=Kl(a.texture,g),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),x=b?gu(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():gu(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const T=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&x.toInspector(`${T} / Color`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture):Kl(this.shadowMap.texture)),x.toInspector(`${T} / Depth`,()=>this.shadowMap.texture.isCubeTexture?$c(this.shadowMap.texture).r.oneMinus():Ql(this.shadowMap.depthTexture,kl().mul(zl(Kl(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return cn(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let r=this._node;return this.setupShadowPosition(e),null===r&&(this._node=r=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(r=e.material.receivedShadowNode(r)),r})()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth);const a=n.name;n.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,i.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");Y_=U_(i,n,Y_),n.overrideMaterial=$_(r),i.setRenderObjectFunction(j_(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===pt&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,D_(i,n,Y_)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),Z_.material=this.vsmMaterialVertical,Z_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Z_.material=this.vsmMaterialHorizontal,Z_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,W_(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const ev=(e,t)=>new J_(e,t),tv=new e,rv=new a,sv=new r,iv=new r,nv=[new r(1,0,0),new r(-1,0,0),new r(0,-1,0),new r(0,1,0),new r(0,0,1),new r(0,0,-1)],av=[new r(0,-1,0),new r(0,-1,0),new r(0,0,-1),new r(0,0,1),new r(0,-1,0),new r(0,-1,0)],ov=[new r(1,0,0),new r(-1,0,0),new r(0,1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1)],uv=[new r(0,-1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1),new r(0,-1,0),new r(0,-1,0)],lv=cn(({depthTexture:e,bd3D:t,dp:r})=>$c(e,t).compare(r)),dv=cn(({depthTexture:e,bd3D:t,dp:r,shadow:s})=>{const i=qc("radius","float",s).setGroup(_a),n=qc("mapSize","vec2",s).setGroup(_a),a=i.div(n.x),o=Vo(t),u=Ro(au(t,o.x.greaterThan(o.z).select(Rn(0,1,0),Rn(1,0,0)))),l=au(t,u),d=_x(dd.xy).mul(6.28318530718),c=vx(0,5,d),h=vx(1,5,d),p=vx(2,5,d),g=vx(3,5,d),m=vx(4,5,d);return $c(e,t.add(u.mul(c.x).add(l.mul(c.y)).mul(a))).compare(r).add($c(e,t.add(u.mul(h.x).add(l.mul(h.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(p.x).add(l.mul(p.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(g.x).add(l.mul(g.y)).mul(a))).compare(r)).add($c(e,t.add(u.mul(m.x).add(l.mul(m.y)).mul(a))).compare(r)).mul(.2)}),cv=cn(({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s},i)=>{const n=r.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),u=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.near),l=Sa("float").setGroup(_a).onRenderUpdate(()=>s.camera.far),d=qc("bias","float",s).setGroup(_a),c=yn(1).toVar();return gn(o.sub(l).lessThanEqual(0).and(o.sub(u).greaterThanEqual(0)),()=>{let r;i.renderer.reversedDepthBuffer?(r=rg(o.negate(),u,l),r.subAssign(d)):(r=tg(o.negate(),u,l),r.addAssign(d));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:r,shadow:s}))}),c});class hv extends J_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===gt?lv:dv}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i}){return cv({filterFn:t,depthTexture:r,shadowCoord:s,shadow:i})}setupRenderTarget(e,t){const r=new mt(e.mapSize.width);r.name="PointShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:w;const s=t.createCubeRenderTarget(e.mapSize.width);return s.texture.name="PointShadowMap",s.depthTexture=r,{shadowMap:s,depthTexture:r}}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.camera,o=t.matrix,u=i.coordinateSystem===h,l=u?nv:ov,d=u?av:uv;r.setSize(t.mapSize.width,t.mapSize.width);const c=i.autoClear,p=i.getClearColor(tv),g=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(r,e),i.clear();const u=s.distance||a.far;u!==a.far&&(a.far=u,a.updateProjectionMatrix()),sv.setFromMatrixPosition(s.matrixWorld),a.position.copy(sv),iv.copy(a.position),iv.add(l[e]),a.up.copy(d[e]),a.lookAt(iv),a.updateMatrixWorld(),o.makeTranslation(-sv.x,-sv.y,-sv.z),rv.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(rv,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${e+1}`,i.render(n,a),n.name=c}i.autoClear=c,i.setClearColor(p,g)}}const pv=(e,t)=>new hv(e,t);class gv extends Op{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Sa(this.color).setGroup(_a),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ri.FRAME,t&&t.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},t.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 __(this.light).sub(e.context.positionView||pc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return ev(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?tn(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(r=e.context.getShadow(this,e)),this.colorNode=r}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),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const mv=cn(({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)}),fv=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=mv({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class yv extends gv{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(2).setGroup(_a)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return pv(this.light)}setupDirect(e){return fv({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const bv=cn(([e=kl()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()}),xv=cn(([e=kl()],{renderer:t,material:r})=>{const s=pu(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.currentSamples>0){const e=yn(s.fwidth()).toVar();i=bu(e.oneMinus(),e.add(1),s).oneMinus()}else i=Eu(s.greaterThan(1),0,1);return i}),Tv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=Tn(e).toVar();return Eu(n,i,s)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),_v=cn(([e,t])=>{const r=Tn(t).toVar(),s=yn(e).toVar();return Eu(r,s.negate(),s)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),vv=cn(([e])=>{const t=yn(e).toVar();return bn(No(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Nv=cn(([e,t])=>{const r=yn(e).toVar();return t.assign(vv(r)),r.sub(yn(t))}),Sv=Vb([cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=yn(s).toVar(),l=yn(r).toVar(),d=yn(t).toVar(),c=yn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),cn(([e,t,r,s,i,n])=>{const a=yn(n).toVar(),o=yn(i).toVar(),u=Rn(s).toVar(),l=Rn(r).toVar(),d=Rn(t).toVar(),c=Rn(e).toVar(),h=yn(Pa(1,o)).toVar();return Pa(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),Rv=Vb([cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=yn(o).toVar(),m=yn(a).toVar(),f=yn(n).toVar(),y=yn(i).toVar(),b=yn(s).toVar(),x=yn(r).toVar(),T=yn(t).toVar(),_=yn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=yn(d).toVar(),h=yn(l).toVar(),p=yn(u).toVar(),g=Rn(o).toVar(),m=Rn(a).toVar(),f=Rn(n).toVar(),y=Rn(i).toVar(),b=Rn(s).toVar(),x=Rn(r).toVar(),T=Rn(t).toVar(),_=Rn(e).toVar(),v=yn(Pa(1,p)).toVar(),N=yn(Pa(1,h)).toVar();return yn(Pa(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),Av=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=xn(e).toVar(),a=xn(n.bitAnd(xn(7))).toVar(),o=yn(Tv(a.lessThan(xn(4)),i,s)).toVar(),u=yn(Ua(2,Tv(a.lessThan(xn(4)),s,i))).toVar();return _v(o,Tn(a.bitAnd(xn(1)))).add(_v(u,Tn(a.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Ev=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=xn(e).toVar(),u=xn(o.bitAnd(xn(15))).toVar(),l=yn(Tv(u.lessThan(xn(8)),a,n)).toVar(),d=yn(Tv(u.lessThan(xn(4)),n,Tv(u.equal(xn(12)).or(u.equal(xn(14))),a,i))).toVar();return _v(l,Tn(u.bitAnd(xn(1)))).add(_v(d,Tn(u.bitAnd(xn(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),wv=Vb([Av,Ev]),Cv=cn(([e,t,r])=>{const s=yn(r).toVar(),i=yn(t).toVar(),n=En(e).toVar();return Rn(wv(n.x,i,s),wv(n.y,i,s),wv(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Mv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=yn(t).toVar(),o=En(e).toVar();return Rn(wv(o.x,a,n,i),wv(o.y,a,n,i),wv(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),Bv=Vb([Cv,Mv]),Fv=cn(([e])=>{const t=yn(e).toVar();return Ua(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Lv=cn(([e])=>{const t=yn(e).toVar();return Ua(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Pv=Vb([Fv,cn(([e])=>{const t=Rn(e).toVar();return Ua(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Uv=Vb([Lv,cn(([e])=>{const t=Rn(e).toVar();return Ua(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),Dv=cn(([e,t])=>{const r=bn(t).toVar(),s=xn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(bn(32).sub(r)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),Iv=cn(([e,t,r])=>{e.subAssign(r),e.bitXorAssign(Dv(r,bn(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Dv(e,bn(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Dv(t,bn(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(Dv(r,bn(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(Dv(e,bn(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(Dv(t,bn(4))),t.addAssign(e)}),Ov=cn(([e,t,r])=>{const s=xn(r).toVar(),i=xn(t).toVar(),n=xn(e).toVar();return s.bitXorAssign(i),s.subAssign(Dv(i,bn(14))),n.bitXorAssign(s),n.subAssign(Dv(s,bn(11))),i.bitXorAssign(n),i.subAssign(Dv(n,bn(25))),s.bitXorAssign(i),s.subAssign(Dv(i,bn(16))),n.bitXorAssign(s),n.subAssign(Dv(s,bn(4))),i.bitXorAssign(n),i.subAssign(Dv(n,bn(14))),s.bitXorAssign(i),s.subAssign(Dv(i,bn(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Vv=cn(([e])=>{const t=xn(e).toVar();return yn(t).div(yn(xn(bn(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),kv=cn(([e])=>{const t=yn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),Gv=Vb([cn(([e])=>{const t=bn(e).toVar(),r=xn(xn(1)).toVar(),s=xn(xn(bn(3735928559)).add(r.shiftLeft(xn(2))).add(xn(13))).toVar();return Ov(s.add(xn(t)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(xn(2)).toVar(),n=xn().toVar(),a=xn().toVar(),o=xn().toVar();return n.assign(a.assign(o.assign(xn(bn(3735928559)).add(i.shiftLeft(xn(2))).add(xn(13))))),n.addAssign(xn(s)),a.addAssign(xn(r)),Ov(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(xn(3)).toVar(),o=xn().toVar(),u=xn().toVar(),l=xn().toVar();return o.assign(u.assign(l.assign(xn(bn(3735928559)).add(a.shiftLeft(xn(2))).add(xn(13))))),o.addAssign(xn(n)),u.addAssign(xn(i)),l.addAssign(xn(s)),Ov(o,u,l)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),cn(([e,t,r,s])=>{const i=bn(s).toVar(),n=bn(r).toVar(),a=bn(t).toVar(),o=bn(e).toVar(),u=xn(xn(4)).toVar(),l=xn().toVar(),d=xn().toVar(),c=xn().toVar();return l.assign(d.assign(c.assign(xn(bn(3735928559)).add(u.shiftLeft(xn(2))).add(xn(13))))),l.addAssign(xn(o)),d.addAssign(xn(a)),c.addAssign(xn(n)),Iv(l,d,c),l.addAssign(xn(i)),Ov(l,d,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),cn(([e,t,r,s,i])=>{const n=bn(i).toVar(),a=bn(s).toVar(),o=bn(r).toVar(),u=bn(t).toVar(),l=bn(e).toVar(),d=xn(xn(5)).toVar(),c=xn().toVar(),h=xn().toVar(),p=xn().toVar();return c.assign(h.assign(p.assign(xn(bn(3735928559)).add(d.shiftLeft(xn(2))).add(xn(13))))),c.addAssign(xn(l)),h.addAssign(xn(u)),p.addAssign(xn(o)),Iv(c,h,p),c.addAssign(xn(a)),h.addAssign(xn(n)),Ov(c,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),zv=Vb([cn(([e,t])=>{const r=bn(t).toVar(),s=bn(e).toVar(),i=xn(Gv(s,r)).toVar(),n=En().toVar();return n.x.assign(i.bitAnd(bn(255))),n.y.assign(i.shiftRight(bn(8)).bitAnd(bn(255))),n.z.assign(i.shiftRight(bn(16)).bitAnd(bn(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),cn(([e,t,r])=>{const s=bn(r).toVar(),i=bn(t).toVar(),n=bn(e).toVar(),a=xn(Gv(n,i,s)).toVar(),o=En().toVar();return o.x.assign(a.bitAnd(bn(255))),o.y.assign(a.shiftRight(bn(8)).bitAnd(bn(255))),o.z.assign(a.shiftRight(bn(16)).bitAnd(bn(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),$v=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=yn(Sv(wv(Gv(r,s),i,n),wv(Gv(r.add(bn(1)),s),i.sub(1),n),wv(Gv(r,s.add(bn(1))),i,n.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=yn(Rv(wv(Gv(r,s,i),n,a,o),wv(Gv(r.add(bn(1)),s,i),n.sub(1),a,o),wv(Gv(r,s.add(bn(1)),i),n,a.sub(1),o),wv(Gv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),wv(Gv(r,s,i.add(bn(1))),n,a,o.sub(1)),wv(Gv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),wv(Gv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),wv(Gv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Uv(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),Wv=Vb([cn(([e])=>{const t=_n(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=yn(Nv(t.x,r)).toVar(),n=yn(Nv(t.y,s)).toVar(),a=yn(kv(i)).toVar(),o=yn(kv(n)).toVar(),u=Rn(Sv(Bv(zv(r,s),i,n),Bv(zv(r.add(bn(1)),s),i.sub(1),n),Bv(zv(r,s.add(bn(1))),i,n.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return Pv(u)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn().toVar(),s=bn().toVar(),i=bn().toVar(),n=yn(Nv(t.x,r)).toVar(),a=yn(Nv(t.y,s)).toVar(),o=yn(Nv(t.z,i)).toVar(),u=yn(kv(n)).toVar(),l=yn(kv(a)).toVar(),d=yn(kv(o)).toVar(),c=Rn(Rv(Bv(zv(r,s,i),n,a,o),Bv(zv(r.add(bn(1)),s,i),n.sub(1),a,o),Bv(zv(r,s.add(bn(1)),i),n,a.sub(1),o),Bv(zv(r.add(bn(1)),s.add(bn(1)),i),n.sub(1),a.sub(1),o),Bv(zv(r,s,i.add(bn(1))),n,a,o.sub(1)),Bv(zv(r.add(bn(1)),s,i.add(bn(1))),n.sub(1),a,o.sub(1)),Bv(zv(r,s.add(bn(1)),i.add(bn(1))),n,a.sub(1),o.sub(1)),Bv(zv(r.add(bn(1)),s.add(bn(1)),i.add(bn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return Uv(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),Hv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Vv(Gv(r))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Vv(Gv(r,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Vv(Gv(r,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Vv(Gv(r,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),qv=Vb([cn(([e])=>{const t=yn(e).toVar(),r=bn(vv(t)).toVar();return Rn(Vv(Gv(r,bn(0))),Vv(Gv(r,bn(1))),Vv(Gv(r,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),cn(([e])=>{const t=_n(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar();return Rn(Vv(Gv(r,s,bn(0))),Vv(Gv(r,s,bn(1))),Vv(Gv(r,s,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),cn(([e])=>{const t=Rn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar();return Rn(Vv(Gv(r,s,i,bn(0))),Vv(Gv(r,s,i,bn(1))),Vv(Gv(r,s,i,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),cn(([e])=>{const t=Cn(e).toVar(),r=bn(vv(t.x)).toVar(),s=bn(vv(t.y)).toVar(),i=bn(vv(t.z)).toVar(),n=bn(vv(t.w)).toVar();return Rn(Vv(Gv(r,s,i,n,bn(0))),Vv(Gv(r,s,i,n,bn(1))),Vv(Gv(r,s,i,n,bn(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),jv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=yn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul($v(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Xv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(0).toVar(),l=yn(1).toVar();return Bp(a,()=>{u.addAssign(l.mul(Wv(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Kv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar();return _n(jv(o,a,n,i),jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Qv=cn(([e,t,r,s])=>{const i=yn(s).toVar(),n=yn(r).toVar(),a=bn(t).toVar(),o=Rn(e).toVar(),u=Rn(Xv(o,a,n,i)).toVar(),l=yn(jv(o.add(Rn(bn(19),bn(193),bn(17))),a,n,i)).toVar();return Cn(u,l)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Yv=Vb([cn(([e,t,r,s,i,n,a])=>{const o=bn(a).toVar(),u=yn(n).toVar(),l=bn(i).toVar(),d=bn(s).toVar(),c=bn(r).toVar(),h=bn(t).toVar(),p=_n(e).toVar(),g=Rn(qv(_n(h.add(d),c.add(l)))).toVar(),m=_n(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=_n(_n(yn(h),yn(c)).add(m)).toVar(),y=_n(f.sub(p)).toVar();return gn(o.equal(bn(2)),()=>Vo(y.x).add(Vo(y.y))),gn(o.equal(bn(3)),()=>eu(Vo(y.x),Vo(y.y))),nu(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),cn(([e,t,r,s,i,n,a,o,u])=>{const l=bn(u).toVar(),d=yn(o).toVar(),c=bn(a).toVar(),h=bn(n).toVar(),p=bn(i).toVar(),g=bn(s).toVar(),m=bn(r).toVar(),f=bn(t).toVar(),y=Rn(e).toVar(),b=Rn(qv(Rn(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=Rn(Rn(yn(f),yn(m),yn(g)).add(b)).toVar(),T=Rn(x.sub(y)).toVar();return gn(l.equal(bn(2)),()=>Vo(T.x).add(Vo(T.y)).add(Vo(T.z))),gn(l.equal(bn(3)),()=>eu(Vo(T.x),Vo(T.y),Vo(T.z))),nu(T,T)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),Zv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();l.assign(Jo(l,r))})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Jv=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.y.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),eN=cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=_n(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=_n(Nv(n.x,a),Nv(n.y,o)).toVar(),l=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{const r=yn(Yv(u,e,t,a,o,i,s)).toVar();gn(r.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(r)}).ElseIf(r.lessThan(l.z),()=>{l.z.assign(r)})})}),gn(s.equal(bn(0)),()=>{l.assign(_o(l))}),l}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),tN=Vb([Zv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=yn(1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();d.assign(Jo(d,n))})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),rN=Vb([Jv,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=_n(1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.y.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),sN=Vb([eN,cn(([e,t,r])=>{const s=bn(r).toVar(),i=yn(t).toVar(),n=Rn(e).toVar(),a=bn().toVar(),o=bn().toVar(),u=bn().toVar(),l=Rn(Nv(n.x,a),Nv(n.y,o),Nv(n.z,u)).toVar(),d=Rn(1e6,1e6,1e6).toVar();return Bp({start:-1,end:bn(1),name:"x",condition:"<="},({x:e})=>{Bp({start:-1,end:bn(1),name:"y",condition:"<="},({y:t})=>{Bp({start:-1,end:bn(1),name:"z",condition:"<="},({z:r})=>{const n=yn(Yv(l,e,t,r,a,o,u,i,s)).toVar();gn(n.lessThan(d.x),()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.z.assign(d.y),d.y.assign(n)}).ElseIf(n.lessThan(d.z),()=>{d.z.assign(n)})})})}),gn(s.equal(bn(0)),()=>{d.assign(_o(d))}),d}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),iN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=_n(t).toVar(),p=_n(r).toVar(),g=_n(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(Rn(v,0),x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),nN=cn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=bn(e).toVar(),h=Rn(t).toVar(),p=Rn(r).toVar(),g=Rn(s).toVar(),m=yn(i).toVar(),f=yn(n).toVar(),y=yn(a).toVar(),b=Tn(o).toVar(),x=bn(u).toVar(),T=yn(l).toVar(),_=yn(d).toVar(),v=h.mul(p).add(g),N=yn(0).toVar();return gn(c.equal(bn(0)),()=>{N.assign(Wv(v))}),gn(c.equal(bn(1)),()=>{N.assign(qv(v))}),gn(c.equal(bn(2)),()=>{N.assign(sN(v,m,bn(0)))}),gn(c.equal(bn(3)),()=>{N.assign(Xv(v,x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),gn(b,()=>{N.assign(mu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),aN=cn(([e])=>{const t=e.y,r=e.z,s=Rn().toVar();return gn(t.lessThan(1e-4),()=>{s.assign(Rn(r,r,r))}).Else(()=>{let i=e.x;i=i.sub(No(i)).mul(6).toVar();const n=bn(Xo(i)),a=i.sub(yn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());gn(n.equal(bn(0)),()=>{s.assign(Rn(r,l,o))}).ElseIf(n.equal(bn(1)),()=>{s.assign(Rn(u,r,o))}).ElseIf(n.equal(bn(2)),()=>{s.assign(Rn(o,r,l))}).ElseIf(n.equal(bn(3)),()=>{s.assign(Rn(o,u,r))}).ElseIf(n.equal(bn(4)),()=>{s.assign(Rn(l,o,r))}).Else(()=>{s.assign(Rn(r,o,u))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),oN=cn(([e])=>{const t=Rn(e).toVar(),r=yn(t.x).toVar(),s=yn(t.y).toVar(),i=yn(t.z).toVar(),n=yn(Jo(r,Jo(s,i))).toVar(),a=yn(eu(r,eu(s,i))).toVar(),o=yn(a.sub(n)).toVar(),u=yn().toVar(),l=yn().toVar(),d=yn().toVar();return d.assign(a),gn(a.greaterThan(0),()=>{l.assign(o.div(a))}).Else(()=>{l.assign(0)}),gn(l.lessThanEqual(0),()=>{u.assign(0)}).Else(()=>{gn(r.greaterThanEqual(a),()=>{u.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{u.assign(La(2,i.sub(r).div(o)))}).Else(()=>{u.assign(La(4,r.sub(s).div(o)))}),u.mulAssign(1/6),gn(u.lessThan(0),()=>{u.addAssign(1)})}),Rn(u,l,d)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),uN=cn(([e])=>{const t=Rn(e).toVar(),r=wn(Ga(t,Rn(.04045))).toVar(),s=Rn(t.div(12.92)).toVar(),i=Rn(ou(eu(t.add(Rn(.055)),Rn(0)).div(1.055),Rn(2.4))).toVar();return gu(s,i,r)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lN=(e,t)=>{e=yn(e),t=yn(t);const r=_n(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return bu(e.sub(r),e.add(r),t)},dN=(e,t,r,s)=>gu(e,t,r[s].clamp()),cN=(e,t,r,s,i)=>gu(e,t,lN(r,s[i])),hN=cn(([e,t,r])=>{const s=Ro(e).toVar(),i=Pa(yn(.5).mul(t.sub(r)),cc).div(s).toVar(),n=Pa(yn(-.5).mul(t.sub(r)),cc).div(s).toVar(),a=Rn().toVar();a.x=s.x.greaterThan(yn(0)).select(i.x,n.x),a.y=s.y.greaterThan(yn(0)).select(i.y,n.y),a.z=s.z.greaterThan(yn(0)).select(i.z,n.z);const o=Jo(a.x,a.y,a.z).toVar();return cc.add(s.mul(o)).toVar().sub(r)}),pN=cn(([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(Ua(r,r).sub(Ua(s,s)))),n});var gN=Object.freeze({__proto__:null,BRDF_GGX:am,BRDF_Lambert:Hg,BasicPointShadowFilter:lv,BasicShadowFilter:V_,Break:Fp,Const:Ou,Continue:()=>Cl("continue").toStack(),DFGLUT:lm,D_GGX:sm,Discard:Ml,EPSILON:ao,F_Schlick:Wg,Fn:cn,HALF_PI:ho,INFINITY:oo,If:gn,Loop:Bp,NodeAccess:ii,NodeShaderStage:ti,NodeType:si,NodeUpdateType:ri,OnBeforeFrameUpdate:e=>Rx(Sx.BEFORE_FRAME,e),OnBeforeMaterialUpdate:e=>Rx(Sx.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>Rx(Sx.BEFORE_OBJECT,e),OnFrameUpdate:e=>Rx(Sx.FRAME,e),OnMaterialUpdate:e=>Rx(Sx.MATERIAL,e),OnObjectUpdate:e=>Rx(Sx.OBJECT,e),PCFShadowFilter:k_,PCFSoftShadowFilter:G_,PI:uo,PI2:lo,PointShadowFilter:dv,Return:()=>Cl("return").toStack(),Schlick_to_F0:hm,ShaderNode:en,Stack:mn,Switch:(...e)=>Si.Switch(...e),TBNViewMatrix:xh,TWO_PI:co,VSMShadowFilter:z_,V_GGX_SmithCorrelated:tm,Var:Iu,VarIntent:Vu,abs:Vo,acesFilmicToneMapping:dT,acos:Uo,acosh:Do,add:La,addMethodChaining:Ai,addNodeElement:function(e){d("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:gT,all:po,alphaT:Jn,and:Wa,anisotropy:ea,anisotropyB:ra,anisotropyT:ta,any:go,append:e=>(d("TSL: append() has been renamed to Stack().",new Is),mn(e)),array:Aa,arrayBuffer:e=>new vi(e,"ArrayBuffer"),asin:Lo,asinh:Po,assign:wa,atan:Io,atanh:Oo,atomicAdd:(e,t)=>zT(kT.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>zT(kT.ATOMIC_AND,e,t),atomicFunc:zT,atomicLoad:e=>zT(kT.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>zT(kT.ATOMIC_MAX,e,t),atomicMin:(e,t)=>zT(kT.ATOMIC_MIN,e,t),atomicOr:(e,t)=>zT(kT.ATOMIC_OR,e,t),atomicStore:(e,t)=>zT(kT.ATOMIC_STORE,e,t),atomicSub:(e,t)=>zT(kT.ATOMIC_SUB,e,t),atomicXor:(e,t)=>zT(kT.ATOMIC_XOR,e,t),attenuationColor:ma,attenuationDistance:ga,attribute:Vl,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ex(e,r,s);return Tp(i,t,e)},backgroundBlurriness:Bx,backgroundIntensity:Fx,backgroundRotation:Lx,batch:Ap,bentNormalView:_h,billboarding:Hb,bitAnd:Xa,bitNot:Ka,bitOr:Qa,bitXor:Ya,bitangentGeometry:mh,bitangentLocal:fh,bitangentView:yh,bitangentWorld:bh,bitcast:yb,blendBurn:mg,blendColor:xg,blendDodge:fg,blendOverlay:bg,blendScreen:yg,blur:pf,bool:Tn,buffer:Zl,bufferAttribute:ul,builtin:sd,builtinAOContext:Lu,builtinShadowContext:Fu,bumpMap:Ch,bvec2:Sn,bvec3:wn,bvec4:Fn,bypass:Rl,cache:Nl,call:Ma,cameraFar:Fd,cameraIndex:Md,cameraNear:Bd,cameraNormalMatrix:Id,cameraPosition:Od,cameraProjectionMatrix:Ld,cameraProjectionMatrixInverse:Pd,cameraViewMatrix:Ud,cameraViewport:Vd,cameraWorldMatrix:Dd,cbrt:hu,cdl:Qx,ceil:So,checker:bv,cineonToneMapping:uT,clamp:mu,clearcoat:qn,clearcoatNormalView:Ac,clearcoatRoughness:jn,clipSpace:oc,code:yT,color:fn,colorSpaceToWorking:Qu,colorToDirection:e=>tn(e).mul(2).sub(1),compute:Tl,computeKernel:xl,computeSkinning:(e,t=null)=>{const r=new wp(e);return r.positionNode=Tp(new q(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinIndexNode=Tp(new q(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.skinWeightNode=Tp(new q(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(pl).toVar(),r.bindMatrixNode=Sa(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Sa(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=Zl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,tn(r)},context:Cu,convert:In,convertColorSpace:(e,t,r)=>new Xu(tn(e),t,r),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():yx(e,...t),cos:Co,cosh:Mo,countLeadingZeros:vb,countOneBits:Nb,countTrailingZeros:_b,cross:au,cubeTexture:$c,cubeTextureBase:zc,dFdx:Wo,dFdy:Ho,dashSize:ua,debug:Pl,decrement:so,decrementBefore:to,defaultBuildStages:ai,defaultShaderStages:ni,defined:Zi,degrees:fo,deltaTime:Gb,densityFogFactor:vT,depth:ag,depthPass:(e,t,r)=>new iT(iT.DEPTH,e,t,r),determinant:Yo,difference:iu,diffuseColor:Gn,diffuseContribution:zn,directPointLight:fv,directionToColor:vh,directionToFaceDirection:bc,dispersion:fa,disposeShadowMaterial:W_,distance:su,div:Da,dot:nu,drawIndex:yl,dynamicBufferAttribute:(e,t=null,r=0,s=0)=>ol(e,t,r,s,x),element:Dn,emissive:$n,equal:Oa,equirectUV:Bg,exp:yo,exp2:bo,exponentialHeightFogFactor:NT,expression:Cl,faceDirection:yc,faceForward:xu,faceforward:Su,float:yn,floatBitsToInt:e=>new fb(e,"int","float"),floatBitsToUint:bb,floor:No,fog:ST,fract:Ao,frameGroup:Ta,frameId:zb,frontFacing:fc,fwidth:Ko,gain:(e,t)=>e.lessThan(.5)?Rb(e.mul(2),t).div(2):Pa(1,Rb(Ua(Pa(1,e),2),t).div(2)),gapSize:la,getConstNodeType:Ji,getCurrentStack:pn,getDirection:lf,getDistanceAttenuation:mv,getGeometryRoughness:Jg,getNormalFromDepth:Tx,getParallaxCorrectNormal:hN,getRoughness:em,getScreenPosition:xx,getShIrradianceAt:pN,getShadowMaterial:$_,getShadowRenderObjectFunction:j_,getTextureIndex:pb,getViewPosition:bx,ggxConvolution:yf,globalId:LT,glsl:(e,t)=>yT(e,t,"glsl"),glslFn:(e,t)=>xT(e,t,"glsl"),grayscale:Hx,greaterThan:Ga,greaterThanEqual:$a,hash:Sb,highpModelNormalViewMatrix:ac,highpModelViewMatrix:nc,hue:Xx,increment:ro,incrementBefore:eo,inspector:Il,instance:vp,instanceIndex:pl,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Hs("float")):(r=qs(t),s=Hs(t));const i=new Ax(e,r,s);return Tp(i,t,i.count)},instancedBufferAttribute:ll,instancedDynamicBufferAttribute:dl,instancedMesh:Sp,int:bn,intBitsToFloat:e=>new fb(e,"float","int"),interleavedGradientNoise:_x,inverse:Zo,inverseSqrt:vo,inversesqrt:Ru,invocationLocalIndex:fl,invocationSubgroupIndex:ml,ior:ca,iridescence:Qn,iridescenceIOR:Yn,iridescenceThickness:Zn,isolate:vl,ivec2:vn,ivec3:An,ivec4:Mn,js:(e,t)=>yT(e,t,"js"),label:Pu,length:Go,lengthSq:pu,lessThan:ka,lessThanEqual:za,lightPosition:x_,lightProjectionUV:b_,lightShadowMatrix:y_,lightTargetDirection:v_,lightTargetPosition:T_,lightViewPosition:__,lightingContext:Gp,lights:(e=[])=>(new A_).setLights(e),linearDepth:og,linearToneMapping:aT,localId:PT,log:xo,log2:To,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(xo(r.div(t)));return yn(Math.E).pow(s).mul(t).negate()},luminance:Kx,mat2:Ln,mat3:Pn,mat4:Un,matcapUV:ey,materialAO:gp,materialAlphaTest:Fh,materialAnisotropy:Yh,materialAnisotropyVector:mp,materialAttenuationColor:np,materialAttenuationDistance:ip,materialClearcoat:Hh,materialClearcoatNormal:jh,materialClearcoatRoughness:qh,materialColor:Lh,materialDispersion:hp,materialEmissive:Uh,materialEnvIntensity:Pc,materialEnvRotation:Uc,materialIOR:sp,materialIridescence:Zh,materialIridescenceIOR:Jh,materialIridescenceThickness:ep,materialLightMap:pp,materialLineDashOffset:dp,materialLineDashSize:op,materialLineGapSize:up,materialLineScale:ap,materialLineWidth:lp,materialMetalness:$h,materialNormal:Wh,materialOpacity:Dh,materialPointSize:cp,materialReference:Kc,materialReflectivity:Gh,materialRefractionRatio:Lc,materialRotation:Xh,materialRoughness:zh,materialSheen:Kh,materialSheenRoughness:Qh,materialShininess:Ph,materialSpecular:Ih,materialSpecularColor:Vh,materialSpecularIntensity:Oh,materialSpecularStrength:kh,materialThickness:rp,materialTransmission:tp,max:eu,maxMipLevel:Wl,mediumpModelViewMatrix:ic,metalness:Hn,min:Jo,mix:gu,mixElement:_u,mod:Ia,modInt:io,modelDirection:Kd,modelNormalMatrix:tc,modelPosition:Yd,modelRadius:ec,modelScale:Zd,modelViewMatrix:sc,modelViewPosition:Jd,modelViewProjection:fp,modelWorldMatrix:Qd,modelWorldMatrixInverse:rc,morphReference:Ip,mrt:mb,mul:Ua,mx_aastep:lN,mx_add:(e,t=yn(0))=>La(e,t),mx_atan2:(e=yn(0),t=yn(1))=>Io(e,t),mx_cell_noise_float:(e=kl())=>Hv(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>yn(e).sub(r).mul(t).add(r),mx_divide:(e,t=yn(1))=>Da(e,t),mx_fractal_noise_float:(e=kl(),t=3,r=2,s=.5,i=1)=>jv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec2:(e=kl(),t=3,r=2,s=.5,i=1)=>Kv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec3:(e=kl(),t=3,r=2,s=.5,i=1)=>Xv(e,bn(t),r,s).mul(i),mx_fractal_noise_vec4:(e=kl(),t=3,r=2,s=.5,i=1)=>Qv(e,bn(t),r,s).mul(i),mx_frame:()=>zb,mx_heighttonormal:(e,t)=>(e=Rn(e),t=yn(t),Ch(e,t)),mx_hsvtorgb:aN,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=yn(1))=>Pa(t,e),mx_modulo:(e,t=yn(1))=>Ia(e,t),mx_multiply:(e,t=yn(1))=>Ua(e,t),mx_noise_float:(e=kl(),t=1,r=0)=>$v(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=kl(),t=1,r=0)=>Wv(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=kl(),t=1,r=0)=>{e=e.convert("vec2|vec3");return Cn(Wv(e),$v(e.add(_n(19,73)))).mul(t).add(r)},mx_place2d:(e,t=_n(.5,.5),r=_n(1,1),s=yn(0),i=_n(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=_n(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=yn(1))=>ou(e,t),mx_ramp4:(e,t,r,s,i=kl())=>{const n=i.x.clamp(),a=i.y.clamp(),o=gu(e,t,n),u=gu(r,s,n);return gu(o,u,a)},mx_ramplr:(e,t,r=kl())=>dN(e,t,r,"x"),mx_ramptb:(e,t,r=kl())=>dN(e,t,r,"y"),mx_rgbtohsv:oN,mx_rotate2d:(e,t)=>{e=_n(e);const r=(t=yn(t)).mul(Math.PI/180);return iy(e,r)},mx_rotate3d:(e,t,r)=>{e=Rn(e),t=yn(t),r=Rn(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=yn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=yn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=kl())=>cN(e,t,r,s,"x"),mx_splittb:(e,t,r,s=kl())=>cN(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:uN,mx_subtract:(e,t=yn(0))=>Pa(e,t),mx_timer:()=>kb,mx_transform_uv:(e=1,t=0,r=kl())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>iN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=kl(),r=_n(1,1),s=_n(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>nN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=kl(),t=1)=>tN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec2:(e=kl(),t=1)=>rN(e.convert("vec2|vec3"),t,bn(1)),mx_worley_noise_vec3:(e=kl(),t=1)=>sN(e.convert("vec2|vec3"),t,bn(1)),negate:zo,neutralToneMapping:mT,nodeArray:nn,nodeImmutable:on,nodeObject:tn,nodeObjectIntent:rn,nodeObjects:sn,nodeProxy:an,nodeProxyIntent:un,normalFlat:_c,normalGeometry:xc,normalLocal:Tc,normalMap:Rh,normalView:Sc,normalViewGeometry:vc,normalWorld:Rc,normalWorldGeometry:Nc,normalize:Ro,not:qa,notEqual:Va,numWorkgroups:BT,objectDirection:zd,objectGroup:va,objectPosition:Wd,objectRadius:jd,objectScale:Hd,objectViewPosition:qd,objectWorldMatrix:$d,oneMinus:$o,or:Ha,orthographicDepthToViewZ:eg,oscSawtooth:(e=kb)=>e.fract(),oscSine:(e=kb)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=kb)=>e.fract().round(),oscTriangle:(e=kb)=>e.add(.5).fract().mul(2).sub(1).abs(),output:oa,outputStruct:lb,overloadingFn:Vb,packHalf2x16:Cb,packSnorm2x16:Eb,packUnorm2x16:wb,parabola:Rb,parallaxDirection:Th,parallaxUV:(e,t)=>e.sub(Th.mul(t)),parameter:(e,t)=>new sb(e,t),pass:(e,t,r)=>new iT(iT.COLOR,e,t,r),passTexture:(e,t)=>new rT(e,t),pcurve:(e,t,r)=>ou(Da(ou(e,t),La(ou(e,t),ou(Pa(1,e),r))),1/t),perspectiveDepthToViewZ:sg,pmremTexture:Vf,pointShadow:pv,pointUV:Cx,pointWidth:da,positionGeometry:uc,positionLocal:lc,positionPrevious:dc,positionView:pc,positionViewDirection:gc,positionWorld:cc,positionWorldDirection:hc,posterize:Yx,pow:ou,pow2:uu,pow3:lu,pow4:du,premultiplyAlpha:Tg,property:Vn,quadBroadcast:g_,quadSwapDiagonal:u_,quadSwapX:a_,quadSwapY:o_,radians:mo,rand:Tu,range:wT,rangeFogFactor:_T,reciprocal:jo,reference:qc,referenceBuffer:jc,reflect:ru,reflectVector:Oc,reflectView:Dc,reflector:e=>new lx(e),refract:yu,refractVector:Vc,refractView:Ic,reinhardToneMapping:oT,remap:Al,remapClamp:El,renderGroup:_a,renderOutput:Fl,rendererReference:el,replaceDefaultUV:function(e,t=null){return Cu(t,{getUV:"function"==typeof e?e:()=>e})},rotate:iy,rotateUV:$b,roughness:Wn,round:qo,rtt:yx,sRGBTransferEOTF:Hu,sRGBTransferOETF:qu,sample:(e,t=null)=>new Nx(e,tn(t)),sampler:e=>(!0===e.isNode?e:Kl(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Kl(e)).convert("samplerComparison"),saturate:fu,saturation:qx,screenCoordinate:dd,screenDPR:od,screenSize:ld,screenUV:ud,select:Eu,setCurrentStack:hn,setName:Bu,shaderStages:oi,shadow:ev,shadowPositionWorld:w_,shapeCircle:xv,sharedUniformGroup:xa,sheen:Xn,sheenRoughness:Kn,shiftLeft:Za,shiftRight:Ja,shininess:aa,sign:ko,sin:Eo,sinc:(e,t)=>Eo(uo.mul(t.mul(e).sub(1))).div(uo.mul(t.mul(e).sub(1))),sinh:wo,skinning:Cp,smoothstep:bu,smoothstepElement:vu,specularColor:sa,specularColorBlended:ia,specularF90:na,spherizeUV:Wb,split:(e,t)=>new yi(tn(e),t),spritesheetUV:jb,sqrt:_o,stack:nb,step:tu,stepElement:Nu,storage:Tp,storageBarrier:()=>IT("storage").toStack(),storageTexture:Ux,string:(e="")=>new vi(e,"string"),struct:(e,t=null)=>{const r=new ab(e,t),s=(...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;eOx(e,t).level(r),texture3DLoad:(...e)=>Ox(...e).setSampler(!1),textureBarrier:()=>IT("texture").toStack(),textureBicubic:Fm,textureBicubicLevel:Bm,textureCubeUV:df,textureLevel:(e,t,r)=>Kl(e,t).level(r),textureLoad:Ql,textureSize:zl,textureStore:(e,t,r)=>{let s;return!0===e.isStorageTextureNode?(s=e.clone(),s.uvNode=t,s.storeNode=r):s=Ux(e,t,r),null!==r&&s.toStack(),s},thickness:pa,time:kb,toneMapping:rl,toneMappingExposure:sl,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>new nT(t,r,tn(s),tn(i),tn(n)),transformDirection:cu,transformNormal:Ec,transformNormalToView:wc,transformedClearcoatNormalView:Bc,transformedNormalView:Cc,transformedNormalWorld:Mc,transmission:ha,transpose:Qo,triNoise3D:Db,triplanarTexture:(...e)=>Xb(...e),triplanarTextures:Xb,trunc:Xo,uint:xn,uintBitsToFloat:e=>new fb(e,"float","uint"),uniform:Sa,uniformArray:td,uniformCubeTexture:(e=kc)=>zc(e),uniformFlow:Mu,uniformGroup:ba,uniformTexture:(e=ql)=>Kl(e),unpackHalf2x16:Lb,unpackNormal:Nh,unpackSnorm2x16:Bb,unpackUnorm2x16:Fb,unpremultiplyAlpha:_g,userData:(e,t,r)=>new Vx(e,t,r),uv:kl,uvec2:Nn,uvec3:En,uvec4:Bn,varying:$u,varyingProperty:kn,vec2:_n,vec3:Rn,vec4:Cn,vectorComponents:ui,velocity:Wx,vertexColor:gg,vertexIndex:hl,vertexStage:Wu,vibrance:jx,viewZToLogarithmicDepth:ig,viewZToOrthographicDepth:Jp,viewZToPerspectiveDepth:tg,viewZToReversedOrthographicDepth:(e,t,r)=>e.add(r).div(r.sub(t)),viewZToReversedPerspectiveDepth:rg,viewport:cd,viewportCoordinate:pd,viewportDepthTexture:Yp,viewportLinearDepth:ug,viewportMipTexture:qp,viewportOpaqueMipTexture:Xp,viewportResolution:md,viewportSafeUV:qb,viewportSharedTexture:eT,viewportSize:hd,viewportTexture:Hp,viewportUV:gd,vogelDiskSample:vx,wgsl:(e,t)=>yT(e,t,"wgsl"),wgslFn:(e,t)=>xT(e,t,"wgsl"),workgroupArray:(e,t)=>new VT("Workgroup",e,t),workgroupBarrier:()=>IT("workgroup").toStack(),workgroupId:FT,workingToColorSpace:Ku,xor:ja});const mN=new rb;class fN extends Ry{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,r){const s=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)s._clearColor.getRGB(mN),mN.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(mN),mN.a=1,n=!0;else if(!0===i.isNode){const u=this.get(e),l=i;mN.copy(s._clearColor);let d=u.backgroundMesh;if(void 0===d){const h=Cn(l).mul(Fx).context({getUV:()=>Lx.mul(Nc),getTextureLevel:()=>Bx}),p=Ld.element(3).element(3).equal(1),g=Da(1,Ld.element(1).element(1)).mul(3),m=p.select(lc.mul(g),lc),f=sc.mul(Cn(m,0));let y=Ld.mul(Cn(f.xyz,1));y=y.setZ(y.w);const b=new vg;function x(){i.removeEventListener("dispose",x),d.material.dispose(),d.geometry.dispose()}b.name="Background.material",b.side=L,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=y,b.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=d=new oe(new ft(1,32,32),b),d.frustumCulled=!1,d.name="Background.mesh",i.addEventListener("dispose",x)}const c=l.getCacheKey();u.backgroundCacheKey!==c&&(u.backgroundMeshNode.node=Cn(l).mul(Fx),u.backgroundMeshNode.needsUpdate=!0,d.material.needsUpdate=!0,u.backgroundCacheKey=c),t.unshift(d,d.geometry,d.material,0,0,null,null)}else o("Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?mN.set(0,0,0,1):"alpha-blend"===a&&mN.set(0,0,0,0),!0===s.autoClear||!0===n){const T=r.clearColorValue;T.r=mN.r,T.g=mN.g,T.b=mN.b,T.a=mN.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(T.r*=T.a,T.g*=T.a,T.b*=T.a),r.depthClearValue=s.getClearDepth(),r.stencilClearValue=s.getClearStencil(),r.clearColor=!0===s.autoClearColor,r.clearDepth=!0===s.autoClearDepth,r.clearStencil=!0===s.autoClearStencil}else r.clearColor=!1,r.clearDepth=!1,r.clearStencil=!1}}let yN=0;class bN{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=yN++}}class xN{constructor(e,t,r,s,i,n,a,o,u,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=l,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new bN(t.name,[]);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class TN{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class _N{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}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 vN{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class NN extends vN{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class SN{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let RN=0;class AN{constructor(e=null){this.id=RN++,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 EN{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class wN{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 CN extends wN{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class MN extends wN{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class BN extends wN{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class FN extends wN{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class LN extends wN{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class PN extends wN{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class UN extends wN{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class DN extends wN{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class IN extends CN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ON extends MN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class VN extends BN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kN extends FN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GN extends LN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zN extends PN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $N extends UN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class WN extends DN{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let HN=0;const qN=new WeakMap,jN=new WeakMap,XN=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),KN=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class QN{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=nb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new AN,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:HN++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&e.blending===tt&&!1===e.alphaToCoverage}createRenderTarget(e,t,r){return new ne(e,t,r)}createCubeRenderTarget(e,t){return new Fg(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=t[0].groupNode;let s,i=r.shared;if(i)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)r+=t.nodeUniform.node.id}else r+=e.nodeUniform.id;const i=this.renderer._currentRenderContext||this.renderer;let n=qN.get(i);void 0===n&&(n=new Map,qN.set(i,n));const a=Vs(r);s=n.get(a),void 0===s&&(s=new bN(e,t),n.set(a,s))}else s=new bN(e,t);return s}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of oi)for(const s in r[e]){const i=r[e][s],n=t[s]||(t[s]=[]);for(const e of i)!1===n.includes(e)&&n.push(e)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(n)}u`:"0u";if("bool"===i)return n?"true":"false";if("color"===i)return`${this.getType("vec3")}( ${KN(n.r)}, ${KN(n.g)}, ${KN(n.b)} )`;const a=this.getTypeLength(i),o=this.getComponentType(i),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==i)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(i)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(i)}()`;throw new Error(`NodeBuilder: Type '${i}' 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 r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new TN(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===R)return"int";if(t===S)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=Ws(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return XN.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof xt||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=nb(this.stack);const e=pn();return this.stacks.push(e),hn(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,hn(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const r=this.getDataFromNode(e,"vertex");let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new TN("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new EN(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new _N(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new vN(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new NN(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let i=1,n=s;for(;void 0!==r[n];)n=s+"_"+i++;i>1&&(e.name=n,d(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${n}'.`)),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new SN("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!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),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new bT,r=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=r,t}flowShaderNode(e){const t=e.layout,r={[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)r[e.name]=new sb(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new AN,this.stack=nb();for(const r of ai)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){d("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){d("Abstract function.")}getVaryings(){d("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e,t=!1){const r=[],s=this.vars[e];if(void 0!==s)for(const e of s)r.push(`${this.getVar(e.type,e.name,e.count)};`);return r.join(t?"\n":"\n\t")}getUniforms(){d("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}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(){d("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 r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}prebuild(){const{object:e,renderer:t,material:r}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:o('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),r&&r.contextNode&&(!0===r.contextNode.isContextNode?this.context={...this.context,...r.contextNode.getFlowContextData()}:o('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==r){let e=t.library.fromMaterial(r);null===e&&(o(`NodeBuilder: Material "${r.type}" is not compatible.`),e=new vg),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"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 ai){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of oi){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this);await Tt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=jN.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const r=this.getSharedDataFromNode(e);let s=r.cache;if(void 0===s){if("float"===t||"int"===t||"uint"===t)s=new IN(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)s=new ON(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)s=new VN(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)s=new kN(e);else if("color"===t)s=new GN(e);else if("mat2"===t)s=new zN(e);else if("mat3"===t)s=new $N(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);s=new WN(e)}r.cache=s}return s}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${_t} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Ys(this.object).useVelocity}}class YN{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderId:0,frameId:0},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateBeforeMap,r);if(t.frameId!==this.frameId){const r=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=r)}}else if(t===ri.RENDER){const t=this._getMaps(this.updateBeforeMap,r);if(t.renderId!==this.renderId){const r=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=r)}}else t===ri.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateAfterMap,r);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateAfterMap,r);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===ri.FRAME){const t=this._getMaps(this.updateMap,r);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===ri.RENDER){const t=this._getMaps(this.updateMap,r);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ri.OBJECT&&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 ZN{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}ZN.isNodeFunctionInput=!0;class JN extends gv{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class eS extends gv{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:v_(this.light),lightColor:e}}}class tS extends gv{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=x_(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Sa(new e).setGroup(_a)}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:r,lightDirectionNode:s}=this,i=Rc.dot(s).mul(.5).add(.5),n=gu(r,t,i);e.context.irradiance.addAssign(n)}}class rS extends gv{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Sa(0).setGroup(_a),this.penumbraCosNode=Sa(0).setGroup(_a),this.cutoffDistanceNode=Sa(0).setGroup(_a),this.decayExponentNode=Sa(0).setGroup(_a),this.colorNode=Sa(this.color).setGroup(_a)}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:r,penumbraCosNode:s}=this;return bu(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=b_(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(v_(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=mv({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=Kl(i.map,h.xy).onRenderUpdate(()=>i.map)),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class sS extends rS{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);s=Kl(r,_n(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}class iS extends gv{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new r);this.lightProbe=td(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=pN(Rc,this.lightProbe);e.context.irradiance.addAssign(t)}}const nS=cn(([e,t])=>{const r=e.abs().sub(t);return Go(eu(r,0)).add(Jo(eu(r.x,r.y),0))});class aS extends rS{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=yn(0),r=this.penumbraCosNode,s=y_(this.light).mul(e.context.positionWorld||cc);return gn(s.w.greaterThan(0),()=>{const e=s.xyz.div(s.w),i=nS(e.xy.sub(_n(.5)),_n(.5)),n=Da(-1,Pa(1,Uo(r)).sub(1));t.assign(fu(i.mul(-2).mul(n)))}),t}}const oS=new a,uS=new a;let lS=null;class dS extends gv{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Sa(new r).setGroup(_a),this.halfWidth=Sa(new r).setGroup(_a),this.updateType=ri.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;uS.identity(),oS.copy(t.matrixWorld),oS.premultiply(r),uS.extractRotation(oS),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(uS),this.halfHeight.value.applyMatrix4(uS)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Kl(lS.LTC_FLOAT_1),r=Kl(lS.LTC_FLOAT_2)):(t=Kl(lS.LTC_HALF_1),r=Kl(lS.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:__(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){lS=e}}class cS{parseFunction(){d("Abstract function.")}}class hS{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){d("Abstract function.")}}hS.isNodeFunction=!0;const pS=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,gS=/[a-z_0-9]+/gi,mS="#pragma main";class fS extends hS{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(mS),r=-1!==t?e.slice(t+12):e,s=r.match(pS);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=gS.exec(i));)n.push(a);const o=[];let u=0;for(;u{let r=this._createNodeBuilder(e,e.material);try{t?await r.buildAsync():r.build()}catch(s){r=this._createNodeBuilder(e,new vg),t?await r.buildAsync():r.build(),o("TSL: "+s)}return r})().then(e=>(s=this._createNodeBuilderState(e),i.set(n,s),s.usedTimes++,r.nodeBuilderState=s,s));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(r){t=this._createNodeBuilder(e,new vg),t.build();let s=r.stackTrace;!s&&r.stack&&(s=new Is(r.stack)),o("TSL: "+r,s)}s=this._createNodeBuilderState(t),i.set(n,s)}}s.usedTimes++,r.nodeBuilderState=s}return s}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 r=this.getForRenderCacheKey(e),s=this.nodeBuilderCache.get(r);return void 0!==s?(s.usedTimes++,t.nodeBuilderState=s,s):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let r=t.nodeBuilderState;if(void 0===r){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),r=this._createNodeBuilderState(s),t.nodeBuilderState=r}return r}_createNodeBuilderState(e){return new xN(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const r=this.get(e);r.environmentNode&&(t=r.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const r=this.get(e);r.backgroundNode&&(t=r.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){bS[0]=e,bS[1]=t;const r=this.renderer.info.calls,s=this.callHashCache.get(bS)||{};if(s.callId!==r){const i=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&xS.push(t.getCacheKey(!0)),i&&xS.push(i.getCacheKey()),n&&xS.push(n.getCacheKey()),xS.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),xS.push(this.renderer.shadowMap.enabled?1:0),xS.push(this.renderer.shadowMap.type),s.callId=r,s.cacheKey=ks(xS),this.callHashCache.set(bS,s),xS.length=0}return bS[0]=null,bS[1]=null,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),r=e.background;if(r){const s=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,()=>{if(!0===r.isCubeTexture||r.mapping===ce||r.mapping===he||r.mapping===Ee){if(e.backgroundBlurriness>0||r.mapping===Ee)return Vf(r);{let e;return e=!0===r.isCubeTexture?$c(r):Kl(r),Ig(e)}}if(!0===r.isTexture)return Kl(r,ud.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&o("WebGPUNodes: Unsupported background configuration.",r)},s);t.backgroundNode=i,t.background=r,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(e){const t=this.get(e),r=e.fog;if(r){if(t.fog!==r){const e=this.getCacheNode("fog",r,()=>{if(r.isFogExp2){const e=qc("color","color",r).setGroup(_a),t=qc("density","float",r).setGroup(_a);return ST(e,vT(t))}if(r.isFog){const e=qc("color","color",r).setGroup(_a),t=qc("near","float",r).setGroup(_a),s=qc("far","float",r).setGroup(_a);return ST(e,_T(t,s))}o("Renderer: Unsupported fog configuration.",r)});t.fogNode=e,t.fog=r}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),r=e.environment;if(r){if(t.environment!==r){const e=this.getCacheNode("environment",r,()=>!0===r.isCubeTexture?$c(r):!0===r.isTexture?Kl(r):void o("Nodes: Unsupported environment configuration.",r));t.environmentNode=e,t.environment=r}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Kl(e,ud).depth(sd("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Kl(e,ud).renderOutput(t.toneMapping,t.currentColorSpace)}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new YN,this.nodeBuilderCache=new Map,this.cacheLib={}}}const _S=new ut;class vS{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,r){const s=e.length;for(let i=0;iFl(e,i.toneMapping,i.outputColorSpace)}),LS.set(r,n))}else n=r;i.contextNode=n,i.setRenderTarget(t.renderTarget),t.rendercall(),i.contextNode=r}i.setRenderTarget(o),i._setXRLayerSize(a.x,a.y),this.isPresenting=n}getSession(){return this._session}async setSession(e){const t=this._renderer,r=t.backend;this._gl=t.getContext();const s=this._gl,i=s.getContextAttributes();if(this._session=e,null!==e){if(!0===r.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await r.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let r=null,n=null,a=null;t.depth&&(a=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,r=t.stencil?qe:He,n=t.stencil?Ze:S);const o={colorFormat:s.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(o),l=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,c=new Z(u.textureWidth,u.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,r,d);if(this._xrRenderTarget=new MS(u.textureWidth,u.textureHeight,{format:Ae,type:Ve,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.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 fe({color:16777215,side:"cylinder"===e.type?L:St}),e.plane.material.blending=Rt,e.plane.material.blendEquation=it,e.plane.material.blendSrc=At,e.plane.material.blendDst=At,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{const r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,s,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new MS(i.framebufferWidth,i.framebufferHeight,{format:Ae,type:Ve,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=-5&i.layers.mask,a.layers.mask=-3&i.layers.mask;const o=e.parent,u=i.cameras;US(i,o);for(let e=0;e=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function VS(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 kS(e,t){if(void 0===t)return;const r=this._cameraXR,i=this._renderer,n=i.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views;null!==this._glBaseLayer&&n.setXRTarget(a.framebuffer);let t=!1;e.length!==r.cameras.length&&(r.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const s=this._renderLists.get(e,t),i=this._renderContexts.get(this._renderTarget,this._mrt),n=e.overrideMaterial||r.material,a=this._objects.get(r,n,e,t,s.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:u}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:u}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new TS(this,r),this._animation=new xy(this,this._nodes,this.info),this._attributes=new By(r,this.info),this._background=new fN(this,this._nodes),this._geometries=new Uy(this._attributes,this.info),this._textures=new tb(this,r,this.info),this._pipelines=new zy(r,this._nodes,this.info),this._bindings=new $y(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Sy(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Ky(this.lighting),this._bundles=new RS,this._renderContexts=new Jy(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,u=this._compilationPromises;null===r&&(r=e);const l=!0===e.isScene?e:!0===r.isScene?r:zS,d=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(d,this._mrt),h=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,s.renderId++,s.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new vS),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const g=this._renderLists.get(l,t);if(g.begin(),this._projectObject(e,t,0,g,c.clippingContext),r!==e&&r.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&g.pushLight(e)}),g.finish(),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;r!==e?this._background.update(r,g,c):this._background.update(l,g,c);const m=g.opaque,f=g.transparent,y=g.transparentDoublePass,b=g.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,l,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,l,b),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=u;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,this._geometries.updateForRender(t),await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const r=[];this._pipelines.getForRender(t,r),r.length>0&&await Promise.all(r),this._nodes.updateAfter(t),await Tt()}}async renderAsync(e,t){v('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){o("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=nc,t.modelNormalViewMatrix=ac):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===nc&&e.modelNormalViewMatrix===ac}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return v('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}`),o(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i,a),u=this.backend.get(o),l=s.version!==u.version;if(l||void 0===u.bundleGPU){this.backend.beginBundle(a),(void 0===u.renderObjects||l)&&(u.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:d,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,i,t,r),!0===this.transparent&&d.length>0&&this._renderTransparents(d,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t{u.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(u)};u.addEventListener("dispose",e),this._frameBufferTargets.set(u,l)}const d=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==d?l.setSize(d.width,d.height,d.depth):l.setSize(i,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:u._viewport,h=this._outputRenderTarget?this._outputRenderTarget.scissor:u._scissor,g=this._outputRenderTarget?1:u._pixelRatio,f=this._outputRenderTarget?this._outputRenderTarget.scissorTest:u._scissorTest;return l.viewport.copy(c),l.scissor.copy(h),l.viewport.multiplyScalar(g),l.scissor.multiplyScalar(g),l.scissorTest=f,l.multiview=null!==d&&d.multiview,l.resolveDepthBuffer=null===d||d.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==d&&d._autoAllocateDepthBuffer,l}_renderScene(e,t,r=!0){if(!0===this._isDeviceLost)return;const s=r?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,u=this._handleObjectFunction;this._callDepth++;const l=!0===e.isScene?e:zS,d=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let p;if(null!==s?(p=s,this.setRenderTarget(p)):p=d,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p);const m=this.xr;if(!1===m.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const r=this.coordinateSystem;if(t.coordinateSystem!==r){if(t.coordinateSystem=r,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=r;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,x=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,x=1),this.getDrawingBufferSize($S),WS.set(0,0,$S.width,$S.height);const T=void 0===y.minDepth?0:y.minDepth,_=void 0===y.maxDepth?1:y.maxDepth;g.viewportValue.copy(y).multiplyScalar(x).floor(),g.viewportValue.width>>=h,g.viewportValue.height>>=h,g.viewportValue.minDepth=T,g.viewportValue.maxDepth=_,g.viewport=!1===g.viewportValue.equals(WS),g.scissorValue.copy(b).multiplyScalar(x).floor(),g.scissor=f._scissorTest&&!1===g.scissorValue.equals(WS),g.scissorValue.width>>=h,g.scissorValue.height>>=h,g.clippingContext||(g.clippingContext=new vS),g.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const v=t.isArrayCamera?qS:HS;t.isArrayCamera||(jS.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(jS,t.coordinateSystem,t.reversedDepth));const N=this._renderLists.get(e,t);if(N.begin(),this._projectObject(e,t,0,N,g.clippingContext),N.finish(),!0===this.sortObjects&&N.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,h);const e=this._textures.get(p);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=$S.width,g.height=$S.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=h,g.height>>=h,g.activeCubeFace=c,g.activeMipmapLevel=h,g.occlusionQueryCount=N.occlusionQueryCount,g.scissorValue.max(XS.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(l,N,g),g.camera=t,this.backend.beginRender(g);const{bundles:S,lightsNode:R,transparentDoublePass:A,transparent:E,opaque:w}=N;return S.length>0&&this._renderBundles(S,l,R),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,R),!0===this.transparent&&E.length>0&&this._renderTransparents(E,A,t,l,R),this.backend.finishRender(g),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=u,this._callDepth--,null!==s&&(this.setRenderTarget(d,c,h),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_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 r,s=this._quadCache.get(e.texture);if(void 0===s){r=new gx(new vg),r.name="Output Color Transform",r.material.name="outputColorTransform",r.material.fragmentNode=this._nodes.getOutputNode(e.texture),s={quad:r,cacheKey:t},this._quadCache.set(e.texture,s);const i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",i)};e.texture.addEventListener("dispose",i)}else r=s.quad,s.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,s.cacheKey=t);const i=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(r,r.camera,!1),this.autoClear=i,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,r=0,s=-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(r%4!=0||s>0&&s%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,r,s)}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,r){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,r)}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,r)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,r,s){this._canvasTarget.setScissor(e,t,r,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,r,s,i=0,n=1){this._canvasTarget.setViewport(e,t,r,s,i,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.get(s,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer;const t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),!0===s.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){v('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,r)}async clearColorAsync(){v('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){v('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){v('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==m,t=this.currentColorSpace!==p.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:m}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:p.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!0===this._initialized){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}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 d("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.deleteForCompute(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s,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 v('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){v('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),r=this._renderContexts.get(e);r.textures=t.textures,r.depthTexture=t.depthTexture,r.width=t.width,r.height=t.height,r.renderTarget=e,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,this.backend.initRenderTarget(r)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=XS.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void o("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=XS.copy(t).floor()}else t=XS.set(0,0,e.image.width,e.image.height);let r,s=this._currentRenderContext;null!==s?r=s.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),null!==r&&(this._textures.updateRenderTarget(r),s=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,s,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(e,t,r,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)r=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?qS:HS;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&XS.setFromMatrixPosition(e.matrixWorld).applyMatrix4(jS);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,XS.z,null,i)}}else if(e.isLineLoop)o("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?qS:HS;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),XS.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(jS)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=L;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=St;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=P}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n(t.not().discard(),e))(u)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),r={version:t,colorNode:u,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,r)}return r}renderObject(e,t,r,s,i,n,a,o=null,u=null){let l,d,c,h,p=!1;if(e.onBeforeRender(this,t,r,s,i,n),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,l=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,h=t.overrideMaterial.side,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:r,positionNode:s}=this._getShadowNodes(i);this.shadowMap.type===pt?e.side=null!==i.shadowSide?i.shadowSide:i.side:e.side=null!==i.shadowSide?i.shadowSide:KS[i.side],null!==t&&(e.colorNode=t),null!==r&&(e.depthNode=r),null!==s&&(e.positionNode=s)}i=e}!0===i.transparent&&i.side===P&&!1===i.forceSinglePass?(i.side=L,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=St,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=P):this._handleObjectFunction(e,i,t,r,a,n,o,u),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=h),e.onAfterRender(this,t,r,s,i,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);if(u.drawRange=e.geometry.drawRange,u.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(u);l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),this._pipelines.isReady(u)&&(this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u))}_createObjectPipeline(e,t,r,s,i,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:r,camera:s,lightsNode:i,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class YS{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class ZS extends YS{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(My-e%My)%My;var e}get buffer(){return this._buffer}update(){return!0}}class JS extends ZS{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let eR=0;class tR extends JS{constructor(e,t){super("UniformBuffer_"+eR++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class rR extends JS{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const r=this.updateRanges,s={start:e.offset,count:e.itemSize};r.push(s),this._updateRangeCache.set(t,s)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let aR=0;class oR extends nR{constructor(e,t){super(e,t),this.id=aR++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class uR extends oR{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class lR extends uR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class dR extends uR{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const cR={bitcast_int_uint:new fT("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new fT("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},hR={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},pR={low:"lowp",medium:"mediump",high:"highp"},gR={swizzleAssign:!0,storageBuffer:!1},mR={perspective:"smooth",linear:"noperspective"},fR={centroid:"centroid"},yR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class bR extends QN{constructor(e,t){super(e,t,new yS),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==T}_include(e){const t=cR[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==cR[e]&&this._include(e),hR[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?We:$e;2===s?n=i?je:$:3===s?n=i?Ke:Xe:4===s&&(n=i?Lt:Ae);const a={Float32Array:K,Uint8Array:Ve,Uint16Array:Ge,Uint32Array:S,Int8Array:Oe,Int16Array:ke,Int32Array:R,Uint8ClampedArray:Ve},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s0?i:"";t=`${r.name} {\n\t${s} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===s[t]){const e=this.uniformGroups[t];if(void 0!==e){const r=[];for(const t of e.uniforms){const e=t.getType(),s=this.getVectorType(e),i=t.nodeUniform.node.precision;let n=`${s} ${t.name};`;null!==i&&(n=pR[i]+" "+n),r.push("\t"+n)}s[t]=r}}i=!0}if(!i){const s=e.node.precision;null!==s&&(t=pR[s]+" "+t),t="uniform "+t,r.push(t)}}let i="";for(const e in s){const t=s[e];i+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==R){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return 0===s.length&&s.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${mR[s.interpolationType]||s.interpolationType} ${fR[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${mR[e.interpolationType]||e.interpolationType} ${fR[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){o("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){o("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){o("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,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.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 r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=gR[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}gR[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 r=0;r0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${s.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${s.result};`)))}const n=e[t];if(n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new uR(i.name,i.node,s),u.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new lR(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new dR(i.name,i.node,s),u.push(a);else if("buffer"===t){i.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let r=t.buffer;void 0===r&&(e.name=`NodeBuffer_${e.id}`,r=new tR(e,s),r.name=e.name,t.buffer=r),u.push(r),a=r}else{let e=this.uniformGroups[o];void 0===e?(e=new iR(o,s),this.uniformGroups[o]=e,u.push(e)):-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}}let xR=null,TR=null;class _R{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Pt.RENDER]:null,[Pt.COMPUTE]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),r=this.renderer.info.frame;let s;s=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+r}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:")?Pt.COMPUTE:Pt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void v("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return xR=xR||new t,this.renderer.getDrawingBufferSize(xR)}setScissorTest(){}getClearColor(){const e=this.renderer;return TR=TR||new rb,e.getClearColor(TR),TR.getRGB(TR),TR}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Ut(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${_t} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let vR,NR,SR=0;class RR{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 AR{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===R,id:SR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new RR(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),d=new Uint8Array(new ArrayBuffer(l)),t.buffer=d.buffer}else d=new Uint8Array(t);return n.bindBuffer(n.COPY_READ_BUFFER,u),n.getBufferSubData(n.COPY_READ_BUFFER,r,d),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:d.buffer}_createBuffer(e,t,r,s){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,r,s),e.bindBuffer(t,null),i}}class ER{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;vR={[it]:e.FUNC_ADD,[It]:e.FUNC_SUBTRACT,[Dt]:e.FUNC_REVERSE_SUBTRACT},NR={[At]:e.ZERO,[Ht]:e.ONE,[Wt]:e.SRC_COLOR,[rt]:e.SRC_ALPHA,[$t]:e.SRC_ALPHA_SATURATE,[zt]:e.DST_COLOR,[Gt]:e.DST_ALPHA,[kt]:e.ONE_MINUS_SRC_COLOR,[st]:e.ONE_MINUS_SRC_ALPHA,[Vt]:e.ONE_MINUS_DST_COLOR,[Ot]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),r=e.getParameter(e.VIEWPORT);this.currentScissor=(new s).fromArray(t),this.currentViewport=(new s).fromArray(r),this._tempVec4=new s}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;e!==qt?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===jt?t.cullFace(t.BACK):e===Xt?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:r}=this;e!==t&&(r.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,r){const s=this.gl,i=this.backend.drawBuffersIndexedExt;if(i)for(let n=0;n0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()})}}let CR,MR,BR,FR=!1;class LR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===FR&&(this._init(),FR=!0)}_init(){const e=this.gl;CR={[kr]:e.REPEAT,[_e]:e.CLAMP_TO_EDGE,[Vr]:e.MIRRORED_REPEAT},MR={[B]:e.NEAREST,[Gr]:e.NEAREST_MIPMAP_NEAREST,[bt]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[yt]:e.LINEAR_MIPMAP_NEAREST,[Y]:e.LINEAR_MIPMAP_LINEAR},BR={[Hr]:e.NEVER,[Wr]:e.ALWAYS,[E]:e.LESS,[w]:e.LEQUAL,[$r]:e.EQUAL,[M]:e.GEQUAL,[C]:e.GREATER,[zr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!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,r}getInternalFormat(e,t,r,s,i,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];d("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let u=null;s&&(u=o.get("EXT_texture_norm16"),u||d("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(r===a.FLOAT&&(l=a.R32F),r===a.HALF_FLOAT&&(l=a.R16F),r===a.UNSIGNED_BYTE&&(l=a.R8),r===a.BYTE&&(l=a.R8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.R16_EXT),r===a.SHORT&&u&&(l=u.R16_SNORM_EXT)),t===a.RED_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.R8UI),r===a.UNSIGNED_SHORT&&(l=a.R16UI),r===a.UNSIGNED_INT&&(l=a.R32UI),r===a.BYTE&&(l=a.R8I),r===a.SHORT&&(l=a.R16I),r===a.INT&&(l=a.R32I)),t===a.RG&&(r===a.FLOAT&&(l=a.RG32F),r===a.HALF_FLOAT&&(l=a.RG16F),r===a.UNSIGNED_BYTE&&(l=a.RG8),r===a.BYTE&&(l=a.RG8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RG16_EXT),r===a.SHORT&&u&&(l=u.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RG8UI),r===a.UNSIGNED_SHORT&&(l=a.RG16UI),r===a.UNSIGNED_INT&&(l=a.RG32UI),r===a.BYTE&&(l=a.RG8I),r===a.SHORT&&(l=a.RG16I),r===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGB32F),r===a.HALF_FLOAT&&(l=a.RGB16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8:a.RGB8),r===a.BYTE&&(l=a.RGB8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGB16_EXT),r===a.SHORT&&u&&(l=u.RGB16_SNORM_EXT),r===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),r===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),r===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGB8UI),r===a.UNSIGNED_SHORT&&(l=a.RGB16UI),r===a.UNSIGNED_INT&&(l=a.RGB32UI),r===a.BYTE&&(l=a.RGB8I),r===a.SHORT&&(l=a.RGB16I),r===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?qr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGBA32F),r===a.HALF_FLOAT&&(l=a.RGBA16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8_ALPHA8:a.RGBA8),r===a.BYTE&&(l=a.RGBA8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGBA16_EXT),r===a.SHORT&&u&&(l=u.RGBA16_SNORM_EXT),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),r===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),r===a.UNSIGNED_INT&&(l=a.RGBA32UI),r===a.BYTE&&(l=a.RGBA8I),r===a.SHORT&&(l=a.RGBA16I),r===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(r===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),r===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),r===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&r===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,{state:n}=this.backend,a=p.getPrimaries(p.workingColorSpace),o=t.colorSpace===T?null:p.getPrimaries(t.colorSpace),u=t.colorSpace===T||a===o?r.NONE:r.BROWSER_DEFAULT_WEBGL;n.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,u),r.texParameteri(e,r.TEXTURE_WRAP_S,CR[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,CR[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,CR[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,MR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,d=t.minFilter===le&&l?Y:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,MR[d]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,BR[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===B)return;if(t.minFilter!==bt&&t.minFilter!==Y)return;if(t.type===K&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i})}createTexture(e,t){const{gl:r,backend:s}=this,{levels:i,width:n,height:a,depth:o}=t,u=s.utils.convert(e.format,e.colorSpace),l=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.normalized,e.colorSpace,e.isVideoTexture),c=r.createTexture(),h=this.getGLTextureType(e);s.state.bindTexture(h,c),this.setTextureParameters(h,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,i,d,n,a,o):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,i,d,n,a,o):e.isVideoTexture||r.texStorage2D(h,i,d,n,a),s.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{state:i}=s,{textureGPU:n,glTextureType:a,glFormat:o,glType:u}=s.get(t),{width:l,height:d}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(a,n),i.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(a,0,0,0,l,d,o,u,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t0){const t=jr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function PR(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 UR{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 DR{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 r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.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 IR={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 OR{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:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;sthis.maxQueries)return v(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){o("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){o("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,r]of this.queryOffsets){if("ended"===this.queryStates.get(r)){const s=this.queries[r];e.set(t,this.resolveQuery(s))}}if(0===e.size)return this.lastValue;const t={},r=[];for(const[s,i]of e){const e=s.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===r.includes(n)&&r.push(n),void 0===t[n]&&(t[n]=0);const a=await i;this.timestamps.set(s,a),t[n]+=a}const s=t[r[r.length-1]];return this.lastValue=s,this.frames=r,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return o("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 r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){o("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class GR extends _R{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,r={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new UR(this),this.capabilities=new DR(this),this.attributeUtils=new AR(this),this.textureUtils=new LR(this),this.bufferRenderer=new OR(this),this.state=new ER(this),this.utils=new wR(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:(d("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 c}async getArrayBufferAsync(e,t=null,r=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,r,s)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&d("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 kR(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.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,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.scissor(0,0,e,r)}this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e{let a=0;for(let t=0;t1?t.renderInstances(r,s,i):t.render(r,s)}draw(e){const{object:t,pipeline:r,material:s,context:i,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(r),{gl:o,state:u}=this,l=this.get(i),d=e.getDrawParameters();if(null===d)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;u.setMaterial(s,c,n),null!==i.mrt&&null!==i.textures&&u.setMRTBlending(i.textures,i.mrt,s),u.useProgram(a);const h=e.getAttributes(),p=this.get(h);let g=p.vaoGPU;if(void 0===g){const e=this._getVaoKey(h);g=this.vaoCache[e],void 0===g&&(g=this._createVao(h),this.vaoCache[e]=g,p.vaoGPU=g)}const m=e.getIndex(),f=null!==m?this.get(m).bufferGPU:null;u.setVertexState(g,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===s.wireframe?(u.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:x,instanceCount:T}=d;let{firstVertex:_}=d;if(b.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);b.index=m.count,b.type=e.type}else b.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()});return void t.push(i)}this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(e,t,r){if(this.renderer.debug.checkShaderErrors){const s=this.gl,i=(s.getProgramInfoLog(e)||"").trim();if(!1===s.getProgramParameter(e,s.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(s,e,r,t);else{const n=this._getShaderErrors(s,r,"vertex"),a=this._getShaderErrors(s,t,"fragment");o("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+n+"\n"+a)}else""!==i&&d("WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;eIR[t]===e),r=this.extensions;for(let e=0;e1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=Zy(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const zR="point-list",$R="line-list",WR="line-strip",HR="triangle-list",qR="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},jR="never",XR="less",KR="equal",QR="less-equal",YR="greater",ZR="not-equal",JR="greater-equal",eA="always",tA="store",rA="load",sA="clear",iA="ccw",nA="cw",aA="none",oA="back",uA="uint16",lA="uint32",dA="r8unorm",cA="r8snorm",hA="r8uint",pA="r8sint",gA="r16uint",mA="r16sint",fA="r16float",yA="rg8unorm",bA="rg8snorm",xA="rg8uint",TA="rg8sint",_A="r16unorm",vA="r16snorm",NA="r32uint",SA="r32sint",RA="r32float",AA="rg16uint",EA="rg16sint",wA="rg16float",CA="rgba8unorm",MA="rgba8unorm-srgb",BA="rgba8snorm",FA="rgba8uint",LA="rgba8sint",PA="bgra8unorm",UA="bgra8unorm-srgb",DA="rg16unorm",IA="rg16snorm",OA="rgb9e5ufloat",VA="rgb10a2unorm",kA="rg11b10ufloat",GA="rg32uint",zA="rg32sint",$A="rg32float",WA="rgba16uint",HA="rgba16sint",qA="rgba16float",jA="rgba16unorm",XA="rgba16snorm",KA="rgba32uint",QA="rgba32sint",YA="rgba32float",ZA="depth16unorm",JA="depth24plus",eE="depth24plus-stencil8",tE="depth32float",rE="depth32float-stencil8",sE="bc1-rgba-unorm",iE="bc1-rgba-unorm-srgb",nE="bc2-rgba-unorm",aE="bc2-rgba-unorm-srgb",oE="bc3-rgba-unorm",uE="bc3-rgba-unorm-srgb",lE="bc4-r-unorm",dE="bc4-r-snorm",cE="bc5-rg-unorm",hE="bc5-rg-snorm",pE="bc6h-rgb-ufloat",gE="bc6h-rgb-float",mE="bc7-rgba-unorm",fE="bc7-rgba-unorm-srgb",yE="etc2-rgb8unorm",bE="etc2-rgb8unorm-srgb",xE="etc2-rgb8a1unorm",TE="etc2-rgb8a1unorm-srgb",_E="etc2-rgba8unorm",vE="etc2-rgba8unorm-srgb",NE="eac-r11unorm",SE="eac-r11snorm",RE="eac-rg11unorm",AE="eac-rg11snorm",EE="astc-4x4-unorm",wE="astc-4x4-unorm-srgb",CE="astc-5x4-unorm",ME="astc-5x4-unorm-srgb",BE="astc-5x5-unorm",FE="astc-5x5-unorm-srgb",LE="astc-6x5-unorm",PE="astc-6x5-unorm-srgb",UE="astc-6x6-unorm",DE="astc-6x6-unorm-srgb",IE="astc-8x5-unorm",OE="astc-8x5-unorm-srgb",VE="astc-8x6-unorm",kE="astc-8x6-unorm-srgb",GE="astc-8x8-unorm",zE="astc-8x8-unorm-srgb",$E="astc-10x5-unorm",WE="astc-10x5-unorm-srgb",HE="astc-10x6-unorm",qE="astc-10x6-unorm-srgb",jE="astc-10x8-unorm",XE="astc-10x8-unorm-srgb",KE="astc-10x10-unorm",QE="astc-10x10-unorm-srgb",YE="astc-12x10-unorm",ZE="astc-12x10-unorm-srgb",JE="astc-12x12-unorm",ew="astc-12x12-unorm-srgb",tw="clamp-to-edge",rw="repeat",sw="mirror-repeat",iw="linear",nw="nearest",aw="zero",ow="one",uw="src",lw="one-minus-src",dw="src-alpha",cw="one-minus-src-alpha",hw="dst",pw="one-minus-dst",gw="dst-alpha",mw="one-minus-dst-alpha",fw="src-alpha-saturated",yw="constant",bw="one-minus-constant",xw="add",Tw="subtract",_w="reverse-subtract",vw="min",Nw="max",Sw=0,Rw=15,Aw="keep",Ew="zero",ww="replace",Cw="invert",Mw="increment-clamp",Bw="decrement-clamp",Fw="increment-wrap",Lw="decrement-wrap",Pw="storage",Uw="read-only-storage",Dw="write-only",Iw="read-only",Ow="read-write",Vw="non-filtering",kw="comparison",Gw="float",zw="unfilterable-float",$w="depth",Ww="sint",Hw="uint",qw="2d",jw="3d",Xw="2d",Kw="2d-array",Qw="cube",Yw="3d",Zw="all",Jw="vertex",eC="instance",tC={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"},rC={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class sC extends nR{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class iC extends ZS{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let nC=0;class aC extends iC{constructor(e,t){super("StorageBuffer_"+nC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ii.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class oC extends Ry{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:iw}),this.flipYSampler=e.createSampler({minFilter:nw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const r=`${e}-${t=t||"2d-array"}`;let s=this.transferPipelines[r];return void 0===s&&(s=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[r]=s),s}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.device.createTexture({size:{width:i,height:n},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(s,e.textureBindingViewDimension),u=this.getTransferPipeline(s,a.textureBindingViewDimension),l=this.device.createCommandEncoder({}),d=(e,t,r,s,i,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),u=l.beginRenderPass({colorAttachments:[{view:s.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:i,arrayLayerCount:1}),loadOp:sA,storeOp:tA}]});u.setPipeline(e),u.setBindGroup(0,o),u.draw(3,1,0,r),u.end()};d(o,e,r,a,0,!1),d(u,a,0,e,r,!0),this.device.queue.submit([l.finish()]),a.destroy()}generateMipmaps(e,t=null){const r=this.get(e),s=r.layers||this._mipmapCreateBundles(e),i=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(i,s),null===t&&this.device.queue.submit([i.finish()]),r.layers=s}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",r=this.getTransferPipeline(e.format,t),s=r.getBindGroupLayout(0),i=[];for(let n=1;n0)for(let t=0,n=s.length;t0){for(const s of e.layerUpdates)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);e.clearLayerUpdates()}else for(let s=0;s0)for(let t=0,n=s.length;t{const t=e.changedElements;for(const e of r)t.includes(e.image)&&(e.needsUpdate=!0)}}dispose(){this._samplerCache.clear(),this._htmlTextures.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new N;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,format:e}),this.defaultTexture[e]=t=r}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const r=new U;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=r}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,r){const s=e.images,i=e.mipmaps;for(let n=0;n<6;n++){const a=s[n],o=!0===e.flipY?lC[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha);for(let s=0;s0?e.width:r.size.width,l=a>0?e.height:r.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:n},{width:u,height:l,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new oC(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},u,{offset:e.width*e.height*l*n,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r){const s=this.backend.device,i=this._getBlockData(r.format),n=r.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,pC=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,gC={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",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 mC extends hS{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(hC);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=pC.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class fC extends cS{parseFunction(e){return new mC(e)}}const yC={[ii.READ_ONLY]:"read",[ii.WRITE_ONLY]:"write",[ii.READ_WRITE]:"read_write"},bC={[kr]:"repeat",[_e]:"clamp",[Vr]:"mirror"},xC={vertex:qR.VERTEX,fragment:qR.FRAGMENT,compute:qR.COMPUTE},TC={instance:!0,swizzleAssign:!1,storageBuffer:!0},_C={"^^":"tsl_xor"},vC={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},NC={},SC={tsl_xor:new fT("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new fT("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new fT("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new fT("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new fT("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new fT("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new fT("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new fT("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new fT("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new fT("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new fT("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 fT("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new fT("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new fT("\nfn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},RC={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let AC="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(AC+="diagnostic( off, derivative_uniformity );\n");class EC extends QN{constructor(e,t){super(e,t,new fC),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${bC[e.wrapS]}S_${bC[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let r=NC[t];if(void 0===r){const s=[],i=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===kr?(s.push(SC.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===_e?(s.push(SC.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Vr?(s.push(SC.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,d(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",NC[t]=r=new fT(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Uu(new wl(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Uu(new wl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Uu(new wl("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2(${s}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${r} ), ${o}, u32( ${n} ), u32( ${i} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${r} ), ${o}, u32( ${i} ) )`)}generateTextureLod(e,t,r,s,i,n="0u"){if(!0===e.isCubeTexture){i&&(r=`${r} + vec3(${i})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}(${i}) / ${u}( ${o} )`);return r=`${u}( clamp( floor( ${a}( ${r} ) * ${u}( ${o} ) ), ${`${u}( 0 )`}, ${`${u}( ${o} - ${"vec3"===u?"vec3( 1, 1, 1 )":"vec2( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,r,n,s,null)}generateStorageTextureLoad(e,t,r,s,i,n){let a;return n&&(r=`${r} + ${n}`),a=i?`textureLoad( ${t}, ${r}, ${i} )`:`textureLoad( ${t}, ${r} )`,a}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0u"),n&&(r=`${r} + ${n}`),i?a=`textureLoad( ${t}, ${r}, ${i}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(A.TEXTURE_COMPARE)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===K||!1===this.isSampleCompare(e)&&e.minFilter===B&&e.magFilter===B||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;o(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`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,r=e.type;return"texture"===r||"cubeTexture"===r||"cubeDepthTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=_C[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(d("WebGPURenderer: Atomic operations are only supported in compute shaders."),ii.READ_WRITE):ii.READ_ONLY:e.access}getStorageAccess(e,t){return yC[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);"texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new dR(i.name,i.node,o,n):new uR(i.name,i.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?s=new lR(i.name,i.node,o,n):"texture3D"===t&&(s=new dR(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(xC[r]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new sC(`${i.name}_sampler`,i.node,o);e.setVisibility(xC[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let u=n.buffer;if(void 0===u){u=new("buffer"===t?tR:aC)(e,o),n.buffer=u}u.setVisibility(u.getVisibility()|xC[r]),l.push(u),a=u,i.name=s||"NodeBuffer_"+i.id}else{let e=this.uniformGroups[u];void 0===e&&(e=new iR(u,o),e.setVisibility(qR.VERTEX|qR.FRAGMENT|qR.COMPUTE),this.uniformGroups[u]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),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,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null,s=""){let i=`var${s} ${t} : `;return i+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),i}getVars(e,t=!1){let r="";t&&(r="");const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count,r)};`);return t?s.join("\n"):`\n\t${s.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];let i=0;for(let n=0;nr.value.itemSize;return s&&!i}getUniforms(e){const t=this.renderer.backend,r=this.uniforms[e],s=[],i=[],n=[],a={};for(const n of r){const r=n.groupNode.name,o=this.bindingsIndexes[r];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const r=n.node.value;let i;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==n.node.isStorageTextureNode)&&(this.isSampleCompare(r)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let a="";const{primarySamples:u}=t.utils.getTextureSampleData(r);if(u>1&&(a="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)i="texture_depth_cube";else if(!0===r.isCubeTexture)i="texture_cube";else if(!0===r.isDepthTexture)i=t.compatibilityMode&&null===r.compareFunction?`texture${a}_2d`:`texture_depth${a}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const s=cC(r,t.device),a=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,u=n.node.value.isArrayTexture;i=`texture_storage_${o?"3d":"2d"+(u?"_array":"")}<${s}, ${a}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture)i="texture_2d_array";else if(!0===r.is3DTexture||!0===r.isData3DTexture)i="texture_3d";else{i=`texture${a}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${i};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,r=this.getType(t.getNodeType(this)),s=t.bufferCount,a=s>0&&"buffer"===n.type?", "+s:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${u}> ${n.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${a} >`;i.push(this._getWGSLStructBinding(n.name,e,u,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const r=[];for(const e of t.uniforms){const t=e.getType(),s=this.getType(this.getVectorType(t));r.push(`\t${e.name} : ${s}`)}let s=this.uniformGroupsBindings[e];void 0===s&&(s={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=s),a[e]={index:s.index,id:s.id,snippets:r}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=this.allowGlobalVariables,s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t,r),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,u=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const r=this.getFlowData(e),n=e.name;if(n&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${n}\n`),i+=`${r.code}\n\t`,e===a&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(u)s.returnType=o.getNodeType(this),s.structs+="var output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location( 0 ) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return vC[e]||e}isAvailable(e){let t=TC[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),TC[e]=t),t}_getWGSLMethod(e){return void 0!==SC[e]&&this._include(e),RC[e]}_include(e){const t=SC[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${AC}\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[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\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 * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * 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,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class wC{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?rE:eE:!0===this.backend.renderer.reversedDepthBuffer?tE:JA),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}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?zR:e.isLineSegments||e.isMesh&&!0===t.wireframe?$R:e.isLine?WR:e.isMesh?HR:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ve)return PA;if(e===Te)return qA;throw new Error("Unsupported output buffer type.")}}const CC=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&CC.set(Float16Array,["float16"]);const MC=new Map([[xt,["float16"]]]),BC=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class FC{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o=r.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e{t.buffer=null,t._mapped=!1,u.unmap()},s=()=>{t.buffer=null,t._mapped=!1,u.destroy(),i.delete(t),t.removeEventListener("release",r),t.removeEventListener("dispose",s)};t.addEventListener("release",r),t.addEventListener("dispose",s),e.readBufferGPU=u}else u=e.readBufferGPU}else u=n.createBuffer({label:`${e.name}_readback`,size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const l=n.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(a,r,u,0,o);const d=l.finish();if(n.queue.submit([d]),await u.mapAsync(GPUMapMode.READ,0,o),null===t){const e=u.getMappedRange(0,o).slice();return u.destroy(),e}if(t.isReadbackBuffer)return t.buffer=u.getMappedRange(0,o),t;{const e=u.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),u.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:r}=e,s=e.array.constructor,i=e.constructor;let n;if(1===t)n=BC.get(s);else{const e=(MC.get(i)||CC.get(s))[r?1:0];if(e){const r=s.BYTES_PER_ELEMENT*t,i=4*Math.floor((r+3)/4)/s.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${i}`}}return n||o("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class LC{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class PC{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,r=t.device,s=t.get(e);if(s.layout)return s.layout.layoutGPU;const i=this._createLayoutEntries(e),n=Vs(JSON.stringify(i));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new LC(r.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,s.layout=a,s.layoutKey=n,a.layoutGPU}createBindings(e,t,r,s=0){const{backend:i}=this,n=i.get(e),a=this.createBindingsLayout(e);let o;r>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[r]===s&&(o=n.groups[r])),void 0===o&&(o=this.createBindGroup(e,a),r>0&&(n.groups[r]=o,n.versions[r]=s)),n.group=o}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer,n=e.updateRanges;if(0===n.length)r.queue.writeBuffer(i,0,s,0);else{const e=Xr(s),t=e?1:s.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${r}-${s}`,a=e[i],void 0===a){const n=Zw;let o;o=t.isSampledCubeTexture?Qw:t.isSampledTexture3D?Yw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Kw:Xw,a=e[i]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:r,baseMipLevel:s})}}n.push({binding:i,resource:a})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let r=0;for(const s of e.bindings){const e=this.backend,i={binding:r,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const e={};s.isStorageBuffer&&(s.visibility&qR.COMPUTE&&(s.access===ii.READ_WRITE||s.access===ii.WRITE_ONLY)?e.type=Pw:e.type=Uw),i.buffer=e}else if(s.isSampledTexture&&s.store){const e={};e.format=this.backend.get(s.texture).texture.format;const t=s.access;e.access=t===ii.READ_WRITE?Ow:t===ii.WRITE_ONLY?Dw:Iw,s.texture.isArrayTexture?e.viewDimension=Kw:s.texture.is3DTexture&&(e.viewDimension=Yw),i.storageTexture=e}else if(s.isSampledTexture){const t={},{primarySamples:r}=e.utils.getTextureSampleData(s.texture);if(r>1&&(t.multisampled=!0,s.texture.isDepthTexture||(t.sampleType=zw)),s.texture.isDepthTexture)e.compatibilityMode&&null===s.texture.compareFunction?t.sampleType=zw:t.sampleType=$w;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture||s.texture.isStorageTexture){const e=s.texture.type;e===R?t.sampleType=Ww:e===S?t.sampleType=Hw:e===K&&(this.backend.hasFeature("float32-filterable")?t.sampleType=Gw:t.sampleType=zw)}s.isSampledCubeTexture?t.viewDimension=Qw:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?t.viewDimension=Kw:s.isSampledTexture3D&&(t.viewDimension=Yw),i.texture=t}else if(s.isSampler){const t={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction&&e.hasCompatibility(A.TEXTURE_COMPARE)?t.type=kw:t.type=Vw),i.sampler=t}else o(`WebGPUBindingUtils: Unsupported binding "${s}".`);t.push(i),r++}return t}deleteBindGroupData(e){const{backend:t}=this,r=t.get(e);r.layout&&(r.layout.usedTimes--,0===r.layout.usedTimes&&this._bindGroupLayoutCache.delete(r.layoutKey),r.layout=void 0,r.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class UC{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class DC{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:r,material:s,geometry:i,pipeline:n}=e,{vertexProgram:a,fragmentProgram:u}=n,l=this.backend,d=l.device,c=l.utils,h=l.get(n),p=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:r}=e.layout;p.push(r)}const g=l.attributeUtils.createShaderVertexBuffers(e);let m;s.blending===re||s.blending===tt&&!1===s.transparent||(m=this._getBlending(s));let f={};!0===s.stencilWrite&&(f={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const y=this._getColorWriteMask(s),b=[];if(null!==e.context.textures){const t=e.context.textures,r=e.context.mrt;for(let e=0;e1},layout:d.createPipelineLayout({bindGroupLayouts:p})},E={},w=e.context.depth,C=e.context.stencil;if(!0!==w&&!0!==C||(!0===w&&(E.format=S,E.depthWriteEnabled=s.depthWrite,E.depthCompare=N),!0===C&&(E.stencilFront=f,E.stencilBack=f,E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),A.depthStencil=E),d.pushErrorScope("validation"),null===t)h.pipeline=d.createRenderPipeline(A),d.popErrorScope().then(e=>{null!==e&&(h.error=!0,o(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await d.createRenderPipelineAsync(A)}catch(e){}const t=await d.popErrorScope();null!==t&&(h.error=!0,o(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:s.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e),{layoutGPU:s}=t.layout;a.push(s)}n.pipeline=s.createComputePipeline({compute:i,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,r;const s=e.blending,i=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(s===Rt){const s=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,u=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},r={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(u)}}else{const i=(e,s,i,n)=>{t={srcFactor:e,dstFactor:s,operation:xw},r={srcFactor:i,dstFactor:n,operation:xw}};if(e.premultipliedAlpha)switch(s){case tt:i(ow,cw,ow,cw);break;case Yt:i(ow,ow,ow,ow);break;case Qt:i(aw,lw,aw,ow);break;case Kt:i(hw,cw,aw,ow)}else switch(s){case tt:i(dw,cw,ow,cw);break;case Yt:i(dw,ow,ow,ow);break;case Qt:o(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Kt:o(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};o("WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case At:t=aw;break;case Ht:t=ow;break;case Wt:t=uw;break;case kt:t=lw;break;case rt:t=dw;break;case st:t=cw;break;case zt:t=hw;break;case Vt:t=pw;break;case Gt:t=gw;break;case Ot:t=mw;break;case $t:t=fw;break;case 211:t=yw;break;case 212:t=bw;break;default:o("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case rs:t=jR;break;case ts:t=eA;break;case es:t=XR;break;case Jr:t=QR;break;case Zr:t=KR;break;case Yr:t=JR;break;case Qr:t=YR;break;case Kr:t=ZR;break;default:o("WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case ds:t=Aw;break;case ls:t=Ew;break;case us:t=ww;break;case os:t=Cw;break;case as:t=Mw;break;case ns:t=Bw;break;case is:t=Fw;break;case ss:t=Lw;break;default:o("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case it:t=xw;break;case It:t=Tw;break;case Dt:t=_w;break;case hs:t=vw;break;case cs:t=Nw;break;default:o("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?uA:lA);let n=r.side===L;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),s.frontFace=!0===n?nA:iA,s.cullMode=r.side===P?aA:oA,s}_getColorWriteMask(e){return!0===e.colorWrite?Rw:Sw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=eA;else{const r=this.backend.parameters.reversedDepthBuffer?ar[e.depthFunc]:e.depthFunc;switch(r){case nr:t=jR;break;case ir:t=eA;break;case sr:t=XR;break;case rr:t=QR;break;case tr:t=KR;break;case er:t=JR;break;case Jt:t=YR;break;case Zt:t=ZR;break;default:o("WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class IC extends VR{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r)),a={},o=[];for(const[t,r]of e){const e=t.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===o.includes(s)&&o.push(s),void 0===a[s]&&(a[s]=0);const i=n[r],u=n[r+1],l=Number(u-i)/1e6;this.timestamps.set(t,l),a[s]+=l}const u=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=u,this.frames=o,u}catch(e){return o("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){o("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){o("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const OC={r:0,g:0,b:0,a:1};class VC extends _R{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 wC(this),this.attributeUtils=new FC(this),this.bindingUtils=new PC(this),this.capabilities=new UC(this),this.pipelineUtils=new DC(this),this.textureUtils=new dC(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[A.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},s="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===s)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(tC),n=[];for(const e of i)s.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};r=await s.requestDevice(a)}else r=t.device;this.compatibilityMode=!r.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),r.lost.then(t=>{if("destroyed"===t.reason)return;const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}),this.device=r,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(tC.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let r=t.context;if(void 0===r){const s=this.parameters;r=!0===e.isDefaultCanvasTarget&&void 0!==s.context?s.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${_t} webgpu`);const i=s.alpha?"premultiplied":"opaque",n=s.outputType===Te?"extended":"standard";r.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),t.context=r}return r}get coordinateSystem(){return h}async getArrayBufferAsync(e,t=null,r=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,r,s)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),r=this.get(t),s=e.currentSamples;let i=r.descriptor;if(void 0===i||r.samples!==s){i={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(i.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=i.colorAttachments[0];s>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,r.descriptor=i,r.samples=s}const n=i.colorAttachments[0];return s>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;void 0!==i&&s.width===r.width&&s.height===r.height&&s.samples===r.samples||(i={},s.descriptors=i);const n=e.getCacheKey();let a=i[n];if(void 0===a){const t=e.textures,o=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s1)if(!0===l){const t=e.camera.cameras;for(let e=0;e0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=r.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:rA}),this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(i=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,i));const n=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),n.dispatchSize=i}i=n.dispatchSize}a.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,r,s,i,n,a,o,u){const{object:l,material:d,context:c}=e,h=e.getIndex(),p=null!==h;this.pipelineUtils.setPipeline(o,s),u.pipeline=s;const g=u.bindingGroups;for(let e=0,t=i.length;e65535?4:2);for(let n=0;n0){const i=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===i.indexesGPU||i.indexesGPU.length!==a.length){const e=this.get(c),t=[],r=new Uint32Array([0,0,0,0]);for(let s=0,i=a.length;s(d("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new GR(e)));super(new t(e),e),this.library=new zC,this.isWebGPURenderer=!0}}class WC extends As{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class HC{constructor(e,t=Cn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new vg;r.name="RenderPipeline",this._quadMesh=new gx(r),this._quadMesh.name="Render Pipeline",this._context=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){const e=this.renderer;this._update(),null!==this._context.onBeforeRenderPipeline&&this._context.onBeforeRenderPipeline();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=m,e.outputColorSpace=p.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterRenderPipeline&&this._context.onAfterRenderPipeline()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),!0===this.needsUpdate){const e=this._toneMapping,t=this._outputColorSpace,r={renderPipeline:this,onBeforeRenderPipeline:null,onAfterRenderPipeline:null};let s=this.outputNode;!0===this.outputColorTransform?(s=s.context(r),s=Fl(s,e,t)):(r.toneMapping=e,r.outputColorSpace=t,s=s.context(r)),this._context=r,this._quadMesh.material.fragmentNode=s,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){v('RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}}class qC extends HC{constructor(e,t){v('PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.'),super(e,t)}}class jC extends u{constructor(e){super(),this.name="",this.buffer=null,this.maxByteLength=e,this.isReadbackBuffer=!0,this._mapped=!1}release(){this.dispatchEvent({type:"release"})}dispose(){this.dispatchEvent({type:"dispose"})}}class XC extends N{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class KC extends Ex{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class QC extends Es{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new ws(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{try{t(this.parse(JSON.parse(r)))}catch(t){s?s(t):o(t),this.manager.itemError(e)}},r,s)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return void 0===this.nodes[e]?(o("NodeLoader: Node type not found:",e),yn()):new this.nodes[e]}}class YC extends Cs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class ZC extends Ms{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}async parseAsync(e){this._nodesJSON=e.nodes;const t=await super.parseAsync(e);return this._nodesJSON=null,t}parseNodes(e,t){if(void 0!==e){const r=new QC;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new YC;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t= 66 ) { + + b = 255; + + } else if ( temp <= 19 ) { + + b = 0; + + } else { + + b = 138.5177312231 * Math.log( temp - 10 ) - 305.0447927307; + + } + + return color.setRGB( + MathUtils.clamp( r, 0, 255 ) / 255, + MathUtils.clamp( g, 0, 255 ) / 255, + MathUtils.clamp( b, 0, 255 ) / 255, + SRGBColorSpace + ); + +} + +export { setKelvin }; diff --git a/examples/models/ldraw/officialLibrary/models/6156-1-WindowBrick.mpd_Packed.mpd b/examples/models/ldraw/officialLibrary/models/6156-1-WindowBrick.mpd_Packed.mpd new file mode 100644 index 00000000000000..f3e7f47ff00f3f --- /dev/null +++ b/examples/models/ldraw/officialLibrary/models/6156-1-WindowBrick.mpd_Packed.mpd @@ -0,0 +1,745 @@ +0 LDraw.org Configuration File +0 Name: LDConfig.ldr +0 Author: LDraw.org +0 !LDRAW_ORG Configuration UPDATE 2022-03-31 + +0 // * LDraw and BrickLink mostly share naming conventions for their colours. +0 // * Where possible LEGO colour numbers were used. +0 // * The LEGO numbers, names and LDD colours are taken directly from LEGO Digital Designer. +0 // * Colours were compared with Ryan Howerter's colour list. +0 // * Most transparent colours were altered so that they can be displayed with their LDraw alpha level. +0 // * Edge colours for solid, pearl, metallic, solid internal common material were calculated +0 // the following way: +0 // If the lightness value L in the HSL colours system was above 20%, a Gray with 20% relative +0 // luminance in the terms of RGB-Gray was used. +0 // If the lightness value L in the HSL colours system was below 20%, a Gray with 50% relative +0 // luminance in the terms of RGB-Gray was used. +0 // * Edge colours for transparent, chrome, milky, glitter, transparent internal common material +0 // were calculated the following way: +0 // The lightness value L in the HSL colours system was lowered by 20 percentage points. If the +0 // lightness value L in the HSL colours system was below 20% it was raised by 20 percentage points. +0 // * Edge colours for speckle colours are defined by the value of the MATERIAL colour. +0 // * Rubber colours got their value from the corresponding solid or transparent colour. This applies +0 // also to the edge colours. +0 // * Material Glitter colours were calculated the following way: +0 // The lightness value L and the hue value H in the HSL colours system was lowered by 20 percentage +0 // points and 20 degree. + + +0 // LDraw Solid Colours +0 // LEGOID 26 - Black +0 !COLOUR Black CODE 0 VALUE #1B2A34 EDGE #808080 +0 // LEGOID 23 - Bright Blue +0 !COLOUR Blue CODE 1 VALUE #1E5AA8 EDGE #333333 +0 // LEGOID 28 - Dark Green +0 !COLOUR Green CODE 2 VALUE #00852B EDGE #333333 +0 // LEGOID 107 - Bright Bluish Green +0 !COLOUR Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333 +0 // LEGOID 21 - Bright Red +0 !COLOUR Red CODE 4 VALUE #B40000 EDGE #333333 +0 // LEGOID 22 / 221 - Medium Reddish Violet / Bright Purple +0 !COLOUR Dark_Pink CODE 5 VALUE #D3359D EDGE #333333 +0 // LEGOID 25 - Earth Orange +0 !COLOUR Brown CODE 6 VALUE #543324 EDGE #1E1E1E +0 // LEGOID 2 - Grey +0 !COLOUR Light_Grey CODE 7 VALUE #8A928D EDGE #333333 +0 // LEGOID 27 - Dark Grey +0 !COLOUR Dark_Grey CODE 8 VALUE #545955 EDGE #333333 +0 // LEGOID 45 - Light Blue +0 !COLOUR Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333 +0 // LEGOID 37 - Bright Green +0 !COLOUR Bright_Green CODE 10 VALUE #58AB41 EDGE #333333 +0 // LEGOID 116 - Medium Bluish Green +0 !COLOUR Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333 +0 // LEGOID 101 - Medium Red +0 !COLOUR Salmon CODE 12 VALUE #F06D61 EDGE #333333 +0 // LEGOID 9 - Light Reddish Violet +0 !COLOUR Pink CODE 13 VALUE #F6A9BB EDGE #333333 +0 // LEGOID 24 - Bright Yellow +0 !COLOUR Yellow CODE 14 VALUE #FAC80A EDGE #333333 +0 // LEGOID 1 - White +0 !COLOUR White CODE 15 VALUE #F4F4F4 EDGE #333333 +0 // LEGOID 6 - Light Green +0 !COLOUR Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333 +0 // LEGOID 3 - Light Yellow +0 !COLOUR Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333 +0 // LEGOID 5 - Brick Yellow +0 !COLOUR Tan CODE 19 VALUE #B0A06F EDGE #333333 +0 // LEGOID 39 - Light Bluish Violet +0 !COLOUR Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333 +0 // LEGOID 104 - Bright Violet +0 !COLOUR Purple CODE 22 VALUE #671F81 EDGE #333333 +0 // LEGOID 196 - Dark Royal Blue +0 !COLOUR Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333 +0 // LEGOID 106 - Bright Orange +0 !COLOUR Orange CODE 25 VALUE #D67923 EDGE #333333 +0 // LEGOID 124 - Bright Reddish Violet +0 !COLOUR Magenta CODE 26 VALUE #901F76 EDGE #333333 +0 // LEGOID 119 - Bright Yellowish Green +0 !COLOUR Lime CODE 27 VALUE #A5CA18 EDGE #333333 +0 // LEGOID 138 - Sand Yellow +0 !COLOUR Dark_Tan CODE 28 VALUE #897D62 EDGE #333333 +0 // LEGOID 222 - Light Purple +0 !COLOUR Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333 +0 // LEGOID 324 - Medium Lavender +0 !COLOUR Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333 +0 // LEGOID 325 - Lavender +0 !COLOUR Lavender CODE 31 VALUE #CDA4DE EDGE #333333 +0 // LEGOID 36 - Light Yellowish Orange +0 !COLOUR Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333 +0 // LEGOID 198 - Bright Reddish Lilac +0 !COLOUR Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333 +0 // LEGOID 192 - Reddish Brown +0 !COLOUR Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080 +0 // LEGOID 194 - Medium Stone Grey +0 !COLOUR Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333 +0 // LEGOID 199 - Dark Stone Grey +0 !COLOUR Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333 +0 // LEGOID 102 - Medium Blue +0 !COLOUR Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333 +0 // LEGOID 29 - Medium Green +0 !COLOUR Medium_Green CODE 74 VALUE #7FC475 EDGE #333333 +0 // LEGOID 223 - Light Pink +0 !COLOUR Light_Pink CODE 77 VALUE #FECCCF EDGE #333333 +0 // LEGOID 283 - Light Nougat +0 !COLOUR Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333 +0 // LEGOID 312 - Medium Nougat +0 !COLOUR Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333 +0 // LEGOID 268 - Medium Lilac +0 !COLOUR Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333 +0 // LEGOID 217 - Brown +0 !COLOUR Medium_Brown CODE 86 VALUE #7B5D41 EDGE #333333 +0 // LEGOID 195 - Medium Royal Blue +0 !COLOUR Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333 +0 // LEGOID 18 - Nougat +0 !COLOUR Nougat CODE 92 VALUE #BB805A EDGE #333333 +0 // LEGOID 100 - Light Red +0 !COLOUR Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333 +0 // LEGOID 110 - Bright Bluish Violet +0 !COLOUR Violet CODE 110 VALUE #26469A EDGE #333333 +0 // LEGOID 112 - Medium Bluish Violet +0 !COLOUR Medium_Violet CODE 112 VALUE #4861AC EDGE #333333 +0 // LEGOID 115 - Medium Yellowish Green +0 !COLOUR Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333 +0 // LEGOID 118 - Light Bluish Green +0 !COLOUR Aqua CODE 118 VALUE #9CD6CC EDGE #333333 +0 // LEGOID 120 - Light Yellowish Green +0 !COLOUR Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333 +0 // LEGOID 125 - Light Orange +0 !COLOUR Light_Orange CODE 125 VALUE #F9A777 EDGE #333333 +0 // LEGOID 128 - Dark Nougat +0 !COLOUR Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333 +0 // LEGOID 208 - Light Stone Grey +0 !COLOUR Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333 +0 // LEGOID 191 - Flame Yellowish Orange +0 !COLOUR Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333 +0 // LEGOID 212 - Light Royal Blue +0 !COLOUR Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333 +0 // LEGOID 216 - Rust +0 !COLOUR Rust CODE 216 VALUE #872B17 EDGE #333333 +0 // LEGOID 218 - Reddish Lilac +0 !COLOUR Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333 +0 // LEGOID 219 - Lilac +0 !COLOUR Lilac CODE 219 VALUE #564E9D EDGE #333333 +0 // LEGOID 226 - Cool Yellow +0 !COLOUR Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333 +0 // LEGOID 232 - Dove Blue +0 !COLOUR Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333 +0 // LEGOID 140 - Earth Blue +0 !COLOUR Dark_Blue CODE 272 VALUE #19325A EDGE #333333 +0 // LEGOID 141 - Earth Green +0 !COLOUR Dark_Green CODE 288 VALUE #00451A EDGE #808080 +0 // LEGOID 295 - Flamingo Pink +0 !COLOUR Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333 +0 // LEGOID 308 - Dark Brown +0 !COLOUR Dark_Brown CODE 308 VALUE #352100 EDGE #808080 +0 // LEGOID 11 - Pastel Blue +0 !COLOUR Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333 +0 // LEGOID 154 - New Dark Red +0 !COLOUR Dark_Red CODE 320 VALUE #720012 EDGE #333333 +0 // LEGOID 321 - Dark Azur +0 !COLOUR Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333 +0 // LEGOID 322 - Medium Azur +0 !COLOUR Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333 +0 // LEGOID 323 - Aqua +0 !COLOUR Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333 +0 // LEGOID 326 - Spring Yellowish Green +0 !COLOUR Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333 +0 // LEGOID 330 - Olive Green +0 !COLOUR Olive_Green CODE 330 VALUE #77774E EDGE #333333 +0 // LEGOID 153 - Sand Red +0 !COLOUR Sand_Red CODE 335 VALUE #88605E EDGE #333333 +0 // LEGOID 16 - Pink +0 !COLOUR Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333 +0 // LEGOID 353 - Vibrant Coral +0 !COLOUR Coral CODE 353 VALUE #FF6D77 EDGE #333333 +0 // LEGOID 12 - Light Orange Brown +0 !COLOUR Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333 +0 // LEGOID 368 - Vibrant Yellow +0 !COLOUR Vibrant_Yellow CODE 368 VALUE #EDFF21 EDGE #333333 +0 // LEGOID 370 - Medium Brown +0 !COLOUR Medium_Brown CODE 370 VALUE #755945 EDGE #333333 +0 // LEGOID 136 - Sand Violet +0 !COLOUR Sand_Purple CODE 373 VALUE #75657D EDGE #333333 +0 // LEGOID 151 - Sand Green +0 !COLOUR Sand_Green CODE 378 VALUE #708E7C EDGE #333333 +0 // LEGOID 135 - Sand Blue +0 !COLOUR Sand_Blue CODE 379 VALUE #70819A EDGE #333333 +0 // LEGOID 4 - Brick Red +0 !COLOUR Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333 +0 // LEGOID 105 - Bright Yellowish Orange +0 !COLOUR Medium_Orange CODE 462 VALUE #F58624 EDGE #333333 +0 // LEGOID 38 - Dark Orange +0 !COLOUR Dark_Orange CODE 484 VALUE #91501C EDGE #333333 +0 // LEGOID 103 - Light Grey +0 !COLOUR Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333 +0 // LEGOID 12 - Light Orange Brown +0 !COLOUR Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333 +0 // LEGOID 13 - Red Orange +0 !COLOUR Fabuland_Red CODE 508 VALUE #FF8014 EDGE #333333 +0 // LEGOID 19 - Light Brown +0 !COLOUR Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333 +0 // LEGOID 14 - Pastel Green +0 !COLOUR Fabuland_Pastel_Green CODE 510 VALUE #78FC78 EDGE #333333 + + +0 // LDraw Transparent Colours +0 // LEGOID 43 - Transparent Blue +0 !COLOUR Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128 +0 // LEGOID 48 - Transparent Green +0 !COLOUR Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128 +0 // LEGOID 311 - Transparent Bright Green +0 !COLOUR Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128 +0 // LEGOID 41 - Transparent Red +0 !COLOUR Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128 +0 // LEGOID 113 - Transparent Medium Reddish Violet +0 !COLOUR Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128 +0 // LEGOID 47 - Transparent Fluorescent Reddish Orange +0 !COLOUR Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128 +0 // LEGOID 229 - Transparent Light Bluish Green +0 !COLOUR Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128 +0 // LEGOID 111 - Transparent Brown +0 !COLOUR Trans_Black CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128 +0 // LEGOID 143 - Transparent Fluorescent Blue +0 !COLOUR Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128 +0 // LEGOID 49 - Transparent Fluorescent Green +0 !COLOUR Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128 +0 // LEGOID 42 - Transparent Light Blue +0 !COLOUR Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 +0 // LEGOID 236 - Transparent Bright Reddish Lilac +0 !COLOUR Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128 +0 // LEGOID 230 - Transparent Bright Pink +0 !COLOUR Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128 +0 // LEGOID 44 - Transparent Yellow +0 !COLOUR Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128 +0 // LEGOID 40 - Transparent +0 !COLOUR Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 +0 // LEGOID 126 - Transparent Bright Bluish Violet +0 !COLOUR Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128 +0 // LEGOID 157 - Transparent Fluorescent Yellow +0 !COLOUR Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128 +0 // LEGOID 182 - Trans Bright Orange +0 !COLOUR Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 +0 // LEGOID 227 - Transparent Bright Yellowish Green +0 !COLOUR Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128 +0 // LEGOID 231 - Transparent Flame Yellowish Orange +0 !COLOUR Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128 +0 // LEGOID 234 - Transparent Fire Yellow +0 !COLOUR Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128 +0 // LEGOID 284 - Transparent Reddish Lilac +0 !COLOUR Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128 +0 // LEGOID 285 - Transparent Light Green +0 !COLOUR Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128 +0 // LEGOID 293 - Transparent Light Royal Blue +0 !COLOUR Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128 + + +0 // LDraw Chrome Plated Colours +0 !COLOUR Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME +0 !COLOUR Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME +0 !COLOUR Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME +0 !COLOUR Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME +0 !COLOUR Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME +0 // LEGOID 310 - Metalized Gold +0 !COLOUR Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME +0 // LEGOID 309 - Metalized Silver +0 !COLOUR Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME + + +0 // LDraw Pearlescent Plastic Colours +0 // LEGOID 149 - Metallic Black +0 !COLOUR Metallic_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT +0 // LEGOID 139 - Copper +0 !COLOUR Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT +0 // LEGOID 296 / 131 / 315 - Cool Silver / Silver / Silver Metallic +0 !COLOUR Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT +0 // LEGOID 145 - Sand Blue Metallic +0 !COLOUR Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT +0 // LEGOID 127 - Gold +0 !COLOUR Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT +0 // LEGOID 148 - Metallic Dark Grey +0 !COLOUR Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT +0 // LEGOID 150 - Metallic Light Grey +0 !COLOUR Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT +0 // LEGOID 147 - Metallic Sand Yellow +0 !COLOUR Flat_Dark_Gold CODE 178 VALUE #83724F EDGE #333333 PEARLESCENT +0 // LEGOID 179 - Silver Flip-flop +0 !COLOUR Flat_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT +0 // LEGOID 183 - Metallic White +0 !COLOUR Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT +0 // LEGOID 184 - Metallic Bright Red +0 !COLOUR Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT +0 // LEGOID 185 - Metallic Bright Blue +0 !COLOUR Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT +0 // LEGOID 186 - Metallic Dark Green +0 !COLOUR Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT +0 // LEGOID 189 - Reddish Gold +0 !COLOUR Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT +0 // LEGOID 200 - Lemon Metallic +0 !COLOUR Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT +0 // LEGOID 297 - Warm Gold +0 !COLOUR Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT + + +0 // LDraw Metallic Paint Colours +0 // LEGOID 298 / 336 - Cool Silver Drum Lacq / Silver Ink +0 !COLOUR Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL +0 // BricksetID 910 - Metallic Green +0 !COLOUR Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL +0 // LEGOID 299 / 335 - Warm Gold Drum Lacq / Gold Ink +0 !COLOUR Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL +0 // LEGOID 337 - Titanium +0 !COLOUR Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL +0 // LEGOID 300 / 334 - Copper Drum Lacq / Copper Ink +0 !COLOUR Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL +0 !COLOUR Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL +0 // BricksetID 911 - Metallic Pink +0 !COLOUR Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL +0 !COLOUR Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL + + +0 // LDraw Milky Colours +0 // LEGOID 20 - Nature +0 !COLOUR Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240 +0 // LEGOID 294 - Phosphorescent Green +0 !COLOUR Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15 +0 // LEGOID 50 - Phosphorescent White +0 !COLOUR Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15 +0 // LEGOID 329 - White Glow +0 !COLOUR Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15 + + +0 // LDraw Glitter Colours +0 // LEGOID 114 - Transparent Medium Reddish-Violet w. Glitter 2% +0 !COLOUR Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER VALUE #B92790 FRACTION 0.17 VFRACTION 0.2 SIZE 1 +0 // LEGOID 117 - Transparent Glitter +0 !COLOUR Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER VALUE #FFFFFF FRACTION 0.08 VFRACTION 0.1 SIZE 1 +0 // LEGOID 129 - Transparent Bright Bluish Violet w. Glitter 2% +0 !COLOUR Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER VALUE #8F00CC FRACTION 0.03 VFRACTION 0.4 SIZE 1 +0 // LEGOID 302 - Transparent Light Blue with Glitter 2% +0 !COLOUR Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER VALUE #59DEBF FRACTION 0.17 VFRACTION 0.2 SIZE 1 +0 // LEGOID 339 - Transparent Fluorescent Green with Glitter 2% +0 !COLOUR Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER VALUE #998C00 FRACTION 0.17 VFRACTION 0.2 SIZE 1 +0 // LEGOID 341 - Transparent Bright Orange with Glitter 2% +0 !COLOUR Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER VALUE #9E2A0A FRACTION 0.17 VFRACTION 0.2 SIZE 1 +0 // LEGOID 360 - Transparent Clear Opal +0 !COLOUR Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER VALUE #FFFFFF FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 +0 // LEGOID 362 - Transparent Blue Opal +0 !COLOUR Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER VALUE #59DEBF FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 +0 // LEGOID 363 - Transparent Brown Opal +0 !COLOUR Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER VALUE #292522 FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 +0 // LEGOID 364 - Transparent Medium Reddish Violet Opal +0 !COLOUR Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER VALUE #B92790 FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 +0 // LEGOID 365 - Transparent Violet Opal +0 !COLOUR Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER VALUE #2F1456 FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 +0 // LEGOID 367 - Transparent Green Opal +0 !COLOUR Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER VALUE #0B270B FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 +0 // LEGOID 351 - Transparent Bright Green with Glitter 2% +0 !COLOUR Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER VALUE #59AF18 FRACTION 0.17 VFRACTION 0.2 SIZE 1 +0 // LEGOID 366 - Transparent Blue Opal +0 !COLOUR Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER VALUE #001D38 FRACTION 0.8 VFRACTION 0.6 MINSIZE 0.02 MAXSIZE 0.1 + + +0 // LDraw Speckle Colours +0 !COLOUR Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE VALUE #AB6038 FRACTION 0.4 MINSIZE 1 MAXSIZE 3 +0 !COLOUR Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE VALUE #898788 FRACTION 0.4 MINSIZE 1 MAXSIZE 3 +0 // LEGOID 132 - Black Glitter +0 !COLOUR Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE VALUE #898788 FRACTION 0.4 MINSIZE 1 MAXSIZE 3 +0 !COLOUR Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE VALUE #DBAC34 FRACTION 0.4 MINSIZE 1 MAXSIZE 3 + + +0 // LDraw Rubber Colours +0 !COLOUR Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER +0 !COLOUR Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER +0 !COLOUR Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER +0 !COLOUR Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER +0 !COLOUR Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER +0 !COLOUR Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER +0 !COLOUR Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER +0 !COLOUR Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER +0 !COLOUR Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER +0 !COLOUR Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER +0 !COLOUR Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER +0 !COLOUR Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER +0 !COLOUR Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER +0 !COLOUR Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER +0 !COLOUR Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER +0 !COLOUR Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER +0 !COLOUR Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER +0 !COLOUR Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER +0 !COLOUR Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER +0 !COLOUR Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER +0 !COLOUR Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER +0 !COLOUR Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER +0 !COLOUR Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER +0 !COLOUR Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER +0 !COLOUR Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER +0 !COLOUR Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER +0 !COLOUR Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER +0 !COLOUR Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER + + +0 // LDraw Transparent Rubber Colours +0 !COLOUR Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER +0 !COLOUR Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER +0 !COLOUR Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER +0 !COLOUR Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER +0 !COLOUR Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER + + +0 // LDraw Internal Common Material Colours +0 !COLOUR Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333 +0 !COLOUR Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333 +0 // LEGOID 109 - Black IR +0 !COLOUR Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210 +0 !COLOUR Magnet CODE 493 VALUE #656761 EDGE #333333 METAL +0 !COLOUR Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL +0 !COLOUR Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL +0 !COLOUR Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 +0 + +0 Panel 1 x 4 x 3 with Glass +0 Name: 6156.dat +0 Author: Thomas Burger [grapeape] +0 !LDRAW_ORG Part UPDATE 1998-07 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 !HISTORY 1998-07-15 [PTadmin] Official Update 1998-07 +0 !HISTORY 2007-07-16 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 + +4 16 40 72 10 31 48 10 -31 48 10 -40 72 10 +3 16 -31 48 10 -33 46 10 -40 72 10 +4 16 -40 72 10 -33 46 10 -33 6 10 -40 0 10 +3 16 40 72 10 31 48 10 33 46 10 +4 16 40 72 10 33 46 10 33 6 10 40 0 10 +4 16 40 0 10 31 4 10 -31 4 10 -40 0 10 +3 16 31 4 10 33 6 10 40 0 10 +3 16 -31 4 10 -33 6 10 -40 0 10 +2 24 33 46 10 31 48 10 +2 24 31 48 10 -31 48 10 +2 24 -31 48 10 -33 46 10 +2 24 -33 46 10 -33 6 10 +2 24 -33 6 10 -31 4 10 +2 24 -31 4 10 31 4 10 +2 24 31 4 10 33 6 10 +2 24 33 6 10 33 46 10 +4 41 31 4 10 31 48 10 -31 48 10 -31 4 10 +4 41 -31 4 10 -33 6 10 -33 46 10 -31 48 10 +4 41 31 48 10 33 46 10 33 6 10 31 4 10 +0 Panel 1 x 4 x 3 without front +1 16 20 68 0 1 0 0 0 -1 0 0 0 1 p/stud3.dat +1 16 0 68 0 1 0 0 0 -1 0 0 0 1 p/stud3.dat +1 16 -20 68 0 1 0 0 0 -1 0 0 0 1 p/stud3.dat +1 16 0 72 0 36 0 0 0 -4 0 0 0 6 p/box4.dat +4 16 40 72 10 36 72 6 -36 72 6 -40 72 10 +4 16 -40 72 10 -36 72 6 -36 72 -6 -40 72 -10 +4 16 -40 72 -10 -36 72 -6 36 72 -6 40 72 -10 +4 16 40 72 -10 36 72 -6 36 72 6 40 72 10 +2 24 40 72 10 -40 72 10 +2 24 -40 72 10 -40 72 -10 +2 24 -40 72 -10 40 72 -10 +2 24 40 72 -10 40 72 10 +2 24 40 64 6 -40 64 6 +2 24 -40 64 6 -40 64 -10 +2 24 -40 64 -10 40 64 -10 +2 24 40 64 -10 40 64 6 +2 24 40 4 6 -40 4 6 +2 24 -40 4 6 -40 4 -10 +2 24 -40 4 -10 40 4 -10 +2 24 40 4 -10 40 4 6 +2 24 40 0 10 -40 0 10 +2 24 -40 0 10 -40 0 -10 +2 24 -40 0 -10 40 0 -10 +2 24 40 0 -10 40 0 10 +2 24 40 0 -10 40 4 -10 +2 24 -40 0 -10 -40 4 -10 +2 24 40 4 6 40 64 6 +2 24 -40 4 6 -40 64 6 +2 24 40 64 -10 40 72 -10 +2 24 -40 64 -10 -40 72 -10 +2 24 40 0 10 40 72 10 +2 24 -40 0 10 -40 72 10 +4 16 40 0 10 40 0 -10 -40 0 -10 -40 0 10 +4 16 -40 72 10 -40 72 -10 -40 64 -10 -40 64 10 +4 16 -40 72 -10 40 72 -10 40 64 -10 -40 64 -10 +4 16 40 72 -10 40 72 10 40 64 10 40 64 -10 +0 +4 16 -40 64 10 -40 64 6 -40 4 6 -40 4 10 +4 16 40 64 6 40 64 10 40 4 10 40 4 6 +4 16 -40 4 10 -40 4 -10 -40 0 -10 -40 0 10 +4 16 -40 4 -10 40 4 -10 40 0 -10 -40 0 -10 +0 inside +2 24 32 60 6 32 64 6 +2 24 -32 60 6 -32 64 6 +4 41 32 60 6 32 64 6 -32 64 6 -32 60 6 +2 24 32 60 6 34 60 6 +2 24 34 60 6 36 58.25 6 +2 24 36 4 6 34 2 6 +2 24 34 2 6 -34 2 6 +2 24 -34 2 6 -36 4 6 +2 24 -36 4 6 -36 58 6 +2 24 36 4 6 36 58 6 +2 24 -36 4 8 -36 58 8 +2 24 36 4 8 36 58 8 +2 24 -36 58 6 -34 60 6 +2 24 -34 60 6 -32 60 6 +4 41 34 60 6 34 2 6 -34 2 6 -34 60 6 +4 41 -34 60 6 -36 58 6 -36 4 6 -34 2 6 +4 41 34 60 6 36 58.25 6 36 4 6 34 2 6 +3 16 40 2 6 36 4 6 34 2 6 +3 16 -40 2 6 -34 2 6 -36 4 6 +4 16 -40 2 6 -36 4 6 -36 58 6 -40 64 6 +3 16 -36 58 6 -34 60 6 -40 64 6 +4 16 -32 64 6 -40 64 6 -34 60 6 -32 60 6 +4 16 40 64 6 32 64 6 32 60 6 34 60 6 +3 16 40 64 6 34 60 6 36 58.25 6 +4 16 40 64 6 36 58.25 6 36 4 6 40 2 6 +0 bottom +2 24 -32 64 6 -28 64 4 +2 24 -28 64 4 -28 64 -1 +3 24 -28 64 -1 -28 64 -1 28 64 -1 +2 24 28 64 -1 28 64 4 +2 24 28 64 4 32 64 6 +2 24 32 64 6 40 64 6 +3 16 32 64 6 40 64 6 40 64 -10 +4 16 40 64 -10 32 64 6 28 64 4 28 64 -1 +3 16 -40 64 6 -32 64 6 -40 64 -10 +4 16 -40 64 -10 -32 64 6 -28 64 4 -28 64 -1 +4 16 -40 64 -10 -28 64 -1 28 64 -1 40 64 -10 +4 41 -32 64 6 -28 64 4 28 64 4 32 64 6 +4 41 -28 64 4 -28 64 -1 28 64 -1 28 64 4 +4 16 40 4 -10 40 4 10 40 0 10 40 0 -10 +0 top +2 24 -27 4 -3 27 4 -3 +2 24 27 4 -3 29 4 -1 +2 24 29 4 -1 29 4 6 +2 24 29 4 6 29 4 6 +2 24 -27 4 -3 -29 4 -1 +2 24 -29 4 -1 -29 4 6 +4 16 -40 4 6 -29 4 6 -29 4 -1 -40 4 -10 +4 16 29 4 6 40 4 6 40 4 -10 29 4 -1 +3 16 29 4 -1 27 4 -3 40 4 -10 +3 16 -29 4 -1 -27 4 -3 -40 4 -10 +4 16 -27 4 -3 27 4 -3 40 4 -10 -40 4 -10 +4 41 -29 4 -1 -27 4 -3 27 4 -3 29 4 -1 +4 41 29 4 -1 29 4 6 -29 4 6 -29 4 -1 +0 +1 16 30 0 0 1 0 0 0 1 0 0 0 1 p/stud.dat +1 16 10 0 0 1 0 0 0 1 0 0 0 1 p/stud.dat +1 16 -10 0 0 1 0 0 0 1 0 0 0 1 p/stud.dat +1 16 -30 0 0 1 0 0 0 1 0 0 0 1 p/stud.dat +0 +0 FILE p/stud.dat +0 Stud +0 Name: stud.dat +0 Author: James Jessiman +0 !LDRAW_ORG Primitive UPDATE 2012-01 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 BFC CERTIFY CCW + +0 !HISTORY 2002-04-04 [sbliss] Modified for BFC compliance +0 !HISTORY 2002-04-25 [PTadmin] Official Update 2002-02 +0 !HISTORY 2007-06-24 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 +0 !HISTORY 2012-02-16 [Philo] Changed to CCW +0 !HISTORY 2012-03-30 [PTadmin] Official Update 2012-01 + +1 16 0 0 0 6 0 0 0 1 0 0 0 6 p/4-4edge.dat +1 16 0 -4 0 6 0 0 0 1 0 0 0 6 p/4-4edge.dat +1 16 0 0 0 6 0 0 0 -4 0 0 0 6 p/4-4cyli.dat +1 16 0 -4 0 6 0 0 0 1 0 0 0 6 p/4-4disc.dat + +0 FILE p/box4.dat +0 Box with 4 Faces (2 Parallel Pairs) and All Edges +0 Name: box4.dat +0 Author: James Jessiman +0 !LDRAW_ORG Primitive UPDATE 2012-01 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 BFC CERTIFY CCW + +0 !HISTORY 2002-04-03 [sbliss] Modified for BFC compliance +0 !HISTORY 2002-04-25 [PTadmin] Official Update 2002-02 +0 !HISTORY 2007-06-24 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 +0 !HISTORY 2012-02-16 [Philo] Changed to CCW +0 !HISTORY 2012-03-30 [PTadmin] Official Update 2012-01 + +2 24 1 1 1 -1 1 1 +2 24 -1 1 1 -1 1 -1 +2 24 -1 1 -1 1 1 -1 +2 24 1 1 -1 1 1 1 +2 24 1 0 1 -1 0 1 +2 24 -1 0 1 -1 0 -1 +2 24 -1 0 -1 1 0 -1 +2 24 1 0 -1 1 0 1 +2 24 1 0 1 1 1 1 +2 24 -1 0 1 -1 1 1 +2 24 1 0 -1 1 1 -1 +2 24 -1 0 -1 -1 1 -1 +4 16 -1 1 1 -1 0 1 1 0 1 1 1 1 +4 16 -1 1 -1 -1 0 -1 -1 0 1 -1 1 1 +4 16 1 1 -1 1 0 -1 -1 0 -1 -1 1 -1 +4 16 1 1 1 1 0 1 1 0 -1 1 1 -1 + +0 FILE p/stud3.dat +0 Stud Tube Solid +0 Name: stud3.dat +0 Author: James Jessiman +0 !LDRAW_ORG Primitive UPDATE 2012-01 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 BFC CERTIFY CCW + +0 !HISTORY 2002-04-04 [sbliss] Modified for BFC compliance +0 !HISTORY 2002-04-25 [PTadmin] Official Update 2002-02 +0 !HISTORY 2007-06-24 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 +0 !HISTORY 2012-02-16 [Philo] Changed to CCW +0 !HISTORY 2012-03-30 [PTadmin] Official Update 2012-01 + +1 16 0 -4 0 4 0 0 0 1 0 0 0 4 p/4-4edge.dat +1 16 0 0 0 4 0 0 0 1 0 0 0 4 p/4-4edge.dat +1 16 0 -4 0 4 0 0 0 1 0 0 0 4 p/4-4disc.dat +1 16 0 -4 0 4 0 0 0 4 0 0 0 4 p/4-4cyli.dat + +0 FILE p/4-4cyli.dat +0 Cylinder 1.0 +0 Name: 4-4cyli.dat +0 Author: James Jessiman +0 !LDRAW_ORG Primitive UPDATE 2005-01 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 BFC CERTIFY CCW + +0 !HISTORY 1998-12-15 [PTadmin] Official Update 1998-10 +0 !HISTORY 2002-03-23 [sbliss] Added BFC statement; merged headers from files in distributions LDraw 0.27 and Complete. +0 !HISTORY 2002-04-25 [PTadmin] Official Update 2002-02 +0 !HISTORY 2004-12-14 [guyvivan] BFC CCW +0 !HISTORY 2005-12-28 [PTadmin] Official Update 2005-01 +0 !HISTORY 2007-06-24 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 + +4 16 1 1 0 0.9239 1 0.3827 0.9239 0 0.3827 1 0 0 +5 24 1 0 0 1 1 0 0.9239 0 0.3827 0.9239 0 -0.3827 +4 16 0.9239 1 0.3827 0.7071 1 0.7071 0.7071 0 0.7071 0.9239 0 0.3827 +5 24 0.9239 0 0.3827 0.9239 1 0.3827 0.7071 0 0.7071 1 0 0 +4 16 0.7071 1 0.7071 0.3827 1 0.9239 0.3827 0 0.9239 0.7071 0 0.7071 +5 24 0.7071 0 0.7071 0.7071 1 0.7071 0.3827 0 0.9239 0.9239 0 0.3827 +4 16 0.3827 1 0.9239 0 1 1 0 0 1 0.3827 0 0.9239 +5 24 0.3827 0 0.9239 0.3827 1 0.9239 0 0 1 0.7071 0 0.7071 +4 16 0 1 1 -0.3827 1 0.9239 -0.3827 0 0.9239 0 0 1 +5 24 0 0 1 0 1 1 -0.3827 0 0.9239 0.3827 0 0.9239 +4 16 -0.3827 1 0.9239 -0.7071 1 0.7071 -0.7071 0 0.7071 -0.3827 0 0.9239 +5 24 -0.3827 0 0.9239 -0.3827 1 0.9239 -0.7071 0 0.7071 0 0 1 +4 16 -0.7071 1 0.7071 -0.9239 1 0.3827 -0.9239 0 0.3827 -0.7071 0 0.7071 +5 24 -0.7071 0 0.7071 -0.7071 1 0.7071 -0.9239 0 0.3827 -0.3827 0 0.9239 +4 16 -0.9239 1 0.3827 -1 1 0 -1 0 0 -0.9239 0 0.3827 +5 24 -0.9239 0 0.3827 -0.9239 1 0.3827 -1 0 0 -0.7071 0 0.7071 +4 16 -1 1 0 -0.9239 1 -0.3827 -0.9239 0 -0.3827 -1 0 0 +5 24 -1 0 0 -1 1 0 -0.9239 0 -0.3827 -0.9239 0 0.3827 +4 16 -0.9239 1 -0.3827 -0.7071 1 -0.7071 -0.7071 0 -0.7071 -0.9239 0 -0.3827 +5 24 -0.9239 0 -0.3827 -0.9239 1 -0.3827 -0.7071 0 -0.7071 -1 0 0 +4 16 -0.7071 1 -0.7071 -0.3827 1 -0.9239 -0.3827 0 -0.9239 -0.7071 0 -0.7071 +5 24 -0.7071 0 -0.7071 -0.7071 1 -0.7071 -0.3827 0 -0.9239 -0.9239 0 -0.3827 +4 16 -0.3827 1 -0.9239 0 1 -1 0 0 -1 -0.3827 0 -0.9239 +5 24 -0.3827 0 -0.9239 -0.3827 1 -0.9239 0 0 -1 -0.7071 0 -0.7071 +4 16 0 1 -1 0.3827 1 -0.9239 0.3827 0 -0.9239 0 0 -1 +5 24 0 0 -1 0 1 -1 0.3827 0 -0.9239 -0.3827 0 -0.9239 +4 16 0.3827 1 -0.9239 0.7071 1 -0.7071 0.7071 0 -0.7071 0.3827 0 -0.9239 +5 24 0.3827 0 -0.9239 0.3827 1 -0.9239 0.7071 0 -0.7071 0 0 -1 +4 16 0.7071 1 -0.7071 0.9239 1 -0.3827 0.9239 0 -0.3827 0.7071 0 -0.7071 +5 24 0.7071 0 -0.7071 0.7071 1 -0.7071 0.9239 0 -0.3827 0.3827 0 -0.9239 +4 16 0.9239 1 -0.3827 1 1 0 1 0 0 0.9239 0 -0.3827 +5 24 0.9239 0 -0.3827 0.9239 1 -0.3827 1 0 0 0.7071 0 -0.7071 +0 + +0 FILE p/4-4disc.dat +0 Disc 1.0 +0 Name: 4-4disc.dat +0 Author: James Jessiman +0 !LDRAW_ORG Primitive UPDATE 2002-02 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 BFC CERTIFY CCW + +0 !HISTORY 1998-12-15 [PTadmin] Official Update 1998-10 +0 !HISTORY 2002-03-23 [sbliss] Added BFC statement +0 !HISTORY 2002-04-25 [PTadmin] Official Update 2002-02 +0 !HISTORY 2007-06-24 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 + +3 16 0 0 0 1 0 0 0.9239 0 0.3827 +3 16 0 0 0 0.9239 0 0.3827 0.7071 0 0.7071 +3 16 0 0 0 0.7071 0 0.7071 0.3827 0 0.9239 +3 16 0 0 0 0.3827 0 0.9239 0 0 1 +3 16 0 0 0 0 0 1 -0.3827 0 0.9239 +3 16 0 0 0 -0.3827 0 0.9239 -0.7071 0 0.7071 +3 16 0 0 0 -0.7071 0 0.7071 -0.9239 0 0.3827 +3 16 0 0 0 -0.9239 0 0.3827 -1 0 -0 +3 16 0 0 0 -1 0 -0 -0.9239 0 -0.3827 +3 16 0 0 0 -0.9239 0 -0.3827 -0.7071 0 -0.7071 +3 16 0 0 0 -0.7071 0 -0.7071 -0.3827 0 -0.9239 +3 16 0 0 0 -0.3827 0 -0.9239 0 0 -1 +3 16 0 0 0 0 0 -1 0.3827 0 -0.9239 +3 16 0 0 0 0.3827 0 -0.9239 0.7071 0 -0.7071 +3 16 0 0 0 0.7071 0 -0.7071 0.9239 0 -0.3827 +3 16 0 0 0 0.9239 0 -0.3827 1 0 0 +0 + +0 FILE p/4-4edge.dat +0 Circle 1.0 +0 Name: 4-4edge.dat +0 Author: James Jessiman +0 !LDRAW_ORG Primitive UPDATE 2017-01 +0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt + +0 BFC CERTIFY CCW + +0 !HISTORY 1998-12-15 [PTadmin] Official Update 1998-10 +0 !HISTORY 2005-12-28 [PTadmin] Official Update 2005-01 +0 !HISTORY 2007-06-24 [PTadmin] Header formatted for Contributor Agreement +0 !HISTORY 2008-07-01 [PTadmin] Official Update 2008-01 +0 !HISTORY 2017-01-15 [Steffen] BFCed +0 !HISTORY 2017-12-30 [PTadmin] Official Update 2017-01 + +2 24 1 0 0 0.9239 0 0.3827 +2 24 0.9239 0 0.3827 0.7071 0 0.7071 +2 24 0.7071 0 0.7071 0.3827 0 0.9239 +2 24 0.3827 0 0.9239 0 0 1 +2 24 0 0 1 -0.3827 0 0.9239 +2 24 -0.3827 0 0.9239 -0.7071 0 0.7071 +2 24 -0.7071 0 0.7071 -0.9239 0 0.3827 +2 24 -0.9239 0 0.3827 -1 0 -0 +2 24 -1 0 -0 -0.9239 0 -0.3827 +2 24 -0.9239 0 -0.3827 -0.7071 0 -0.7071 +2 24 -0.7071 0 -0.7071 -0.3827 0 -0.9239 +2 24 -0.3827 0 -0.9239 0 0 -1 +2 24 0 0 -1 0.3827 0 -0.9239 +2 24 0.3827 0 -0.9239 0.7071 0 -0.7071 +2 24 0.7071 0 -0.7071 0.9239 0 -0.3827 +2 24 0.9239 0 -0.3827 1 0 0 + + diff --git a/examples/screenshots/css2d_label.jpg b/examples/screenshots/css2d_label.jpg index 45aa705ac0ff55..15b55279ecb6b7 100644 Binary files a/examples/screenshots/css2d_label.jpg and b/examples/screenshots/css2d_label.jpg differ diff --git a/examples/screenshots/css3d_molecules.jpg b/examples/screenshots/css3d_molecules.jpg index a19d5c5fac1d6f..7734c2e5b0e646 100644 Binary files a/examples/screenshots/css3d_molecules.jpg and b/examples/screenshots/css3d_molecules.jpg differ diff --git a/examples/screenshots/css3d_orthographic.jpg b/examples/screenshots/css3d_orthographic.jpg index d964c7e443b08a..2b26ab32b2a172 100644 Binary files a/examples/screenshots/css3d_orthographic.jpg and b/examples/screenshots/css3d_orthographic.jpg differ diff --git a/examples/screenshots/css3d_periodictable.jpg b/examples/screenshots/css3d_periodictable.jpg index 2aee6c312dff4e..48aee0b4b1fb2c 100644 Binary files a/examples/screenshots/css3d_periodictable.jpg and b/examples/screenshots/css3d_periodictable.jpg differ diff --git a/examples/screenshots/css3d_sandbox.jpg b/examples/screenshots/css3d_sandbox.jpg index cbf2a407189f84..bab3e9eaa9e6dd 100644 Binary files a/examples/screenshots/css3d_sandbox.jpg and b/examples/screenshots/css3d_sandbox.jpg differ diff --git a/examples/screenshots/css3d_sprites.jpg b/examples/screenshots/css3d_sprites.jpg index 7617f06d0137ec..70acbfe5c6ec4f 100644 Binary files a/examples/screenshots/css3d_sprites.jpg and b/examples/screenshots/css3d_sprites.jpg differ diff --git a/examples/screenshots/games_fps.jpg b/examples/screenshots/games_fps.jpg index 850daebde77789..e7911147889ad8 100644 Binary files a/examples/screenshots/games_fps.jpg and b/examples/screenshots/games_fps.jpg differ diff --git a/examples/screenshots/misc_animation_groups.jpg b/examples/screenshots/misc_animation_groups.jpg index a5cc7d5fab6bda..4e5defdbda3cce 100644 Binary files a/examples/screenshots/misc_animation_groups.jpg and b/examples/screenshots/misc_animation_groups.jpg differ diff --git a/examples/screenshots/misc_animation_keys.jpg b/examples/screenshots/misc_animation_keys.jpg index dd0ab52ec11c2e..fa0bbcd6126446 100644 Binary files a/examples/screenshots/misc_animation_keys.jpg and b/examples/screenshots/misc_animation_keys.jpg differ diff --git a/examples/screenshots/misc_boxselection.jpg b/examples/screenshots/misc_boxselection.jpg index 40e7cbb165bfa3..8e9c499676ba9c 100644 Binary files a/examples/screenshots/misc_boxselection.jpg and b/examples/screenshots/misc_boxselection.jpg differ diff --git a/examples/screenshots/misc_controls_arcball.jpg b/examples/screenshots/misc_controls_arcball.jpg index 9a468826d7cdfb..ba7b62e38a759c 100644 Binary files a/examples/screenshots/misc_controls_arcball.jpg and b/examples/screenshots/misc_controls_arcball.jpg differ diff --git a/examples/screenshots/misc_controls_drag.jpg b/examples/screenshots/misc_controls_drag.jpg index 9c6aff16d8bf2f..f89730594752d3 100644 Binary files a/examples/screenshots/misc_controls_drag.jpg and b/examples/screenshots/misc_controls_drag.jpg differ diff --git a/examples/screenshots/misc_controls_fly.jpg b/examples/screenshots/misc_controls_fly.jpg index 73205d8bf51cd0..c7f515fc802a3c 100644 Binary files a/examples/screenshots/misc_controls_fly.jpg and b/examples/screenshots/misc_controls_fly.jpg differ diff --git a/examples/screenshots/misc_controls_map.jpg b/examples/screenshots/misc_controls_map.jpg index 486d1a34b82cdd..1eb15ceca77f68 100644 Binary files a/examples/screenshots/misc_controls_map.jpg and b/examples/screenshots/misc_controls_map.jpg differ diff --git a/examples/screenshots/misc_controls_orbit.jpg b/examples/screenshots/misc_controls_orbit.jpg index 01cf1dfea4b719..fe9e18d4c66f40 100644 Binary files a/examples/screenshots/misc_controls_orbit.jpg and b/examples/screenshots/misc_controls_orbit.jpg differ diff --git a/examples/screenshots/misc_controls_pointerlock.jpg b/examples/screenshots/misc_controls_pointerlock.jpg index a9e579390ee9a6..edb33b130a0c4a 100644 Binary files a/examples/screenshots/misc_controls_pointerlock.jpg and b/examples/screenshots/misc_controls_pointerlock.jpg differ diff --git a/examples/screenshots/misc_controls_trackball.jpg b/examples/screenshots/misc_controls_trackball.jpg index 06c995fd84281d..130c1ccbf027f2 100644 Binary files a/examples/screenshots/misc_controls_trackball.jpg and b/examples/screenshots/misc_controls_trackball.jpg differ diff --git a/examples/screenshots/misc_controls_transform.jpg b/examples/screenshots/misc_controls_transform.jpg index c41fd4038ea427..3cf9a1dd830d9b 100644 Binary files a/examples/screenshots/misc_controls_transform.jpg and b/examples/screenshots/misc_controls_transform.jpg differ diff --git a/examples/screenshots/misc_exporter_draco.jpg b/examples/screenshots/misc_exporter_draco.jpg index 7c657cb116b204..0adbbf7e31480c 100644 Binary files a/examples/screenshots/misc_exporter_draco.jpg and b/examples/screenshots/misc_exporter_draco.jpg differ diff --git a/examples/screenshots/misc_exporter_exr.jpg b/examples/screenshots/misc_exporter_exr.jpg index a81c0014b5305e..81cab9bfabaa42 100644 Binary files a/examples/screenshots/misc_exporter_exr.jpg and b/examples/screenshots/misc_exporter_exr.jpg differ diff --git a/examples/screenshots/misc_exporter_gcode.jpg b/examples/screenshots/misc_exporter_gcode.jpg index 85bf3f80ce2a4a..98483feed4c5ab 100644 Binary files a/examples/screenshots/misc_exporter_gcode.jpg and b/examples/screenshots/misc_exporter_gcode.jpg differ diff --git a/examples/screenshots/misc_exporter_gltf.jpg b/examples/screenshots/misc_exporter_gltf.jpg index 6866d46dae5fe9..1ddc28808c6ec2 100644 Binary files a/examples/screenshots/misc_exporter_gltf.jpg and b/examples/screenshots/misc_exporter_gltf.jpg differ diff --git a/examples/screenshots/misc_exporter_ktx2.jpg b/examples/screenshots/misc_exporter_ktx2.jpg index cc5e34f4ebe326..2de0943d627d6a 100644 Binary files a/examples/screenshots/misc_exporter_ktx2.jpg and b/examples/screenshots/misc_exporter_ktx2.jpg differ diff --git a/examples/screenshots/misc_exporter_obj.jpg b/examples/screenshots/misc_exporter_obj.jpg index 0212e97a053c49..96f15b2a17b411 100644 Binary files a/examples/screenshots/misc_exporter_obj.jpg and b/examples/screenshots/misc_exporter_obj.jpg differ diff --git a/examples/screenshots/misc_exporter_ply.jpg b/examples/screenshots/misc_exporter_ply.jpg index 9396bbaf299e71..2fdd830213ec37 100644 Binary files a/examples/screenshots/misc_exporter_ply.jpg and b/examples/screenshots/misc_exporter_ply.jpg differ diff --git a/examples/screenshots/misc_exporter_stl.jpg b/examples/screenshots/misc_exporter_stl.jpg index 99aced410da549..d144ac36b3be27 100644 Binary files a/examples/screenshots/misc_exporter_stl.jpg and b/examples/screenshots/misc_exporter_stl.jpg differ diff --git a/examples/screenshots/misc_exporter_usdz.jpg b/examples/screenshots/misc_exporter_usdz.jpg index f690c9bc6d3279..ad1b20e71388b6 100644 Binary files a/examples/screenshots/misc_exporter_usdz.jpg and b/examples/screenshots/misc_exporter_usdz.jpg differ diff --git a/examples/screenshots/misc_raycaster_helper.jpg b/examples/screenshots/misc_raycaster_helper.jpg index 78326f3c1969f3..21a35c48fd3678 100644 Binary files a/examples/screenshots/misc_raycaster_helper.jpg and b/examples/screenshots/misc_raycaster_helper.jpg differ diff --git a/examples/screenshots/misc_uv_tests.jpg b/examples/screenshots/misc_uv_tests.jpg index af43f31e386db5..b3b31b31900b3b 100644 Binary files a/examples/screenshots/misc_uv_tests.jpg and b/examples/screenshots/misc_uv_tests.jpg differ diff --git a/examples/screenshots/physics_ammo_break.jpg b/examples/screenshots/physics_ammo_break.jpg index 9558f1b2ddbcab..6ac9575f5fbc11 100644 Binary files a/examples/screenshots/physics_ammo_break.jpg and b/examples/screenshots/physics_ammo_break.jpg differ diff --git a/examples/screenshots/physics_ammo_cloth.jpg b/examples/screenshots/physics_ammo_cloth.jpg index 7058a1414b57ce..b083eb4ac8116d 100644 Binary files a/examples/screenshots/physics_ammo_cloth.jpg and b/examples/screenshots/physics_ammo_cloth.jpg differ diff --git a/examples/screenshots/physics_ammo_instancing.jpg b/examples/screenshots/physics_ammo_instancing.jpg index 06267ec951871b..14c92bc3923cf1 100644 Binary files a/examples/screenshots/physics_ammo_instancing.jpg and b/examples/screenshots/physics_ammo_instancing.jpg differ diff --git a/examples/screenshots/physics_ammo_rope.jpg b/examples/screenshots/physics_ammo_rope.jpg index 4276aad98c7fab..806a29a149768e 100644 Binary files a/examples/screenshots/physics_ammo_rope.jpg and b/examples/screenshots/physics_ammo_rope.jpg differ diff --git a/examples/screenshots/physics_ammo_terrain.jpg b/examples/screenshots/physics_ammo_terrain.jpg index 6f8e6b6ae0068e..892922b2399ab1 100644 Binary files a/examples/screenshots/physics_ammo_terrain.jpg and b/examples/screenshots/physics_ammo_terrain.jpg differ diff --git a/examples/screenshots/physics_ammo_volume.jpg b/examples/screenshots/physics_ammo_volume.jpg index ab5a2e7eb55891..45a42ed55ec0a2 100644 Binary files a/examples/screenshots/physics_ammo_volume.jpg and b/examples/screenshots/physics_ammo_volume.jpg differ diff --git a/examples/screenshots/physics_jolt_instancing.jpg b/examples/screenshots/physics_jolt_instancing.jpg index c2d8f43418c2a8..202d827d5b4b2b 100644 Binary files a/examples/screenshots/physics_jolt_instancing.jpg and b/examples/screenshots/physics_jolt_instancing.jpg differ diff --git a/examples/screenshots/physics_rapier_basic.jpg b/examples/screenshots/physics_rapier_basic.jpg index d85ad0ea2e2c2f..2461ffeae8a350 100644 Binary files a/examples/screenshots/physics_rapier_basic.jpg and b/examples/screenshots/physics_rapier_basic.jpg differ diff --git a/examples/screenshots/physics_rapier_character_controller.jpg b/examples/screenshots/physics_rapier_character_controller.jpg index 32e9412a786aa9..e7c6a9f5b4eb25 100644 Binary files a/examples/screenshots/physics_rapier_character_controller.jpg and b/examples/screenshots/physics_rapier_character_controller.jpg differ diff --git a/examples/screenshots/physics_rapier_instancing.jpg b/examples/screenshots/physics_rapier_instancing.jpg index 8c42d0b05377e5..3246fbb84f9206 100644 Binary files a/examples/screenshots/physics_rapier_instancing.jpg and b/examples/screenshots/physics_rapier_instancing.jpg differ diff --git a/examples/screenshots/physics_rapier_joints.jpg b/examples/screenshots/physics_rapier_joints.jpg index 47d708b4549615..a6e1114c722b52 100644 Binary files a/examples/screenshots/physics_rapier_joints.jpg and b/examples/screenshots/physics_rapier_joints.jpg differ diff --git a/examples/screenshots/physics_rapier_terrain.jpg b/examples/screenshots/physics_rapier_terrain.jpg index 6f8e6b6ae0068e..892922b2399ab1 100644 Binary files a/examples/screenshots/physics_rapier_terrain.jpg and b/examples/screenshots/physics_rapier_terrain.jpg differ diff --git a/examples/screenshots/physics_rapier_vehicle_controller.jpg b/examples/screenshots/physics_rapier_vehicle_controller.jpg index 41738dfedc297e..7c335aad23e136 100644 Binary files a/examples/screenshots/physics_rapier_vehicle_controller.jpg and b/examples/screenshots/physics_rapier_vehicle_controller.jpg differ diff --git a/examples/screenshots/svg_lines.jpg b/examples/screenshots/svg_lines.jpg index 82e4ceb456d6fd..e1e2b6459c4b6e 100644 Binary files a/examples/screenshots/svg_lines.jpg and b/examples/screenshots/svg_lines.jpg differ diff --git a/examples/screenshots/svg_sandbox.jpg b/examples/screenshots/svg_sandbox.jpg index 4664781665dfbc..777a770e73b623 100644 Binary files a/examples/screenshots/svg_sandbox.jpg and b/examples/screenshots/svg_sandbox.jpg differ diff --git a/examples/screenshots/webaudio_orientation.jpg b/examples/screenshots/webaudio_orientation.jpg index 71d66851cd391b..7290401997e7a3 100644 Binary files a/examples/screenshots/webaudio_orientation.jpg and b/examples/screenshots/webaudio_orientation.jpg differ diff --git a/examples/screenshots/webaudio_sandbox.jpg b/examples/screenshots/webaudio_sandbox.jpg index 6637a252210d7d..4a1a9ddf01a069 100644 Binary files a/examples/screenshots/webaudio_sandbox.jpg and b/examples/screenshots/webaudio_sandbox.jpg differ diff --git a/examples/screenshots/webaudio_timing.jpg b/examples/screenshots/webaudio_timing.jpg index 7434a7f9506f03..b668660b48a987 100644 Binary files a/examples/screenshots/webaudio_timing.jpg and b/examples/screenshots/webaudio_timing.jpg differ diff --git a/examples/screenshots/webaudio_visualizer.jpg b/examples/screenshots/webaudio_visualizer.jpg index 783d31abca3d66..6246b7f6eb0eca 100644 Binary files a/examples/screenshots/webaudio_visualizer.jpg and b/examples/screenshots/webaudio_visualizer.jpg differ diff --git a/examples/screenshots/webgl_animation_keyframes.jpg b/examples/screenshots/webgl_animation_keyframes.jpg index a73335ccfc9894..e8ab2af72e7592 100644 Binary files a/examples/screenshots/webgl_animation_keyframes.jpg and b/examples/screenshots/webgl_animation_keyframes.jpg differ diff --git a/examples/screenshots/webgl_animation_multiple.jpg b/examples/screenshots/webgl_animation_multiple.jpg index 091f4059b1ebe4..824a4393d5df04 100644 Binary files a/examples/screenshots/webgl_animation_multiple.jpg and b/examples/screenshots/webgl_animation_multiple.jpg differ diff --git a/examples/screenshots/webgl_animation_skinning_additive_blending.jpg b/examples/screenshots/webgl_animation_skinning_additive_blending.jpg index bf61a83ff8ee7b..e8567217fc5b55 100644 Binary files a/examples/screenshots/webgl_animation_skinning_additive_blending.jpg and b/examples/screenshots/webgl_animation_skinning_additive_blending.jpg differ diff --git a/examples/screenshots/webgl_animation_skinning_blending.jpg b/examples/screenshots/webgl_animation_skinning_blending.jpg index 271358537b7fa6..ffbbfb2394adb8 100644 Binary files a/examples/screenshots/webgl_animation_skinning_blending.jpg and b/examples/screenshots/webgl_animation_skinning_blending.jpg differ diff --git a/examples/screenshots/webgl_animation_skinning_ik.jpg b/examples/screenshots/webgl_animation_skinning_ik.jpg index 64d367821e8247..58b36f93e37e55 100644 Binary files a/examples/screenshots/webgl_animation_skinning_ik.jpg and b/examples/screenshots/webgl_animation_skinning_ik.jpg differ diff --git a/examples/screenshots/webgl_animation_skinning_morph.jpg b/examples/screenshots/webgl_animation_skinning_morph.jpg index 1ef86583e0247e..133879f731a985 100644 Binary files a/examples/screenshots/webgl_animation_skinning_morph.jpg and b/examples/screenshots/webgl_animation_skinning_morph.jpg differ diff --git a/examples/screenshots/webgl_animation_walk.jpg b/examples/screenshots/webgl_animation_walk.jpg index 88982e1f454318..1b5221c8b779a5 100644 Binary files a/examples/screenshots/webgl_animation_walk.jpg and b/examples/screenshots/webgl_animation_walk.jpg differ diff --git a/examples/screenshots/webgl_batch_lod_bvh.jpg b/examples/screenshots/webgl_batch_lod_bvh.jpg index 14c5780a879ef8..6b248df9596c6a 100644 Binary files a/examples/screenshots/webgl_batch_lod_bvh.jpg and b/examples/screenshots/webgl_batch_lod_bvh.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry.jpg b/examples/screenshots/webgl_buffergeometry.jpg index 545835550c29c8..e19174fb4199e3 100644 Binary files a/examples/screenshots/webgl_buffergeometry.jpg and b/examples/screenshots/webgl_buffergeometry.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_attributes_integer.jpg b/examples/screenshots/webgl_buffergeometry_attributes_integer.jpg index c1e8e942cfad06..3b42cff6cf2aed 100644 Binary files a/examples/screenshots/webgl_buffergeometry_attributes_integer.jpg and b/examples/screenshots/webgl_buffergeometry_attributes_integer.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_attributes_none.jpg b/examples/screenshots/webgl_buffergeometry_attributes_none.jpg index f3c0a2f2dbf9d3..1e4d6413322d1d 100644 Binary files a/examples/screenshots/webgl_buffergeometry_attributes_none.jpg and b/examples/screenshots/webgl_buffergeometry_attributes_none.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_custom_attributes_particles.jpg b/examples/screenshots/webgl_buffergeometry_custom_attributes_particles.jpg index ac15ba37c0e075..2c8ad164321a58 100644 Binary files a/examples/screenshots/webgl_buffergeometry_custom_attributes_particles.jpg and b/examples/screenshots/webgl_buffergeometry_custom_attributes_particles.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_drawrange.jpg b/examples/screenshots/webgl_buffergeometry_drawrange.jpg index 318e75a7a38b75..0a6fe51ca220f8 100644 Binary files a/examples/screenshots/webgl_buffergeometry_drawrange.jpg and b/examples/screenshots/webgl_buffergeometry_drawrange.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_glbufferattribute.jpg b/examples/screenshots/webgl_buffergeometry_glbufferattribute.jpg index 3361c2cfcd835d..7ca979ab6da308 100644 Binary files a/examples/screenshots/webgl_buffergeometry_glbufferattribute.jpg and b/examples/screenshots/webgl_buffergeometry_glbufferattribute.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_indexed.jpg b/examples/screenshots/webgl_buffergeometry_indexed.jpg index 876778fc75b1f7..8b6cee8ef258f2 100644 Binary files a/examples/screenshots/webgl_buffergeometry_indexed.jpg and b/examples/screenshots/webgl_buffergeometry_indexed.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_instancing.jpg b/examples/screenshots/webgl_buffergeometry_instancing.jpg index 497fb97a84f97c..9cb95456b278b8 100644 Binary files a/examples/screenshots/webgl_buffergeometry_instancing.jpg and b/examples/screenshots/webgl_buffergeometry_instancing.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_instancing_billboards.jpg b/examples/screenshots/webgl_buffergeometry_instancing_billboards.jpg index ff3918d028ea5c..bccafa0e7a94b1 100644 Binary files a/examples/screenshots/webgl_buffergeometry_instancing_billboards.jpg and b/examples/screenshots/webgl_buffergeometry_instancing_billboards.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_instancing_interleaved.jpg b/examples/screenshots/webgl_buffergeometry_instancing_interleaved.jpg index b6fca3963e9cac..ad1e4f527c5e24 100644 Binary files a/examples/screenshots/webgl_buffergeometry_instancing_interleaved.jpg and b/examples/screenshots/webgl_buffergeometry_instancing_interleaved.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_lines.jpg b/examples/screenshots/webgl_buffergeometry_lines.jpg index e9eb0f9cbdf22d..c131ca3baa4328 100644 Binary files a/examples/screenshots/webgl_buffergeometry_lines.jpg and b/examples/screenshots/webgl_buffergeometry_lines.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_lines_indexed.jpg b/examples/screenshots/webgl_buffergeometry_lines_indexed.jpg index be3f59cc5a4daa..7e2c7210664132 100644 Binary files a/examples/screenshots/webgl_buffergeometry_lines_indexed.jpg and b/examples/screenshots/webgl_buffergeometry_lines_indexed.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_points.jpg b/examples/screenshots/webgl_buffergeometry_points.jpg index 46b4f70c20bf25..972f621fe99653 100644 Binary files a/examples/screenshots/webgl_buffergeometry_points.jpg and b/examples/screenshots/webgl_buffergeometry_points.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_points_interleaved.jpg b/examples/screenshots/webgl_buffergeometry_points_interleaved.jpg index ee53384ce6a0cb..ac852fbdcbc145 100644 Binary files a/examples/screenshots/webgl_buffergeometry_points_interleaved.jpg and b/examples/screenshots/webgl_buffergeometry_points_interleaved.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_rawshader.jpg b/examples/screenshots/webgl_buffergeometry_rawshader.jpg index d4590d0a7e5585..f02ed9e6dd4056 100644 Binary files a/examples/screenshots/webgl_buffergeometry_rawshader.jpg and b/examples/screenshots/webgl_buffergeometry_rawshader.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_selective_draw.jpg b/examples/screenshots/webgl_buffergeometry_selective_draw.jpg index 4fef422b8dfae6..6b5a301dbd9fd5 100644 Binary files a/examples/screenshots/webgl_buffergeometry_selective_draw.jpg and b/examples/screenshots/webgl_buffergeometry_selective_draw.jpg differ diff --git a/examples/screenshots/webgl_buffergeometry_uint.jpg b/examples/screenshots/webgl_buffergeometry_uint.jpg index afd1bfcf63ba55..7a13466857f92d 100644 Binary files a/examples/screenshots/webgl_buffergeometry_uint.jpg and b/examples/screenshots/webgl_buffergeometry_uint.jpg differ diff --git a/examples/screenshots/webgl_camera.jpg b/examples/screenshots/webgl_camera.jpg index 7e142b0890f3ac..6479f37140c8fe 100644 Binary files a/examples/screenshots/webgl_camera.jpg and b/examples/screenshots/webgl_camera.jpg differ diff --git a/examples/screenshots/webgl_camera_array.jpg b/examples/screenshots/webgl_camera_array.jpg index b06e816b42da53..87812d1da85c41 100644 Binary files a/examples/screenshots/webgl_camera_array.jpg and b/examples/screenshots/webgl_camera_array.jpg differ diff --git a/examples/screenshots/webgl_camera_logarithmicdepthbuffer.jpg b/examples/screenshots/webgl_camera_logarithmicdepthbuffer.jpg index 2d28c344720535..3cfeafaf40f513 100644 Binary files a/examples/screenshots/webgl_camera_logarithmicdepthbuffer.jpg and b/examples/screenshots/webgl_camera_logarithmicdepthbuffer.jpg differ diff --git a/examples/screenshots/webgl_clipculldistance.jpg b/examples/screenshots/webgl_clipculldistance.jpg index 0117e58b342d7b..f4c54d09d5cc4e 100644 Binary files a/examples/screenshots/webgl_clipculldistance.jpg and b/examples/screenshots/webgl_clipculldistance.jpg differ diff --git a/examples/screenshots/webgl_clipping.jpg b/examples/screenshots/webgl_clipping.jpg index 27c6a6e0fea089..11697e1495e675 100644 Binary files a/examples/screenshots/webgl_clipping.jpg and b/examples/screenshots/webgl_clipping.jpg differ diff --git a/examples/screenshots/webgl_clipping_advanced.jpg b/examples/screenshots/webgl_clipping_advanced.jpg index 45b9475fe01066..9d80a30a5d077a 100644 Binary files a/examples/screenshots/webgl_clipping_advanced.jpg and b/examples/screenshots/webgl_clipping_advanced.jpg differ diff --git a/examples/screenshots/webgl_clipping_intersection.jpg b/examples/screenshots/webgl_clipping_intersection.jpg index 1daecbd42e5fa4..a93642d7108936 100644 Binary files a/examples/screenshots/webgl_clipping_intersection.jpg and b/examples/screenshots/webgl_clipping_intersection.jpg differ diff --git a/examples/screenshots/webgl_clipping_stencil.jpg b/examples/screenshots/webgl_clipping_stencil.jpg index b322a4d0fee009..81738b7e3197ca 100644 Binary files a/examples/screenshots/webgl_clipping_stencil.jpg and b/examples/screenshots/webgl_clipping_stencil.jpg differ diff --git a/examples/screenshots/webgl_custom_attributes.jpg b/examples/screenshots/webgl_custom_attributes.jpg index 48f8d3def67182..7d2f32878d5263 100644 Binary files a/examples/screenshots/webgl_custom_attributes.jpg and b/examples/screenshots/webgl_custom_attributes.jpg differ diff --git a/examples/screenshots/webgl_custom_attributes_lines.jpg b/examples/screenshots/webgl_custom_attributes_lines.jpg index 16d52e2aa8f6a7..9605a3bc3d9c7c 100644 Binary files a/examples/screenshots/webgl_custom_attributes_lines.jpg and b/examples/screenshots/webgl_custom_attributes_lines.jpg differ diff --git a/examples/screenshots/webgl_custom_attributes_points.jpg b/examples/screenshots/webgl_custom_attributes_points.jpg index c4966a40c7b349..ccb428edb45b9e 100644 Binary files a/examples/screenshots/webgl_custom_attributes_points.jpg and b/examples/screenshots/webgl_custom_attributes_points.jpg differ diff --git a/examples/screenshots/webgl_custom_attributes_points2.jpg b/examples/screenshots/webgl_custom_attributes_points2.jpg index e00eff6d3835b9..a84cd2b3d90c34 100644 Binary files a/examples/screenshots/webgl_custom_attributes_points2.jpg and b/examples/screenshots/webgl_custom_attributes_points2.jpg differ diff --git a/examples/screenshots/webgl_custom_attributes_points3.jpg b/examples/screenshots/webgl_custom_attributes_points3.jpg index 7f0947e82ef701..6a59f949142df2 100644 Binary files a/examples/screenshots/webgl_custom_attributes_points3.jpg and b/examples/screenshots/webgl_custom_attributes_points3.jpg differ diff --git a/examples/screenshots/webgl_decals.jpg b/examples/screenshots/webgl_decals.jpg index c753ae42e759f4..a130d44cc2e372 100644 Binary files a/examples/screenshots/webgl_decals.jpg and b/examples/screenshots/webgl_decals.jpg differ diff --git a/examples/screenshots/webgl_depth_texture.jpg b/examples/screenshots/webgl_depth_texture.jpg index 4910ba12268fa4..6c59757e1e362a 100644 Binary files a/examples/screenshots/webgl_depth_texture.jpg and b/examples/screenshots/webgl_depth_texture.jpg differ diff --git a/examples/screenshots/webgl_effects_anaglyph.jpg b/examples/screenshots/webgl_effects_anaglyph.jpg index 610dbaa0f4eeae..a3d5f6f4341958 100644 Binary files a/examples/screenshots/webgl_effects_anaglyph.jpg and b/examples/screenshots/webgl_effects_anaglyph.jpg differ diff --git a/examples/screenshots/webgl_effects_ascii.jpg b/examples/screenshots/webgl_effects_ascii.jpg index fc2ac64269e75e..82a8fb3c846103 100644 Binary files a/examples/screenshots/webgl_effects_ascii.jpg and b/examples/screenshots/webgl_effects_ascii.jpg differ diff --git a/examples/screenshots/webgl_effects_parallaxbarrier.jpg b/examples/screenshots/webgl_effects_parallaxbarrier.jpg index 78b8474429d9e6..47ee741de2e4d2 100644 Binary files a/examples/screenshots/webgl_effects_parallaxbarrier.jpg and b/examples/screenshots/webgl_effects_parallaxbarrier.jpg differ diff --git a/examples/screenshots/webgl_effects_stereo.jpg b/examples/screenshots/webgl_effects_stereo.jpg index 4aaf721fa3069d..96073a33a98ce5 100644 Binary files a/examples/screenshots/webgl_effects_stereo.jpg and b/examples/screenshots/webgl_effects_stereo.jpg differ diff --git a/examples/screenshots/webgl_framebuffer_texture.jpg b/examples/screenshots/webgl_framebuffer_texture.jpg index aa2470aad1dc73..c09ffe36813ca6 100644 Binary files a/examples/screenshots/webgl_framebuffer_texture.jpg and b/examples/screenshots/webgl_framebuffer_texture.jpg differ diff --git a/examples/screenshots/webgl_furnace_test.jpg b/examples/screenshots/webgl_furnace_test.jpg index 83c692aa5dd661..0fd4bd19d59759 100644 Binary files a/examples/screenshots/webgl_furnace_test.jpg and b/examples/screenshots/webgl_furnace_test.jpg differ diff --git a/examples/screenshots/webgl_geometries.jpg b/examples/screenshots/webgl_geometries.jpg index f496bd9fa4b855..bda8d8f96b614a 100644 Binary files a/examples/screenshots/webgl_geometries.jpg and b/examples/screenshots/webgl_geometries.jpg differ diff --git a/examples/screenshots/webgl_geometry_colors.jpg b/examples/screenshots/webgl_geometry_colors.jpg index e194b506a3a11c..14efc190c06429 100644 Binary files a/examples/screenshots/webgl_geometry_colors.jpg and b/examples/screenshots/webgl_geometry_colors.jpg differ diff --git a/examples/screenshots/webgl_geometry_colors_lookuptable.jpg b/examples/screenshots/webgl_geometry_colors_lookuptable.jpg index ed8539f8e7617b..615c3195cac937 100644 Binary files a/examples/screenshots/webgl_geometry_colors_lookuptable.jpg and b/examples/screenshots/webgl_geometry_colors_lookuptable.jpg differ diff --git a/examples/screenshots/webgl_geometry_convex.jpg b/examples/screenshots/webgl_geometry_convex.jpg index 544abcb81654cf..8f682f1fab5756 100644 Binary files a/examples/screenshots/webgl_geometry_convex.jpg and b/examples/screenshots/webgl_geometry_convex.jpg differ diff --git a/examples/screenshots/webgl_geometry_csg.jpg b/examples/screenshots/webgl_geometry_csg.jpg index ca5b34b00507e7..155d6a9b873462 100644 Binary files a/examples/screenshots/webgl_geometry_csg.jpg and b/examples/screenshots/webgl_geometry_csg.jpg differ diff --git a/examples/screenshots/webgl_geometry_cube.jpg b/examples/screenshots/webgl_geometry_cube.jpg index bb63794fe81616..e9518eca62ad56 100644 Binary files a/examples/screenshots/webgl_geometry_cube.jpg and b/examples/screenshots/webgl_geometry_cube.jpg differ diff --git a/examples/screenshots/webgl_geometry_extrude_shapes.jpg b/examples/screenshots/webgl_geometry_extrude_shapes.jpg index a0f14d4d9aea71..128e7969747442 100644 Binary files a/examples/screenshots/webgl_geometry_extrude_shapes.jpg and b/examples/screenshots/webgl_geometry_extrude_shapes.jpg differ diff --git a/examples/screenshots/webgl_geometry_extrude_splines.jpg b/examples/screenshots/webgl_geometry_extrude_splines.jpg index 387c80c166ae95..d3cd9213169fe5 100644 Binary files a/examples/screenshots/webgl_geometry_extrude_splines.jpg and b/examples/screenshots/webgl_geometry_extrude_splines.jpg differ diff --git a/examples/screenshots/webgl_geometry_minecraft.jpg b/examples/screenshots/webgl_geometry_minecraft.jpg index bf990cc124857d..559ce833fe5467 100644 Binary files a/examples/screenshots/webgl_geometry_minecraft.jpg and b/examples/screenshots/webgl_geometry_minecraft.jpg differ diff --git a/examples/screenshots/webgl_geometry_nurbs.jpg b/examples/screenshots/webgl_geometry_nurbs.jpg index a0a7c541a78c74..a20d460cbf3c8b 100644 Binary files a/examples/screenshots/webgl_geometry_nurbs.jpg and b/examples/screenshots/webgl_geometry_nurbs.jpg differ diff --git a/examples/screenshots/webgl_geometry_shapes.jpg b/examples/screenshots/webgl_geometry_shapes.jpg index cdbc4eab72f384..e3dad1555f6a4b 100644 Binary files a/examples/screenshots/webgl_geometry_shapes.jpg and b/examples/screenshots/webgl_geometry_shapes.jpg differ diff --git a/examples/screenshots/webgl_geometry_spline_editor.jpg b/examples/screenshots/webgl_geometry_spline_editor.jpg index 20dae59d25c932..9ce6aac08f3485 100644 Binary files a/examples/screenshots/webgl_geometry_spline_editor.jpg and b/examples/screenshots/webgl_geometry_spline_editor.jpg differ diff --git a/examples/screenshots/webgl_geometry_teapot.jpg b/examples/screenshots/webgl_geometry_teapot.jpg index 8dc764bfcdef31..a55622c80d6f8e 100644 Binary files a/examples/screenshots/webgl_geometry_teapot.jpg and b/examples/screenshots/webgl_geometry_teapot.jpg differ diff --git a/examples/screenshots/webgl_geometry_terrain.jpg b/examples/screenshots/webgl_geometry_terrain.jpg index 4dbb711d5636a2..e61ff5d1dfb1c9 100644 Binary files a/examples/screenshots/webgl_geometry_terrain.jpg and b/examples/screenshots/webgl_geometry_terrain.jpg differ diff --git a/examples/screenshots/webgl_geometry_terrain_raycast.jpg b/examples/screenshots/webgl_geometry_terrain_raycast.jpg index 42c77fd739b713..2b16dc703eca9b 100644 Binary files a/examples/screenshots/webgl_geometry_terrain_raycast.jpg and b/examples/screenshots/webgl_geometry_terrain_raycast.jpg differ diff --git a/examples/screenshots/webgl_geometry_text.jpg b/examples/screenshots/webgl_geometry_text.jpg index 11d6c3e6d2bbf0..be3c616629fcdf 100644 Binary files a/examples/screenshots/webgl_geometry_text.jpg and b/examples/screenshots/webgl_geometry_text.jpg differ diff --git a/examples/screenshots/webgl_geometry_text_shapes.jpg b/examples/screenshots/webgl_geometry_text_shapes.jpg index 7fb3f4a685872f..54613617c63a2d 100644 Binary files a/examples/screenshots/webgl_geometry_text_shapes.jpg and b/examples/screenshots/webgl_geometry_text_shapes.jpg differ diff --git a/examples/screenshots/webgl_geometry_text_stroke.jpg b/examples/screenshots/webgl_geometry_text_stroke.jpg index c96fd67cea2496..503e4e34b4c521 100644 Binary files a/examples/screenshots/webgl_geometry_text_stroke.jpg and b/examples/screenshots/webgl_geometry_text_stroke.jpg differ diff --git a/examples/screenshots/webgl_gpgpu_birds.jpg b/examples/screenshots/webgl_gpgpu_birds.jpg index 85a3ad84bf60eb..1b7311b9cc59e5 100644 Binary files a/examples/screenshots/webgl_gpgpu_birds.jpg and b/examples/screenshots/webgl_gpgpu_birds.jpg differ diff --git a/examples/screenshots/webgl_gpgpu_birds_gltf.jpg b/examples/screenshots/webgl_gpgpu_birds_gltf.jpg index 993fde0bb80830..71d353179659e3 100644 Binary files a/examples/screenshots/webgl_gpgpu_birds_gltf.jpg and b/examples/screenshots/webgl_gpgpu_birds_gltf.jpg differ diff --git a/examples/screenshots/webgl_gpgpu_protoplanet.jpg b/examples/screenshots/webgl_gpgpu_protoplanet.jpg index f2ce7f3c490a41..500feb261510e4 100644 Binary files a/examples/screenshots/webgl_gpgpu_protoplanet.jpg and b/examples/screenshots/webgl_gpgpu_protoplanet.jpg differ diff --git a/examples/screenshots/webgl_gpgpu_water.jpg b/examples/screenshots/webgl_gpgpu_water.jpg index 43c3b64ebeb46b..ee89a706015600 100644 Binary files a/examples/screenshots/webgl_gpgpu_water.jpg and b/examples/screenshots/webgl_gpgpu_water.jpg differ diff --git a/examples/screenshots/webgl_helpers.jpg b/examples/screenshots/webgl_helpers.jpg index 8240f8eb844ee4..bd527777102ccf 100644 Binary files a/examples/screenshots/webgl_helpers.jpg and b/examples/screenshots/webgl_helpers.jpg differ diff --git a/examples/screenshots/webgl_instancing_dynamic.jpg b/examples/screenshots/webgl_instancing_dynamic.jpg index 2ad100785a0c66..1db28cbfa18349 100644 Binary files a/examples/screenshots/webgl_instancing_dynamic.jpg and b/examples/screenshots/webgl_instancing_dynamic.jpg differ diff --git a/examples/screenshots/webgl_instancing_morph.jpg b/examples/screenshots/webgl_instancing_morph.jpg index 2f1c089f0307fd..e0cf4e6512e371 100644 Binary files a/examples/screenshots/webgl_instancing_morph.jpg and b/examples/screenshots/webgl_instancing_morph.jpg differ diff --git a/examples/screenshots/webgl_instancing_performance.jpg b/examples/screenshots/webgl_instancing_performance.jpg index 90bade50524b7d..796ecc81e9a2d0 100644 Binary files a/examples/screenshots/webgl_instancing_performance.jpg and b/examples/screenshots/webgl_instancing_performance.jpg differ diff --git a/examples/screenshots/webgl_instancing_raycast.jpg b/examples/screenshots/webgl_instancing_raycast.jpg index c925d694f5afce..392addff0df4b5 100644 Binary files a/examples/screenshots/webgl_instancing_raycast.jpg and b/examples/screenshots/webgl_instancing_raycast.jpg differ diff --git a/examples/screenshots/webgl_instancing_scatter.jpg b/examples/screenshots/webgl_instancing_scatter.jpg index 703cf8dcfe16d5..8611e50f6ad63b 100644 Binary files a/examples/screenshots/webgl_instancing_scatter.jpg and b/examples/screenshots/webgl_instancing_scatter.jpg differ diff --git a/examples/screenshots/webgl_interactive_buffergeometry.jpg b/examples/screenshots/webgl_interactive_buffergeometry.jpg index 255fbad16e8171..5d07133dc7024e 100644 Binary files a/examples/screenshots/webgl_interactive_buffergeometry.jpg and b/examples/screenshots/webgl_interactive_buffergeometry.jpg differ diff --git a/examples/screenshots/webgl_interactive_cubes.jpg b/examples/screenshots/webgl_interactive_cubes.jpg index f281a845cb38d4..bb18b3483880cb 100644 Binary files a/examples/screenshots/webgl_interactive_cubes.jpg and b/examples/screenshots/webgl_interactive_cubes.jpg differ diff --git a/examples/screenshots/webgl_interactive_cubes_gpu.jpg b/examples/screenshots/webgl_interactive_cubes_gpu.jpg index 3849be90bb38fd..3e330fffefc502 100644 Binary files a/examples/screenshots/webgl_interactive_cubes_gpu.jpg and b/examples/screenshots/webgl_interactive_cubes_gpu.jpg differ diff --git a/examples/screenshots/webgl_interactive_cubes_ortho.jpg b/examples/screenshots/webgl_interactive_cubes_ortho.jpg index 2ae66f1941a99c..3ff79bac8168b0 100644 Binary files a/examples/screenshots/webgl_interactive_cubes_ortho.jpg and b/examples/screenshots/webgl_interactive_cubes_ortho.jpg differ diff --git a/examples/screenshots/webgl_interactive_lines.jpg b/examples/screenshots/webgl_interactive_lines.jpg index c90079c2f99c7d..4577cc278ed962 100644 Binary files a/examples/screenshots/webgl_interactive_lines.jpg and b/examples/screenshots/webgl_interactive_lines.jpg differ diff --git a/examples/screenshots/webgl_interactive_points.jpg b/examples/screenshots/webgl_interactive_points.jpg index 0717aa4d04fcd4..00ce57b035562e 100644 Binary files a/examples/screenshots/webgl_interactive_points.jpg and b/examples/screenshots/webgl_interactive_points.jpg differ diff --git a/examples/screenshots/webgl_interactive_raycasting_points.jpg b/examples/screenshots/webgl_interactive_raycasting_points.jpg index da5d8907846907..9827dd3645ced5 100644 Binary files a/examples/screenshots/webgl_interactive_raycasting_points.jpg and b/examples/screenshots/webgl_interactive_raycasting_points.jpg differ diff --git a/examples/screenshots/webgl_interactive_voxelpainter.jpg b/examples/screenshots/webgl_interactive_voxelpainter.jpg index bf5ab7cf9417b9..4450dbde6fe1d2 100644 Binary files a/examples/screenshots/webgl_interactive_voxelpainter.jpg and b/examples/screenshots/webgl_interactive_voxelpainter.jpg differ diff --git a/examples/screenshots/webgl_lensflares.jpg b/examples/screenshots/webgl_lensflares.jpg index ab14300b09b971..d48d26de01086d 100644 Binary files a/examples/screenshots/webgl_lensflares.jpg and b/examples/screenshots/webgl_lensflares.jpg differ diff --git a/examples/screenshots/webgl_lightprobe.jpg b/examples/screenshots/webgl_lightprobe.jpg index b371031b941d0e..b97e5002a84c09 100644 Binary files a/examples/screenshots/webgl_lightprobe.jpg and b/examples/screenshots/webgl_lightprobe.jpg differ diff --git a/examples/screenshots/webgl_lightprobe_cubecamera.jpg b/examples/screenshots/webgl_lightprobe_cubecamera.jpg index 2ae40ed5e11846..591dbf50ff7257 100644 Binary files a/examples/screenshots/webgl_lightprobe_cubecamera.jpg and b/examples/screenshots/webgl_lightprobe_cubecamera.jpg differ diff --git a/examples/screenshots/webgl_lights_hemisphere.jpg b/examples/screenshots/webgl_lights_hemisphere.jpg index b0e4c05032f7c3..896c94f05d4745 100644 Binary files a/examples/screenshots/webgl_lights_hemisphere.jpg and b/examples/screenshots/webgl_lights_hemisphere.jpg differ diff --git a/examples/screenshots/webgl_lights_physical.jpg b/examples/screenshots/webgl_lights_physical.jpg index 1e86b3a97d8c87..cf6c4ff1d32afd 100644 Binary files a/examples/screenshots/webgl_lights_physical.jpg and b/examples/screenshots/webgl_lights_physical.jpg differ diff --git a/examples/screenshots/webgl_lights_rectarealight.jpg b/examples/screenshots/webgl_lights_rectarealight.jpg index 856bdaac309896..63592967dfbddc 100644 Binary files a/examples/screenshots/webgl_lights_rectarealight.jpg and b/examples/screenshots/webgl_lights_rectarealight.jpg differ diff --git a/examples/screenshots/webgl_lights_spotlight.jpg b/examples/screenshots/webgl_lights_spotlight.jpg index 51052afaf0f60b..841a74b4df2179 100644 Binary files a/examples/screenshots/webgl_lights_spotlight.jpg and b/examples/screenshots/webgl_lights_spotlight.jpg differ diff --git a/examples/screenshots/webgl_lights_spotlights.jpg b/examples/screenshots/webgl_lights_spotlights.jpg index f8473994c55ff4..856f91d59936c3 100644 Binary files a/examples/screenshots/webgl_lights_spotlights.jpg and b/examples/screenshots/webgl_lights_spotlights.jpg differ diff --git a/examples/screenshots/webgl_lines_colors.jpg b/examples/screenshots/webgl_lines_colors.jpg index c2c699de28417f..fd4008bb0076d8 100644 Binary files a/examples/screenshots/webgl_lines_colors.jpg and b/examples/screenshots/webgl_lines_colors.jpg differ diff --git a/examples/screenshots/webgl_lines_dashed.jpg b/examples/screenshots/webgl_lines_dashed.jpg index 0ce0037e290a08..f225647fc81701 100644 Binary files a/examples/screenshots/webgl_lines_dashed.jpg and b/examples/screenshots/webgl_lines_dashed.jpg differ diff --git a/examples/screenshots/webgl_lines_fat.jpg b/examples/screenshots/webgl_lines_fat.jpg index 5254df07789ced..807590230dc0ea 100644 Binary files a/examples/screenshots/webgl_lines_fat.jpg and b/examples/screenshots/webgl_lines_fat.jpg differ diff --git a/examples/screenshots/webgl_lines_fat_raycasting.jpg b/examples/screenshots/webgl_lines_fat_raycasting.jpg index 40eee642dc4803..e6d0fd4869c09e 100644 Binary files a/examples/screenshots/webgl_lines_fat_raycasting.jpg and b/examples/screenshots/webgl_lines_fat_raycasting.jpg differ diff --git a/examples/screenshots/webgl_lines_fat_wireframe.jpg b/examples/screenshots/webgl_lines_fat_wireframe.jpg index ba4c8d9afba46d..89b5b27add1ea7 100644 Binary files a/examples/screenshots/webgl_lines_fat_wireframe.jpg and b/examples/screenshots/webgl_lines_fat_wireframe.jpg differ diff --git a/examples/screenshots/webgl_loader_3dm.jpg b/examples/screenshots/webgl_loader_3dm.jpg index 9555227dcdcdc3..d6e56aa0717aa4 100644 Binary files a/examples/screenshots/webgl_loader_3dm.jpg and b/examples/screenshots/webgl_loader_3dm.jpg differ diff --git a/examples/screenshots/webgl_loader_3ds.jpg b/examples/screenshots/webgl_loader_3ds.jpg index 0eb85e6abc5712..115b0211a46aed 100644 Binary files a/examples/screenshots/webgl_loader_3ds.jpg and b/examples/screenshots/webgl_loader_3ds.jpg differ diff --git a/examples/screenshots/webgl_loader_3mf.jpg b/examples/screenshots/webgl_loader_3mf.jpg index a1178cfa60128a..133720a2689849 100644 Binary files a/examples/screenshots/webgl_loader_3mf.jpg and b/examples/screenshots/webgl_loader_3mf.jpg differ diff --git a/examples/screenshots/webgl_loader_3mf_materials.jpg b/examples/screenshots/webgl_loader_3mf_materials.jpg index b2b553ef2e5aa3..06b6a8a5fd0234 100644 Binary files a/examples/screenshots/webgl_loader_3mf_materials.jpg and b/examples/screenshots/webgl_loader_3mf_materials.jpg differ diff --git a/examples/screenshots/webgl_loader_amf.jpg b/examples/screenshots/webgl_loader_amf.jpg index 55a7c576bd2de9..b8ea44c084d822 100644 Binary files a/examples/screenshots/webgl_loader_amf.jpg and b/examples/screenshots/webgl_loader_amf.jpg differ diff --git a/examples/screenshots/webgl_loader_bvh.jpg b/examples/screenshots/webgl_loader_bvh.jpg index 59b2a69c12c668..384ae888d005a7 100644 Binary files a/examples/screenshots/webgl_loader_bvh.jpg and b/examples/screenshots/webgl_loader_bvh.jpg differ diff --git a/examples/screenshots/webgl_loader_collada.jpg b/examples/screenshots/webgl_loader_collada.jpg index 5f3de3b59ebea3..d3a562847ce2b4 100644 Binary files a/examples/screenshots/webgl_loader_collada.jpg and b/examples/screenshots/webgl_loader_collada.jpg differ diff --git a/examples/screenshots/webgl_loader_collada_kinematics.jpg b/examples/screenshots/webgl_loader_collada_kinematics.jpg index e56879a9b21c27..9333570a2730ab 100644 Binary files a/examples/screenshots/webgl_loader_collada_kinematics.jpg and b/examples/screenshots/webgl_loader_collada_kinematics.jpg differ diff --git a/examples/screenshots/webgl_loader_collada_skinning.jpg b/examples/screenshots/webgl_loader_collada_skinning.jpg index 12b9839487346f..01f080101e5010 100644 Binary files a/examples/screenshots/webgl_loader_collada_skinning.jpg and b/examples/screenshots/webgl_loader_collada_skinning.jpg differ diff --git a/examples/screenshots/webgl_loader_draco.jpg b/examples/screenshots/webgl_loader_draco.jpg index 97b0cf4960435d..56910d80b2f7fb 100644 Binary files a/examples/screenshots/webgl_loader_draco.jpg and b/examples/screenshots/webgl_loader_draco.jpg differ diff --git a/examples/screenshots/webgl_loader_fbx.jpg b/examples/screenshots/webgl_loader_fbx.jpg index e714a6dc815fae..352bb432497df2 100644 Binary files a/examples/screenshots/webgl_loader_fbx.jpg and b/examples/screenshots/webgl_loader_fbx.jpg differ diff --git a/examples/screenshots/webgl_loader_fbx_nurbs.jpg b/examples/screenshots/webgl_loader_fbx_nurbs.jpg index 979b34197b9512..3e58f0497ea84d 100644 Binary files a/examples/screenshots/webgl_loader_fbx_nurbs.jpg and b/examples/screenshots/webgl_loader_fbx_nurbs.jpg differ diff --git a/examples/screenshots/webgl_loader_gcode.jpg b/examples/screenshots/webgl_loader_gcode.jpg index 9e3d07bfda1289..c3637a94e3570d 100644 Binary files a/examples/screenshots/webgl_loader_gcode.jpg and b/examples/screenshots/webgl_loader_gcode.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf.jpg b/examples/screenshots/webgl_loader_gltf.jpg index b50bdc22b1477a..ee3fe18e551bd2 100644 Binary files a/examples/screenshots/webgl_loader_gltf.jpg and b/examples/screenshots/webgl_loader_gltf.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_animation_pointer.jpg b/examples/screenshots/webgl_loader_gltf_animation_pointer.jpg index b938a4b8f7a03d..d22dad3354eddf 100644 Binary files a/examples/screenshots/webgl_loader_gltf_animation_pointer.jpg and b/examples/screenshots/webgl_loader_gltf_animation_pointer.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_anisotropy.jpg b/examples/screenshots/webgl_loader_gltf_anisotropy.jpg index 7e5f40b16bcbd8..1da4893458e3cb 100644 Binary files a/examples/screenshots/webgl_loader_gltf_anisotropy.jpg and b/examples/screenshots/webgl_loader_gltf_anisotropy.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_avif.jpg b/examples/screenshots/webgl_loader_gltf_avif.jpg index cc6b5714f5f04e..37382746b022f3 100644 Binary files a/examples/screenshots/webgl_loader_gltf_avif.jpg and b/examples/screenshots/webgl_loader_gltf_avif.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_compressed.jpg b/examples/screenshots/webgl_loader_gltf_compressed.jpg index e9544d2a342556..762a219155b6c2 100644 Binary files a/examples/screenshots/webgl_loader_gltf_compressed.jpg and b/examples/screenshots/webgl_loader_gltf_compressed.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_dispersion.jpg b/examples/screenshots/webgl_loader_gltf_dispersion.jpg index acd494db41735e..8db8972c45348e 100644 Binary files a/examples/screenshots/webgl_loader_gltf_dispersion.jpg and b/examples/screenshots/webgl_loader_gltf_dispersion.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_instancing.jpg b/examples/screenshots/webgl_loader_gltf_instancing.jpg index f2835610a13ac3..016a646db69ae9 100644 Binary files a/examples/screenshots/webgl_loader_gltf_instancing.jpg and b/examples/screenshots/webgl_loader_gltf_instancing.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_iridescence.jpg b/examples/screenshots/webgl_loader_gltf_iridescence.jpg index 2074e2de376c00..e04877051b7f59 100644 Binary files a/examples/screenshots/webgl_loader_gltf_iridescence.jpg and b/examples/screenshots/webgl_loader_gltf_iridescence.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_progressive_lod.jpg b/examples/screenshots/webgl_loader_gltf_progressive_lod.jpg index 112dcb1ffdf9d7..2ee275bbbdf058 100644 Binary files a/examples/screenshots/webgl_loader_gltf_progressive_lod.jpg and b/examples/screenshots/webgl_loader_gltf_progressive_lod.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_sheen.jpg b/examples/screenshots/webgl_loader_gltf_sheen.jpg index db3459be454004..742d1583651012 100644 Binary files a/examples/screenshots/webgl_loader_gltf_sheen.jpg and b/examples/screenshots/webgl_loader_gltf_sheen.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_transmission.jpg b/examples/screenshots/webgl_loader_gltf_transmission.jpg index c348d2d2c05ddf..9b8333195c50d4 100644 Binary files a/examples/screenshots/webgl_loader_gltf_transmission.jpg and b/examples/screenshots/webgl_loader_gltf_transmission.jpg differ diff --git a/examples/screenshots/webgl_loader_gltf_variants.jpg b/examples/screenshots/webgl_loader_gltf_variants.jpg index 48dce72ee800b0..b6bad7b4b731ca 100644 Binary files a/examples/screenshots/webgl_loader_gltf_variants.jpg and b/examples/screenshots/webgl_loader_gltf_variants.jpg differ diff --git a/examples/screenshots/webgl_loader_ifc.jpg b/examples/screenshots/webgl_loader_ifc.jpg index ce09e29b056554..d5df276544631c 100644 Binary files a/examples/screenshots/webgl_loader_ifc.jpg and b/examples/screenshots/webgl_loader_ifc.jpg differ diff --git a/examples/screenshots/webgl_loader_imagebitmap.jpg b/examples/screenshots/webgl_loader_imagebitmap.jpg index 659a6cc3d631ad..3798a4e4427eee 100644 Binary files a/examples/screenshots/webgl_loader_imagebitmap.jpg and b/examples/screenshots/webgl_loader_imagebitmap.jpg differ diff --git a/examples/screenshots/webgl_loader_kmz.jpg b/examples/screenshots/webgl_loader_kmz.jpg index 09f6650fc7c3d5..bdde356190f663 100644 Binary files a/examples/screenshots/webgl_loader_kmz.jpg and b/examples/screenshots/webgl_loader_kmz.jpg differ diff --git a/examples/screenshots/webgl_loader_ldraw.jpg b/examples/screenshots/webgl_loader_ldraw.jpg index b055c6f2068225..84e99d0b1fa39a 100644 Binary files a/examples/screenshots/webgl_loader_ldraw.jpg and b/examples/screenshots/webgl_loader_ldraw.jpg differ diff --git a/examples/screenshots/webgl_loader_md2.jpg b/examples/screenshots/webgl_loader_md2.jpg index fd1cc2298034ba..97168280aeecfd 100644 Binary files a/examples/screenshots/webgl_loader_md2.jpg and b/examples/screenshots/webgl_loader_md2.jpg differ diff --git a/examples/screenshots/webgl_loader_md2_control.jpg b/examples/screenshots/webgl_loader_md2_control.jpg index 6030ca883e28c6..a50a3c20a097e6 100644 Binary files a/examples/screenshots/webgl_loader_md2_control.jpg and b/examples/screenshots/webgl_loader_md2_control.jpg differ diff --git a/examples/screenshots/webgl_loader_mdd.jpg b/examples/screenshots/webgl_loader_mdd.jpg index c148d6fb6b3b58..30e276dc8639cf 100644 Binary files a/examples/screenshots/webgl_loader_mdd.jpg and b/examples/screenshots/webgl_loader_mdd.jpg differ diff --git a/examples/screenshots/webgl_loader_nrrd.jpg b/examples/screenshots/webgl_loader_nrrd.jpg index c612c3947ad39a..9a8bb1c551c530 100644 Binary files a/examples/screenshots/webgl_loader_nrrd.jpg and b/examples/screenshots/webgl_loader_nrrd.jpg differ diff --git a/examples/screenshots/webgl_loader_obj.jpg b/examples/screenshots/webgl_loader_obj.jpg index 7fad41c7ca2793..c556e742717ff3 100644 Binary files a/examples/screenshots/webgl_loader_obj.jpg and b/examples/screenshots/webgl_loader_obj.jpg differ diff --git a/examples/screenshots/webgl_loader_pcd.jpg b/examples/screenshots/webgl_loader_pcd.jpg index 1ef7e8b5a6bdcb..4a09821000af7e 100644 Binary files a/examples/screenshots/webgl_loader_pcd.jpg and b/examples/screenshots/webgl_loader_pcd.jpg differ diff --git a/examples/screenshots/webgl_loader_pdb.jpg b/examples/screenshots/webgl_loader_pdb.jpg index 3e23b7869180de..787c19d074c1f2 100644 Binary files a/examples/screenshots/webgl_loader_pdb.jpg and b/examples/screenshots/webgl_loader_pdb.jpg differ diff --git a/examples/screenshots/webgl_loader_ply.jpg b/examples/screenshots/webgl_loader_ply.jpg index a8269cbe4e8a99..e6b1b1242754f1 100644 Binary files a/examples/screenshots/webgl_loader_ply.jpg and b/examples/screenshots/webgl_loader_ply.jpg differ diff --git a/examples/screenshots/webgl_loader_stl.jpg b/examples/screenshots/webgl_loader_stl.jpg index a064cb8428e473..642091d6635222 100644 Binary files a/examples/screenshots/webgl_loader_stl.jpg and b/examples/screenshots/webgl_loader_stl.jpg differ diff --git a/examples/screenshots/webgl_loader_svg.jpg b/examples/screenshots/webgl_loader_svg.jpg index 744ec1afe943ca..b2bc0bf3bb1750 100644 Binary files a/examples/screenshots/webgl_loader_svg.jpg and b/examples/screenshots/webgl_loader_svg.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_dds.jpg b/examples/screenshots/webgl_loader_texture_dds.jpg index 785a7952a0c293..f2bb3df913fda3 100644 Binary files a/examples/screenshots/webgl_loader_texture_dds.jpg and b/examples/screenshots/webgl_loader_texture_dds.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_exr.jpg b/examples/screenshots/webgl_loader_texture_exr.jpg index e7c1053ba3c154..51fe84333fd4d6 100644 Binary files a/examples/screenshots/webgl_loader_texture_exr.jpg and b/examples/screenshots/webgl_loader_texture_exr.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_hdr.jpg b/examples/screenshots/webgl_loader_texture_hdr.jpg index 61860a49e55104..d6c7f0ba503323 100644 Binary files a/examples/screenshots/webgl_loader_texture_hdr.jpg and b/examples/screenshots/webgl_loader_texture_hdr.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_ktx.jpg b/examples/screenshots/webgl_loader_texture_ktx.jpg index 9d057c9ea88efd..56687659515ba1 100644 Binary files a/examples/screenshots/webgl_loader_texture_ktx.jpg and b/examples/screenshots/webgl_loader_texture_ktx.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_ktx2.jpg b/examples/screenshots/webgl_loader_texture_ktx2.jpg index fff5457a86c597..bb07cebc4c8359 100644 Binary files a/examples/screenshots/webgl_loader_texture_ktx2.jpg and b/examples/screenshots/webgl_loader_texture_ktx2.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_tga.jpg b/examples/screenshots/webgl_loader_texture_tga.jpg index 24b6f546ceaa37..f20ad7de37626d 100644 Binary files a/examples/screenshots/webgl_loader_texture_tga.jpg and b/examples/screenshots/webgl_loader_texture_tga.jpg differ diff --git a/examples/screenshots/webgl_loader_texture_tiff.jpg b/examples/screenshots/webgl_loader_texture_tiff.jpg index 285d722628d819..15c6f8b0b31c3e 100644 Binary files a/examples/screenshots/webgl_loader_texture_tiff.jpg and b/examples/screenshots/webgl_loader_texture_tiff.jpg differ diff --git a/examples/screenshots/webgl_loader_ttf.jpg b/examples/screenshots/webgl_loader_ttf.jpg index 3ab9b6792d0876..8d64e9fc9d6977 100644 Binary files a/examples/screenshots/webgl_loader_ttf.jpg and b/examples/screenshots/webgl_loader_ttf.jpg differ diff --git a/examples/screenshots/webgl_loader_usdz.jpg b/examples/screenshots/webgl_loader_usdz.jpg index 8a77f3caef32e3..2ccc4e695e166f 100644 Binary files a/examples/screenshots/webgl_loader_usdz.jpg and b/examples/screenshots/webgl_loader_usdz.jpg differ diff --git a/examples/screenshots/webgl_loader_vox.jpg b/examples/screenshots/webgl_loader_vox.jpg index fee99d749d5a16..8e550c9e0ec3ab 100644 Binary files a/examples/screenshots/webgl_loader_vox.jpg and b/examples/screenshots/webgl_loader_vox.jpg differ diff --git a/examples/screenshots/webgl_loader_vrml.jpg b/examples/screenshots/webgl_loader_vrml.jpg index 0176cf5da31cb5..f5e61b51529506 100644 Binary files a/examples/screenshots/webgl_loader_vrml.jpg and b/examples/screenshots/webgl_loader_vrml.jpg differ diff --git a/examples/screenshots/webgl_loader_xyz.jpg b/examples/screenshots/webgl_loader_xyz.jpg index 5019bc383ef29a..beaa2f4ddd4f1c 100644 Binary files a/examples/screenshots/webgl_loader_xyz.jpg and b/examples/screenshots/webgl_loader_xyz.jpg differ diff --git a/examples/screenshots/webgl_lod.jpg b/examples/screenshots/webgl_lod.jpg index 40d5ce608da986..4e906cce33ccbb 100644 Binary files a/examples/screenshots/webgl_lod.jpg and b/examples/screenshots/webgl_lod.jpg differ diff --git a/examples/screenshots/webgl_materials_alphahash.jpg b/examples/screenshots/webgl_materials_alphahash.jpg index 196a7af6c089f2..42c372f82eaa6a 100644 Binary files a/examples/screenshots/webgl_materials_alphahash.jpg and b/examples/screenshots/webgl_materials_alphahash.jpg differ diff --git a/examples/screenshots/webgl_materials_blending.jpg b/examples/screenshots/webgl_materials_blending.jpg index 20a5bbf341bc05..bf32b7e2f6665a 100644 Binary files a/examples/screenshots/webgl_materials_blending.jpg and b/examples/screenshots/webgl_materials_blending.jpg differ diff --git a/examples/screenshots/webgl_materials_blending_custom.jpg b/examples/screenshots/webgl_materials_blending_custom.jpg index 87802f6142fad0..27b45da08b8854 100644 Binary files a/examples/screenshots/webgl_materials_blending_custom.jpg and b/examples/screenshots/webgl_materials_blending_custom.jpg differ diff --git a/examples/screenshots/webgl_materials_bumpmap.jpg b/examples/screenshots/webgl_materials_bumpmap.jpg index c7d979e174690d..71359bafb9d7fd 100644 Binary files a/examples/screenshots/webgl_materials_bumpmap.jpg and b/examples/screenshots/webgl_materials_bumpmap.jpg differ diff --git a/examples/screenshots/webgl_materials_car.jpg b/examples/screenshots/webgl_materials_car.jpg index 39f853551ef1fb..fa5ab74fed13c1 100644 Binary files a/examples/screenshots/webgl_materials_car.jpg and b/examples/screenshots/webgl_materials_car.jpg differ diff --git a/examples/screenshots/webgl_materials_channels.jpg b/examples/screenshots/webgl_materials_channels.jpg index 9a548f38b9784a..6b10d72e9b3cd6 100644 Binary files a/examples/screenshots/webgl_materials_channels.jpg and b/examples/screenshots/webgl_materials_channels.jpg differ diff --git a/examples/screenshots/webgl_materials_cubemap.jpg b/examples/screenshots/webgl_materials_cubemap.jpg index ed5e70694eca9a..66c64db7d5a8da 100644 Binary files a/examples/screenshots/webgl_materials_cubemap.jpg and b/examples/screenshots/webgl_materials_cubemap.jpg differ diff --git a/examples/screenshots/webgl_materials_cubemap_mipmaps.jpg b/examples/screenshots/webgl_materials_cubemap_mipmaps.jpg index dc13bac3bd9b3b..7a8cfa3d665aea 100644 Binary files a/examples/screenshots/webgl_materials_cubemap_mipmaps.jpg and b/examples/screenshots/webgl_materials_cubemap_mipmaps.jpg differ diff --git a/examples/screenshots/webgl_materials_cubemap_refraction.jpg b/examples/screenshots/webgl_materials_cubemap_refraction.jpg index 78a83dfd5effdc..c676527731b643 100644 Binary files a/examples/screenshots/webgl_materials_cubemap_refraction.jpg and b/examples/screenshots/webgl_materials_cubemap_refraction.jpg differ diff --git a/examples/screenshots/webgl_materials_cubemap_render_to_mipmaps.jpg b/examples/screenshots/webgl_materials_cubemap_render_to_mipmaps.jpg index 0ea92d92158ed5..b2fe963fe89d03 100644 Binary files a/examples/screenshots/webgl_materials_cubemap_render_to_mipmaps.jpg and b/examples/screenshots/webgl_materials_cubemap_render_to_mipmaps.jpg differ diff --git a/examples/screenshots/webgl_materials_envmaps.jpg b/examples/screenshots/webgl_materials_envmaps.jpg index 84cb169075e111..8b074bb568b0a8 100644 Binary files a/examples/screenshots/webgl_materials_envmaps.jpg and b/examples/screenshots/webgl_materials_envmaps.jpg differ diff --git a/examples/screenshots/webgl_materials_envmaps_exr.jpg b/examples/screenshots/webgl_materials_envmaps_exr.jpg index 7fa358b4252a08..cb1160facbd12d 100644 Binary files a/examples/screenshots/webgl_materials_envmaps_exr.jpg and b/examples/screenshots/webgl_materials_envmaps_exr.jpg differ diff --git a/examples/screenshots/webgl_materials_envmaps_fasthdr.jpg b/examples/screenshots/webgl_materials_envmaps_fasthdr.jpg index a67574f4f6df49..a68aade22353dc 100644 Binary files a/examples/screenshots/webgl_materials_envmaps_fasthdr.jpg and b/examples/screenshots/webgl_materials_envmaps_fasthdr.jpg differ diff --git a/examples/screenshots/webgl_materials_envmaps_groundprojected.jpg b/examples/screenshots/webgl_materials_envmaps_groundprojected.jpg index 753526f4096ca5..e140b523b9a170 100644 Binary files a/examples/screenshots/webgl_materials_envmaps_groundprojected.jpg and b/examples/screenshots/webgl_materials_envmaps_groundprojected.jpg differ diff --git a/examples/screenshots/webgl_materials_matcap.jpg b/examples/screenshots/webgl_materials_matcap.jpg index 9b9b3d003aff36..663bba62576a20 100644 Binary files a/examples/screenshots/webgl_materials_matcap.jpg and b/examples/screenshots/webgl_materials_matcap.jpg differ diff --git a/examples/screenshots/webgl_materials_modified.jpg b/examples/screenshots/webgl_materials_modified.jpg index afc34fddc6c114..b74c21c91f754a 100644 Binary files a/examples/screenshots/webgl_materials_modified.jpg and b/examples/screenshots/webgl_materials_modified.jpg differ diff --git a/examples/screenshots/webgl_materials_normalmap.jpg b/examples/screenshots/webgl_materials_normalmap.jpg index 8e573e3cf2a0d5..d3dd86b0c1ef8b 100644 Binary files a/examples/screenshots/webgl_materials_normalmap.jpg and b/examples/screenshots/webgl_materials_normalmap.jpg differ diff --git a/examples/screenshots/webgl_materials_normalmap_object_space.jpg b/examples/screenshots/webgl_materials_normalmap_object_space.jpg index eda4216494a61b..351d79f8a3da0b 100644 Binary files a/examples/screenshots/webgl_materials_normalmap_object_space.jpg and b/examples/screenshots/webgl_materials_normalmap_object_space.jpg differ diff --git a/examples/screenshots/webgl_materials_physical_clearcoat.jpg b/examples/screenshots/webgl_materials_physical_clearcoat.jpg index d364672c61b664..55f6856637b730 100644 Binary files a/examples/screenshots/webgl_materials_physical_clearcoat.jpg and b/examples/screenshots/webgl_materials_physical_clearcoat.jpg differ diff --git a/examples/screenshots/webgl_materials_physical_transmission.jpg b/examples/screenshots/webgl_materials_physical_transmission.jpg index d5d7d70abb5a75..cd994f8abd9c53 100644 Binary files a/examples/screenshots/webgl_materials_physical_transmission.jpg and b/examples/screenshots/webgl_materials_physical_transmission.jpg differ diff --git a/examples/screenshots/webgl_materials_physical_transmission_alpha.jpg b/examples/screenshots/webgl_materials_physical_transmission_alpha.jpg index 64a14e5783e8a0..f10a20002667d3 100644 Binary files a/examples/screenshots/webgl_materials_physical_transmission_alpha.jpg and b/examples/screenshots/webgl_materials_physical_transmission_alpha.jpg differ diff --git a/examples/screenshots/webgl_materials_subsurface_scattering.jpg b/examples/screenshots/webgl_materials_subsurface_scattering.jpg index 1490842c9b0ef9..433f9b3f6055b2 100644 Binary files a/examples/screenshots/webgl_materials_subsurface_scattering.jpg and b/examples/screenshots/webgl_materials_subsurface_scattering.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_anisotropy.jpg b/examples/screenshots/webgl_materials_texture_anisotropy.jpg index 8569dfb7ca4d3f..be7c8f7c832240 100644 Binary files a/examples/screenshots/webgl_materials_texture_anisotropy.jpg and b/examples/screenshots/webgl_materials_texture_anisotropy.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_canvas.jpg b/examples/screenshots/webgl_materials_texture_canvas.jpg index bc396debdf892b..b478d955e17bc6 100644 Binary files a/examples/screenshots/webgl_materials_texture_canvas.jpg and b/examples/screenshots/webgl_materials_texture_canvas.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_filters.jpg b/examples/screenshots/webgl_materials_texture_filters.jpg index 757b633317067b..8fa5d35b10b4ff 100644 Binary files a/examples/screenshots/webgl_materials_texture_filters.jpg and b/examples/screenshots/webgl_materials_texture_filters.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_html.jpg b/examples/screenshots/webgl_materials_texture_html.jpg index bdf04eeaf83e52..488b16ab4de516 100644 Binary files a/examples/screenshots/webgl_materials_texture_html.jpg and b/examples/screenshots/webgl_materials_texture_html.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_manualmipmap.jpg b/examples/screenshots/webgl_materials_texture_manualmipmap.jpg index b876d480655fa0..e5d2cf57ef5443 100644 Binary files a/examples/screenshots/webgl_materials_texture_manualmipmap.jpg and b/examples/screenshots/webgl_materials_texture_manualmipmap.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_partialupdate.jpg b/examples/screenshots/webgl_materials_texture_partialupdate.jpg index 4f6a563a0519b9..81c9a4a5b73220 100644 Binary files a/examples/screenshots/webgl_materials_texture_partialupdate.jpg and b/examples/screenshots/webgl_materials_texture_partialupdate.jpg differ diff --git a/examples/screenshots/webgl_materials_texture_rotation.jpg b/examples/screenshots/webgl_materials_texture_rotation.jpg index dbc4b26ffb3bd6..6b0e045ea2460b 100644 Binary files a/examples/screenshots/webgl_materials_texture_rotation.jpg and b/examples/screenshots/webgl_materials_texture_rotation.jpg differ diff --git a/examples/screenshots/webgl_materials_toon.jpg b/examples/screenshots/webgl_materials_toon.jpg index 7554d69d857e37..b626f85f3abde9 100644 Binary files a/examples/screenshots/webgl_materials_toon.jpg and b/examples/screenshots/webgl_materials_toon.jpg differ diff --git a/examples/screenshots/webgl_materials_video.jpg b/examples/screenshots/webgl_materials_video.jpg index 66c1f87401831c..b5e5dde094db67 100644 Binary files a/examples/screenshots/webgl_materials_video.jpg and b/examples/screenshots/webgl_materials_video.jpg differ diff --git a/examples/screenshots/webgl_materials_wireframe.jpg b/examples/screenshots/webgl_materials_wireframe.jpg index ce5da16e86578e..b87dc4e8bdd5da 100644 Binary files a/examples/screenshots/webgl_materials_wireframe.jpg and b/examples/screenshots/webgl_materials_wireframe.jpg differ diff --git a/examples/screenshots/webgl_math_obb.jpg b/examples/screenshots/webgl_math_obb.jpg index d82241e14e6b18..7e284d2513be60 100644 Binary files a/examples/screenshots/webgl_math_obb.jpg and b/examples/screenshots/webgl_math_obb.jpg differ diff --git a/examples/screenshots/webgl_math_orientation_transform.jpg b/examples/screenshots/webgl_math_orientation_transform.jpg index 8eda044ba79c4f..0782239700e6bb 100644 Binary files a/examples/screenshots/webgl_math_orientation_transform.jpg and b/examples/screenshots/webgl_math_orientation_transform.jpg differ diff --git a/examples/screenshots/webgl_mesh_batch.jpg b/examples/screenshots/webgl_mesh_batch.jpg index 6594f8ef00d925..a50dc3db85b22f 100644 Binary files a/examples/screenshots/webgl_mesh_batch.jpg and b/examples/screenshots/webgl_mesh_batch.jpg differ diff --git a/examples/screenshots/webgl_mirror.jpg b/examples/screenshots/webgl_mirror.jpg index 6f78a59341e347..9f9c35b368a83f 100644 Binary files a/examples/screenshots/webgl_mirror.jpg and b/examples/screenshots/webgl_mirror.jpg differ diff --git a/examples/screenshots/webgl_modifier_curve.jpg b/examples/screenshots/webgl_modifier_curve.jpg index 4a6fa6bb65ecda..549d5c181483b1 100644 Binary files a/examples/screenshots/webgl_modifier_curve.jpg and b/examples/screenshots/webgl_modifier_curve.jpg differ diff --git a/examples/screenshots/webgl_modifier_curve_instanced.jpg b/examples/screenshots/webgl_modifier_curve_instanced.jpg index 8f7c2f0a7a997c..10ea7184b55fec 100644 Binary files a/examples/screenshots/webgl_modifier_curve_instanced.jpg and b/examples/screenshots/webgl_modifier_curve_instanced.jpg differ diff --git a/examples/screenshots/webgl_modifier_edgesplit.jpg b/examples/screenshots/webgl_modifier_edgesplit.jpg index 64475bb91891cb..7588197ca5b29d 100644 Binary files a/examples/screenshots/webgl_modifier_edgesplit.jpg and b/examples/screenshots/webgl_modifier_edgesplit.jpg differ diff --git a/examples/screenshots/webgl_modifier_simplifier.jpg b/examples/screenshots/webgl_modifier_simplifier.jpg index b9b4c8cc83b217..7de4e07804b878 100644 Binary files a/examples/screenshots/webgl_modifier_simplifier.jpg and b/examples/screenshots/webgl_modifier_simplifier.jpg differ diff --git a/examples/screenshots/webgl_modifier_subdivision.jpg b/examples/screenshots/webgl_modifier_subdivision.jpg index 47e95588fa967d..1f9538d668ca58 100644 Binary files a/examples/screenshots/webgl_modifier_subdivision.jpg and b/examples/screenshots/webgl_modifier_subdivision.jpg differ diff --git a/examples/screenshots/webgl_modifier_tessellation.jpg b/examples/screenshots/webgl_modifier_tessellation.jpg index 5a907853f4f333..0ead2ee6d7dd68 100644 Binary files a/examples/screenshots/webgl_modifier_tessellation.jpg and b/examples/screenshots/webgl_modifier_tessellation.jpg differ diff --git a/examples/screenshots/webgl_morphtargets.jpg b/examples/screenshots/webgl_morphtargets.jpg index 9d5fbc9fd38c40..7a6f0add133594 100644 Binary files a/examples/screenshots/webgl_morphtargets.jpg and b/examples/screenshots/webgl_morphtargets.jpg differ diff --git a/examples/screenshots/webgl_morphtargets_horse.jpg b/examples/screenshots/webgl_morphtargets_horse.jpg index 8e05f33d918198..83ef241cd2c76f 100644 Binary files a/examples/screenshots/webgl_morphtargets_horse.jpg and b/examples/screenshots/webgl_morphtargets_horse.jpg differ diff --git a/examples/screenshots/webgl_morphtargets_sphere.jpg b/examples/screenshots/webgl_morphtargets_sphere.jpg index 61840b84ccac11..cc07c0fd1fbbf5 100644 Binary files a/examples/screenshots/webgl_morphtargets_sphere.jpg and b/examples/screenshots/webgl_morphtargets_sphere.jpg differ diff --git a/examples/screenshots/webgl_multiple_elements.jpg b/examples/screenshots/webgl_multiple_elements.jpg index f1024a8b5ff640..6b2f94d8fa0444 100644 Binary files a/examples/screenshots/webgl_multiple_elements.jpg and b/examples/screenshots/webgl_multiple_elements.jpg differ diff --git a/examples/screenshots/webgl_multiple_elements_text.jpg b/examples/screenshots/webgl_multiple_elements_text.jpg index c1087c2e84b7aa..f9a27876196344 100644 Binary files a/examples/screenshots/webgl_multiple_elements_text.jpg and b/examples/screenshots/webgl_multiple_elements_text.jpg differ diff --git a/examples/screenshots/webgl_multiple_rendertargets.jpg b/examples/screenshots/webgl_multiple_rendertargets.jpg index 219a0eb4605e94..33e4ab5b2e8d36 100644 Binary files a/examples/screenshots/webgl_multiple_rendertargets.jpg and b/examples/screenshots/webgl_multiple_rendertargets.jpg differ diff --git a/examples/screenshots/webgl_multiple_scenes_comparison.jpg b/examples/screenshots/webgl_multiple_scenes_comparison.jpg index c253133ec55e81..6c91d79644563b 100644 Binary files a/examples/screenshots/webgl_multiple_scenes_comparison.jpg and b/examples/screenshots/webgl_multiple_scenes_comparison.jpg differ diff --git a/examples/screenshots/webgl_multiple_views.jpg b/examples/screenshots/webgl_multiple_views.jpg index 06d69f8907191c..bd63aa98e2e9a8 100644 Binary files a/examples/screenshots/webgl_multiple_views.jpg and b/examples/screenshots/webgl_multiple_views.jpg differ diff --git a/examples/screenshots/webgl_multisampled_renderbuffers.jpg b/examples/screenshots/webgl_multisampled_renderbuffers.jpg index fa29757722a763..55b543487c7a6e 100644 Binary files a/examples/screenshots/webgl_multisampled_renderbuffers.jpg and b/examples/screenshots/webgl_multisampled_renderbuffers.jpg differ diff --git a/examples/screenshots/webgl_panorama_cube.jpg b/examples/screenshots/webgl_panorama_cube.jpg index 833ca5f47b4418..e2aaf6b79f4034 100644 Binary files a/examples/screenshots/webgl_panorama_cube.jpg and b/examples/screenshots/webgl_panorama_cube.jpg differ diff --git a/examples/screenshots/webgl_panorama_equirectangular.jpg b/examples/screenshots/webgl_panorama_equirectangular.jpg index 9885ea9bd25c63..146b7f1557c42b 100644 Binary files a/examples/screenshots/webgl_panorama_equirectangular.jpg and b/examples/screenshots/webgl_panorama_equirectangular.jpg differ diff --git a/examples/screenshots/webgl_performance.jpg b/examples/screenshots/webgl_performance.jpg index 5b5cb4410a37b0..5870c82e1b4722 100644 Binary files a/examples/screenshots/webgl_performance.jpg and b/examples/screenshots/webgl_performance.jpg differ diff --git a/examples/screenshots/webgl_pmrem_cubemap.jpg b/examples/screenshots/webgl_pmrem_cubemap.jpg index 4d2c045f0ab9f5..2b1b5d4fd5690e 100644 Binary files a/examples/screenshots/webgl_pmrem_cubemap.jpg and b/examples/screenshots/webgl_pmrem_cubemap.jpg differ diff --git a/examples/screenshots/webgl_pmrem_equirectangular.jpg b/examples/screenshots/webgl_pmrem_equirectangular.jpg index ab936ec88c2cbf..9948178bb18e52 100644 Binary files a/examples/screenshots/webgl_pmrem_equirectangular.jpg and b/examples/screenshots/webgl_pmrem_equirectangular.jpg differ diff --git a/examples/screenshots/webgl_pmrem_test.jpg b/examples/screenshots/webgl_pmrem_test.jpg index 9f54502951e236..ea946668e05718 100644 Binary files a/examples/screenshots/webgl_pmrem_test.jpg and b/examples/screenshots/webgl_pmrem_test.jpg differ diff --git a/examples/screenshots/webgl_points_billboards.jpg b/examples/screenshots/webgl_points_billboards.jpg index 1a59e09efacc71..6a80e92b8d2571 100644 Binary files a/examples/screenshots/webgl_points_billboards.jpg and b/examples/screenshots/webgl_points_billboards.jpg differ diff --git a/examples/screenshots/webgl_points_dynamic.jpg b/examples/screenshots/webgl_points_dynamic.jpg index 87e10f16035f34..8777973e1e1e49 100644 Binary files a/examples/screenshots/webgl_points_dynamic.jpg and b/examples/screenshots/webgl_points_dynamic.jpg differ diff --git a/examples/screenshots/webgl_points_sprites.jpg b/examples/screenshots/webgl_points_sprites.jpg index 697725db3ef373..39e70bc6a2dd98 100644 Binary files a/examples/screenshots/webgl_points_sprites.jpg and b/examples/screenshots/webgl_points_sprites.jpg differ diff --git a/examples/screenshots/webgl_points_waves.jpg b/examples/screenshots/webgl_points_waves.jpg index 1f71490cbf6176..1979612a6d4eb3 100644 Binary files a/examples/screenshots/webgl_points_waves.jpg and b/examples/screenshots/webgl_points_waves.jpg differ diff --git a/examples/screenshots/webgl_portal.jpg b/examples/screenshots/webgl_portal.jpg index 8e749f98d568cd..864305735199e2 100644 Binary files a/examples/screenshots/webgl_portal.jpg and b/examples/screenshots/webgl_portal.jpg differ diff --git a/examples/screenshots/webgl_postprocessing.jpg b/examples/screenshots/webgl_postprocessing.jpg index fa7db61c675710..1b61f6acbcb2a6 100644 Binary files a/examples/screenshots/webgl_postprocessing.jpg and b/examples/screenshots/webgl_postprocessing.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_3dlut.jpg b/examples/screenshots/webgl_postprocessing_3dlut.jpg index b5dba6c234b3ab..dd294785b1600a 100644 Binary files a/examples/screenshots/webgl_postprocessing_3dlut.jpg and b/examples/screenshots/webgl_postprocessing_3dlut.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_advanced.jpg b/examples/screenshots/webgl_postprocessing_advanced.jpg index 6785ada9cd3fe3..3cc9a746100507 100644 Binary files a/examples/screenshots/webgl_postprocessing_advanced.jpg and b/examples/screenshots/webgl_postprocessing_advanced.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_afterimage.jpg b/examples/screenshots/webgl_postprocessing_afterimage.jpg index ab16a5fc63632d..2549e6b369ab5b 100644 Binary files a/examples/screenshots/webgl_postprocessing_afterimage.jpg and b/examples/screenshots/webgl_postprocessing_afterimage.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_backgrounds.jpg b/examples/screenshots/webgl_postprocessing_backgrounds.jpg index 88426e84258bd8..f4da60f7b947bd 100644 Binary files a/examples/screenshots/webgl_postprocessing_backgrounds.jpg and b/examples/screenshots/webgl_postprocessing_backgrounds.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_dof.jpg b/examples/screenshots/webgl_postprocessing_dof.jpg index b856cb92d782b5..9bb7ad5579ce19 100644 Binary files a/examples/screenshots/webgl_postprocessing_dof.jpg and b/examples/screenshots/webgl_postprocessing_dof.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_dof2.jpg b/examples/screenshots/webgl_postprocessing_dof2.jpg index 10312be65d30cc..7f3a9d133e1832 100644 Binary files a/examples/screenshots/webgl_postprocessing_dof2.jpg and b/examples/screenshots/webgl_postprocessing_dof2.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_fxaa.jpg b/examples/screenshots/webgl_postprocessing_fxaa.jpg index 21362983d82e7a..ba4ff1bcd1b649 100644 Binary files a/examples/screenshots/webgl_postprocessing_fxaa.jpg and b/examples/screenshots/webgl_postprocessing_fxaa.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_glitch.jpg b/examples/screenshots/webgl_postprocessing_glitch.jpg index 0a2b93466cb5b7..e066e126af56e5 100644 Binary files a/examples/screenshots/webgl_postprocessing_glitch.jpg and b/examples/screenshots/webgl_postprocessing_glitch.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_godrays.jpg b/examples/screenshots/webgl_postprocessing_godrays.jpg index 0a8a358541c7bd..30951e8cf302bb 100644 Binary files a/examples/screenshots/webgl_postprocessing_godrays.jpg and b/examples/screenshots/webgl_postprocessing_godrays.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_gtao.jpg b/examples/screenshots/webgl_postprocessing_gtao.jpg index 419ab1f51bea1f..c1510d87189a3c 100644 Binary files a/examples/screenshots/webgl_postprocessing_gtao.jpg and b/examples/screenshots/webgl_postprocessing_gtao.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_masking.jpg b/examples/screenshots/webgl_postprocessing_masking.jpg index adad6a4bb6cd6d..908bb9e5013c80 100644 Binary files a/examples/screenshots/webgl_postprocessing_masking.jpg and b/examples/screenshots/webgl_postprocessing_masking.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_outline.jpg b/examples/screenshots/webgl_postprocessing_outline.jpg index 36cf3e484203a6..b664df2e9b15f2 100644 Binary files a/examples/screenshots/webgl_postprocessing_outline.jpg and b/examples/screenshots/webgl_postprocessing_outline.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_pixel.jpg b/examples/screenshots/webgl_postprocessing_pixel.jpg index bf3cbc6be5786b..6787a0f3ff817f 100644 Binary files a/examples/screenshots/webgl_postprocessing_pixel.jpg and b/examples/screenshots/webgl_postprocessing_pixel.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_procedural.jpg b/examples/screenshots/webgl_postprocessing_procedural.jpg index d304dbef7c5945..64a0170e8d4ba2 100644 Binary files a/examples/screenshots/webgl_postprocessing_procedural.jpg and b/examples/screenshots/webgl_postprocessing_procedural.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_rgb_halftone.jpg b/examples/screenshots/webgl_postprocessing_rgb_halftone.jpg index 98fa5d60b4e4b6..8a19aac6ac1d77 100644 Binary files a/examples/screenshots/webgl_postprocessing_rgb_halftone.jpg and b/examples/screenshots/webgl_postprocessing_rgb_halftone.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_sao.jpg b/examples/screenshots/webgl_postprocessing_sao.jpg index b57ab3a33d9c0b..f6821ce4d95911 100644 Binary files a/examples/screenshots/webgl_postprocessing_sao.jpg and b/examples/screenshots/webgl_postprocessing_sao.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_smaa.jpg b/examples/screenshots/webgl_postprocessing_smaa.jpg index 96a374bd25e340..59fd53d8595b08 100644 Binary files a/examples/screenshots/webgl_postprocessing_smaa.jpg and b/examples/screenshots/webgl_postprocessing_smaa.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_sobel.jpg b/examples/screenshots/webgl_postprocessing_sobel.jpg index 85ae2b83b1971e..21b920d49d99ce 100644 Binary files a/examples/screenshots/webgl_postprocessing_sobel.jpg and b/examples/screenshots/webgl_postprocessing_sobel.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_ssaa.jpg b/examples/screenshots/webgl_postprocessing_ssaa.jpg index 7c81584957a8bb..32b1b8c39b7632 100644 Binary files a/examples/screenshots/webgl_postprocessing_ssaa.jpg and b/examples/screenshots/webgl_postprocessing_ssaa.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_ssao.jpg b/examples/screenshots/webgl_postprocessing_ssao.jpg index 6ca16efc9dc917..40cd62b3fb7b9a 100644 Binary files a/examples/screenshots/webgl_postprocessing_ssao.jpg and b/examples/screenshots/webgl_postprocessing_ssao.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_ssr.jpg b/examples/screenshots/webgl_postprocessing_ssr.jpg index 5f920f81918be1..f9505eb2a7dd91 100644 Binary files a/examples/screenshots/webgl_postprocessing_ssr.jpg and b/examples/screenshots/webgl_postprocessing_ssr.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_taa.jpg b/examples/screenshots/webgl_postprocessing_taa.jpg index 9d89ac53be1f74..83711d692d59bf 100644 Binary files a/examples/screenshots/webgl_postprocessing_taa.jpg and b/examples/screenshots/webgl_postprocessing_taa.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_transition.jpg b/examples/screenshots/webgl_postprocessing_transition.jpg index e135b301781f1e..815cd5c0ea6004 100644 Binary files a/examples/screenshots/webgl_postprocessing_transition.jpg and b/examples/screenshots/webgl_postprocessing_transition.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_unreal_bloom.jpg b/examples/screenshots/webgl_postprocessing_unreal_bloom.jpg index 49d3b19e31e074..f54d6debe1f6f7 100644 Binary files a/examples/screenshots/webgl_postprocessing_unreal_bloom.jpg and b/examples/screenshots/webgl_postprocessing_unreal_bloom.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_unreal_bloom_selective.jpg b/examples/screenshots/webgl_postprocessing_unreal_bloom_selective.jpg index a64a3f4d388fb8..8781c0f0ddd3af 100644 Binary files a/examples/screenshots/webgl_postprocessing_unreal_bloom_selective.jpg and b/examples/screenshots/webgl_postprocessing_unreal_bloom_selective.jpg differ diff --git a/examples/screenshots/webgl_random_uv.jpg b/examples/screenshots/webgl_random_uv.jpg index f33631aa9aeb9f..5d4149954d90e8 100644 Binary files a/examples/screenshots/webgl_random_uv.jpg and b/examples/screenshots/webgl_random_uv.jpg differ diff --git a/examples/screenshots/webgl_raycaster_bvh.jpg b/examples/screenshots/webgl_raycaster_bvh.jpg index f1a82720402459..dad2bbf37a5905 100644 Binary files a/examples/screenshots/webgl_raycaster_bvh.jpg and b/examples/screenshots/webgl_raycaster_bvh.jpg differ diff --git a/examples/screenshots/webgl_raycaster_sprite.jpg b/examples/screenshots/webgl_raycaster_sprite.jpg index b1b6e8ba949eea..652438c8bf4351 100644 Binary files a/examples/screenshots/webgl_raycaster_sprite.jpg and b/examples/screenshots/webgl_raycaster_sprite.jpg differ diff --git a/examples/screenshots/webgl_raycaster_texture.jpg b/examples/screenshots/webgl_raycaster_texture.jpg index 0490c189f00138..1b1837f764a857 100644 Binary files a/examples/screenshots/webgl_raycaster_texture.jpg and b/examples/screenshots/webgl_raycaster_texture.jpg differ diff --git a/examples/screenshots/webgl_read_float_buffer.jpg b/examples/screenshots/webgl_read_float_buffer.jpg index c9964e05107291..dfec7781545f9c 100644 Binary files a/examples/screenshots/webgl_read_float_buffer.jpg and b/examples/screenshots/webgl_read_float_buffer.jpg differ diff --git a/examples/screenshots/webgl_refraction.jpg b/examples/screenshots/webgl_refraction.jpg index 68cd1d73fabb4e..e20e1e69af5704 100644 Binary files a/examples/screenshots/webgl_refraction.jpg and b/examples/screenshots/webgl_refraction.jpg differ diff --git a/examples/screenshots/webgl_rendertarget_texture2darray.jpg b/examples/screenshots/webgl_rendertarget_texture2darray.jpg index 3a07ae8330a5bb..411494b86384d4 100644 Binary files a/examples/screenshots/webgl_rendertarget_texture2darray.jpg and b/examples/screenshots/webgl_rendertarget_texture2darray.jpg differ diff --git a/examples/screenshots/webgl_reversed_depth_buffer.jpg b/examples/screenshots/webgl_reversed_depth_buffer.jpg index e9e3014cf51e2e..dfba53a3aad4c5 100644 Binary files a/examples/screenshots/webgl_reversed_depth_buffer.jpg and b/examples/screenshots/webgl_reversed_depth_buffer.jpg differ diff --git a/examples/screenshots/webgl_rtt.jpg b/examples/screenshots/webgl_rtt.jpg index 9f45f0340171c9..6f7a1933d89911 100644 Binary files a/examples/screenshots/webgl_rtt.jpg and b/examples/screenshots/webgl_rtt.jpg differ diff --git a/examples/screenshots/webgl_shader.jpg b/examples/screenshots/webgl_shader.jpg index 81ced5d25993be..4487a914ff5dca 100644 Binary files a/examples/screenshots/webgl_shader.jpg and b/examples/screenshots/webgl_shader.jpg differ diff --git a/examples/screenshots/webgl_shader_lava.jpg b/examples/screenshots/webgl_shader_lava.jpg index d89bb3ae3b06af..ae9ae2a8314ffd 100644 Binary files a/examples/screenshots/webgl_shader_lava.jpg and b/examples/screenshots/webgl_shader_lava.jpg differ diff --git a/examples/screenshots/webgl_shaders_ocean.jpg b/examples/screenshots/webgl_shaders_ocean.jpg index 00d681246b49ab..50c5d5cf1e7d09 100644 Binary files a/examples/screenshots/webgl_shaders_ocean.jpg and b/examples/screenshots/webgl_shaders_ocean.jpg differ diff --git a/examples/screenshots/webgl_shaders_sky.jpg b/examples/screenshots/webgl_shaders_sky.jpg index c5b14c0740e4ee..6a9057581d972a 100644 Binary files a/examples/screenshots/webgl_shaders_sky.jpg and b/examples/screenshots/webgl_shaders_sky.jpg differ diff --git a/examples/screenshots/webgl_shadow_contact.jpg b/examples/screenshots/webgl_shadow_contact.jpg index 369fbae4108f21..59f78d03648c32 100644 Binary files a/examples/screenshots/webgl_shadow_contact.jpg and b/examples/screenshots/webgl_shadow_contact.jpg differ diff --git a/examples/screenshots/webgl_shadowmap.jpg b/examples/screenshots/webgl_shadowmap.jpg index 643c8f93aaf98b..151a630d463112 100644 Binary files a/examples/screenshots/webgl_shadowmap.jpg and b/examples/screenshots/webgl_shadowmap.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_csm.jpg b/examples/screenshots/webgl_shadowmap_csm.jpg index b08ff992db75a0..1a9fc72b67e2ca 100644 Binary files a/examples/screenshots/webgl_shadowmap_csm.jpg and b/examples/screenshots/webgl_shadowmap_csm.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_pcss.jpg b/examples/screenshots/webgl_shadowmap_pcss.jpg index bb2861e61956cb..ff2d14c1b729d8 100644 Binary files a/examples/screenshots/webgl_shadowmap_pcss.jpg and b/examples/screenshots/webgl_shadowmap_pcss.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_performance.jpg b/examples/screenshots/webgl_shadowmap_performance.jpg index f6afb844511797..20b32f7989dfc2 100644 Binary files a/examples/screenshots/webgl_shadowmap_performance.jpg and b/examples/screenshots/webgl_shadowmap_performance.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_pointlight.jpg b/examples/screenshots/webgl_shadowmap_pointlight.jpg index ea2c787f3d43af..b6c0ba53479531 100644 Binary files a/examples/screenshots/webgl_shadowmap_pointlight.jpg and b/examples/screenshots/webgl_shadowmap_pointlight.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_viewer.jpg b/examples/screenshots/webgl_shadowmap_viewer.jpg index 95b8b3013c55d8..984bb89c72f8b9 100644 Binary files a/examples/screenshots/webgl_shadowmap_viewer.jpg and b/examples/screenshots/webgl_shadowmap_viewer.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_vsm.jpg b/examples/screenshots/webgl_shadowmap_vsm.jpg index 635263acdf40bc..8227f785fd3db7 100644 Binary files a/examples/screenshots/webgl_shadowmap_vsm.jpg and b/examples/screenshots/webgl_shadowmap_vsm.jpg differ diff --git a/examples/screenshots/webgl_shadowmesh.jpg b/examples/screenshots/webgl_shadowmesh.jpg index 9f70ca80c96f6e..37a2de847c47a7 100644 Binary files a/examples/screenshots/webgl_shadowmesh.jpg and b/examples/screenshots/webgl_shadowmesh.jpg differ diff --git a/examples/screenshots/webgl_simple_gi.jpg b/examples/screenshots/webgl_simple_gi.jpg index 4a91056071067c..f9a297e6334648 100644 Binary files a/examples/screenshots/webgl_simple_gi.jpg and b/examples/screenshots/webgl_simple_gi.jpg differ diff --git a/examples/screenshots/webgl_sprites.jpg b/examples/screenshots/webgl_sprites.jpg index f27d0ac7d3e2a2..c1cceeb5389d6e 100644 Binary files a/examples/screenshots/webgl_sprites.jpg and b/examples/screenshots/webgl_sprites.jpg differ diff --git a/examples/screenshots/webgl_test_memory.jpg b/examples/screenshots/webgl_test_memory.jpg index 208c8c333fc37f..ddc343438d8ed2 100644 Binary files a/examples/screenshots/webgl_test_memory.jpg and b/examples/screenshots/webgl_test_memory.jpg differ diff --git a/examples/screenshots/webgl_test_wide_gamut.jpg b/examples/screenshots/webgl_test_wide_gamut.jpg index 986891b8000736..8efb363bf4b3be 100644 Binary files a/examples/screenshots/webgl_test_wide_gamut.jpg and b/examples/screenshots/webgl_test_wide_gamut.jpg differ diff --git a/examples/screenshots/webgl_texture2darray.jpg b/examples/screenshots/webgl_texture2darray.jpg index 3a07ae8330a5bb..411494b86384d4 100644 Binary files a/examples/screenshots/webgl_texture2darray.jpg and b/examples/screenshots/webgl_texture2darray.jpg differ diff --git a/examples/screenshots/webgl_texture2darray_compressed.jpg b/examples/screenshots/webgl_texture2darray_compressed.jpg index b67fdfee9c696e..c376e56b623f27 100644 Binary files a/examples/screenshots/webgl_texture2darray_compressed.jpg and b/examples/screenshots/webgl_texture2darray_compressed.jpg differ diff --git a/examples/screenshots/webgl_texture2darray_layerupdate.jpg b/examples/screenshots/webgl_texture2darray_layerupdate.jpg index 32097d84ca2556..0563040b7dd2e4 100644 Binary files a/examples/screenshots/webgl_texture2darray_layerupdate.jpg and b/examples/screenshots/webgl_texture2darray_layerupdate.jpg differ diff --git a/examples/screenshots/webgl_texture3d.jpg b/examples/screenshots/webgl_texture3d.jpg index 1f7eccb2e15408..40b064da6b3148 100644 Binary files a/examples/screenshots/webgl_texture3d.jpg and b/examples/screenshots/webgl_texture3d.jpg differ diff --git a/examples/screenshots/webgl_texture3d_partialupdate.jpg b/examples/screenshots/webgl_texture3d_partialupdate.jpg index b5d8104e183813..22724f1df7b9c3 100644 Binary files a/examples/screenshots/webgl_texture3d_partialupdate.jpg and b/examples/screenshots/webgl_texture3d_partialupdate.jpg differ diff --git a/examples/screenshots/webgl_tonemapping.jpg b/examples/screenshots/webgl_tonemapping.jpg index b7816c4c4885be..6b741d97ee426d 100644 Binary files a/examples/screenshots/webgl_tonemapping.jpg and b/examples/screenshots/webgl_tonemapping.jpg differ diff --git a/examples/screenshots/webgl_tsl_clearcoat.jpg b/examples/screenshots/webgl_tsl_clearcoat.jpg index 3f23098f88b9ca..f83fb0a96c4df3 100644 Binary files a/examples/screenshots/webgl_tsl_clearcoat.jpg and b/examples/screenshots/webgl_tsl_clearcoat.jpg differ diff --git a/examples/screenshots/webgl_tsl_instancing.jpg b/examples/screenshots/webgl_tsl_instancing.jpg index d6181ff421bd6a..ffdce07378797e 100644 Binary files a/examples/screenshots/webgl_tsl_instancing.jpg and b/examples/screenshots/webgl_tsl_instancing.jpg differ diff --git a/examples/screenshots/webgl_tsl_shadowmap.jpg b/examples/screenshots/webgl_tsl_shadowmap.jpg index 9d068f4adc3c68..ea4bb40ec22e2f 100644 Binary files a/examples/screenshots/webgl_tsl_shadowmap.jpg and b/examples/screenshots/webgl_tsl_shadowmap.jpg differ diff --git a/examples/screenshots/webgl_tsl_skinning.jpg b/examples/screenshots/webgl_tsl_skinning.jpg index 218485520bd7fc..7d35b388c1b9c0 100644 Binary files a/examples/screenshots/webgl_tsl_skinning.jpg and b/examples/screenshots/webgl_tsl_skinning.jpg differ diff --git a/examples/screenshots/webgl_ubo.jpg b/examples/screenshots/webgl_ubo.jpg index c3881062a09e17..dfa2046978490f 100644 Binary files a/examples/screenshots/webgl_ubo.jpg and b/examples/screenshots/webgl_ubo.jpg differ diff --git a/examples/screenshots/webgl_ubo_arrays.jpg b/examples/screenshots/webgl_ubo_arrays.jpg index fc0a91181185fa..111d85c18bb10d 100644 Binary files a/examples/screenshots/webgl_ubo_arrays.jpg and b/examples/screenshots/webgl_ubo_arrays.jpg differ diff --git a/examples/screenshots/webgl_video_kinect.jpg b/examples/screenshots/webgl_video_kinect.jpg index 393df11b903246..ed1aa5102bbf61 100644 Binary files a/examples/screenshots/webgl_video_kinect.jpg and b/examples/screenshots/webgl_video_kinect.jpg differ diff --git a/examples/screenshots/webgl_video_panorama_equirectangular.jpg b/examples/screenshots/webgl_video_panorama_equirectangular.jpg index 9f992ba01334c5..1a462579d88bf5 100644 Binary files a/examples/screenshots/webgl_video_panorama_equirectangular.jpg and b/examples/screenshots/webgl_video_panorama_equirectangular.jpg differ diff --git a/examples/screenshots/webgl_volume_cloud.jpg b/examples/screenshots/webgl_volume_cloud.jpg index 599f2682d1d562..b4d930166e4070 100644 Binary files a/examples/screenshots/webgl_volume_cloud.jpg and b/examples/screenshots/webgl_volume_cloud.jpg differ diff --git a/examples/screenshots/webgl_volume_instancing.jpg b/examples/screenshots/webgl_volume_instancing.jpg index c74efc6d332f33..b436072286aed0 100644 Binary files a/examples/screenshots/webgl_volume_instancing.jpg and b/examples/screenshots/webgl_volume_instancing.jpg differ diff --git a/examples/screenshots/webgl_volume_perlin.jpg b/examples/screenshots/webgl_volume_perlin.jpg index 499388e40b7dde..d5084ef083c539 100644 Binary files a/examples/screenshots/webgl_volume_perlin.jpg and b/examples/screenshots/webgl_volume_perlin.jpg differ diff --git a/examples/screenshots/webgl_watch.jpg b/examples/screenshots/webgl_watch.jpg index 3f05ebbe667383..de8530d13610a1 100644 Binary files a/examples/screenshots/webgl_watch.jpg and b/examples/screenshots/webgl_watch.jpg differ diff --git a/examples/screenshots/webgl_worker_offscreencanvas.jpg b/examples/screenshots/webgl_worker_offscreencanvas.jpg index b65e4cf7588b79..9c05c0c02d3d2e 100644 Binary files a/examples/screenshots/webgl_worker_offscreencanvas.jpg and b/examples/screenshots/webgl_worker_offscreencanvas.jpg differ diff --git a/examples/screenshots/webgpu_animation_retargeting.jpg b/examples/screenshots/webgpu_animation_retargeting.jpg index 3d7f808298d336..ca328e22e781e1 100644 Binary files a/examples/screenshots/webgpu_animation_retargeting.jpg and b/examples/screenshots/webgpu_animation_retargeting.jpg differ diff --git a/examples/screenshots/webgpu_animation_retargeting_readyplayer.jpg b/examples/screenshots/webgpu_animation_retargeting_readyplayer.jpg index a39d29eb7ff7e9..6cef2dcaee9373 100644 Binary files a/examples/screenshots/webgpu_animation_retargeting_readyplayer.jpg and b/examples/screenshots/webgpu_animation_retargeting_readyplayer.jpg differ diff --git a/examples/screenshots/webgpu_backdrop.jpg b/examples/screenshots/webgpu_backdrop.jpg index fa2f1130a43ae8..3f05fde1f801db 100644 Binary files a/examples/screenshots/webgpu_backdrop.jpg and b/examples/screenshots/webgpu_backdrop.jpg differ diff --git a/examples/screenshots/webgpu_backdrop_area.jpg b/examples/screenshots/webgpu_backdrop_area.jpg index 3b775b449537fa..b02962b19a48d1 100644 Binary files a/examples/screenshots/webgpu_backdrop_area.jpg and b/examples/screenshots/webgpu_backdrop_area.jpg differ diff --git a/examples/screenshots/webgpu_camera.jpg b/examples/screenshots/webgpu_camera.jpg index 677f91fcd8a3d8..a54cc0ab746996 100644 Binary files a/examples/screenshots/webgpu_camera.jpg and b/examples/screenshots/webgpu_camera.jpg differ diff --git a/examples/screenshots/webgpu_camera_array.jpg b/examples/screenshots/webgpu_camera_array.jpg index e9f7a47c7cd8ef..abd54ea7a0d6de 100644 Binary files a/examples/screenshots/webgpu_camera_array.jpg and b/examples/screenshots/webgpu_camera_array.jpg differ diff --git a/examples/screenshots/webgpu_camera_logarithmicdepthbuffer.jpg b/examples/screenshots/webgpu_camera_logarithmicdepthbuffer.jpg index 68340a8fc4a5b7..dfea466dee1fe4 100644 Binary files a/examples/screenshots/webgpu_camera_logarithmicdepthbuffer.jpg and b/examples/screenshots/webgpu_camera_logarithmicdepthbuffer.jpg differ diff --git a/examples/screenshots/webgpu_caustics.jpg b/examples/screenshots/webgpu_caustics.jpg index 1e251635d8fb01..a604092f791bb2 100644 Binary files a/examples/screenshots/webgpu_caustics.jpg and b/examples/screenshots/webgpu_caustics.jpg differ diff --git a/examples/screenshots/webgpu_centroid_sampling.jpg b/examples/screenshots/webgpu_centroid_sampling.jpg index 0875be1868f7d2..449d4b272e52e6 100644 Binary files a/examples/screenshots/webgpu_centroid_sampling.jpg and b/examples/screenshots/webgpu_centroid_sampling.jpg differ diff --git a/examples/screenshots/webgpu_clearcoat.jpg b/examples/screenshots/webgpu_clearcoat.jpg index 29739381d7f3dc..678a7af5e71dd7 100644 Binary files a/examples/screenshots/webgpu_clearcoat.jpg and b/examples/screenshots/webgpu_clearcoat.jpg differ diff --git a/examples/screenshots/webgpu_clipping.jpg b/examples/screenshots/webgpu_clipping.jpg index 97754d29d28fa4..60fb4522b7329f 100644 Binary files a/examples/screenshots/webgpu_clipping.jpg and b/examples/screenshots/webgpu_clipping.jpg differ diff --git a/examples/screenshots/webgpu_compile_async.jpg b/examples/screenshots/webgpu_compile_async.jpg index ff3afe1088211e..1a7c9690439a31 100644 Binary files a/examples/screenshots/webgpu_compile_async.jpg and b/examples/screenshots/webgpu_compile_async.jpg differ diff --git a/examples/screenshots/webgpu_compute_audio.jpg b/examples/screenshots/webgpu_compute_audio.jpg index 001fe203e0b94e..616ea28582e5eb 100644 Binary files a/examples/screenshots/webgpu_compute_audio.jpg and b/examples/screenshots/webgpu_compute_audio.jpg differ diff --git a/examples/screenshots/webgpu_compute_birds.jpg b/examples/screenshots/webgpu_compute_birds.jpg index 0da12cbbe354d7..2b03a8e4dc1c8a 100644 Binary files a/examples/screenshots/webgpu_compute_birds.jpg and b/examples/screenshots/webgpu_compute_birds.jpg differ diff --git a/examples/screenshots/webgpu_compute_geometry.jpg b/examples/screenshots/webgpu_compute_geometry.jpg index 1445f3e869ca70..744d71be1669f6 100644 Binary files a/examples/screenshots/webgpu_compute_geometry.jpg and b/examples/screenshots/webgpu_compute_geometry.jpg differ diff --git a/examples/screenshots/webgpu_compute_particles.jpg b/examples/screenshots/webgpu_compute_particles.jpg index 7d168f35f39727..56da9de25a8905 100644 Binary files a/examples/screenshots/webgpu_compute_particles.jpg and b/examples/screenshots/webgpu_compute_particles.jpg differ diff --git a/examples/screenshots/webgpu_compute_particles_rain.jpg b/examples/screenshots/webgpu_compute_particles_rain.jpg index 9e6dc17c7e7336..ad44b454bde21d 100644 Binary files a/examples/screenshots/webgpu_compute_particles_rain.jpg and b/examples/screenshots/webgpu_compute_particles_rain.jpg differ diff --git a/examples/screenshots/webgpu_compute_particles_snow.jpg b/examples/screenshots/webgpu_compute_particles_snow.jpg index d7531389569d2b..e3e85950fe3ff1 100644 Binary files a/examples/screenshots/webgpu_compute_particles_snow.jpg and b/examples/screenshots/webgpu_compute_particles_snow.jpg differ diff --git a/examples/screenshots/webgpu_compute_points.jpg b/examples/screenshots/webgpu_compute_points.jpg index b145f01116bd93..6a4c996c31c38d 100644 Binary files a/examples/screenshots/webgpu_compute_points.jpg and b/examples/screenshots/webgpu_compute_points.jpg differ diff --git a/examples/screenshots/webgpu_compute_reduce.jpg b/examples/screenshots/webgpu_compute_reduce.jpg index 18cf422d54b0f6..74fb97bfe87467 100644 Binary files a/examples/screenshots/webgpu_compute_reduce.jpg and b/examples/screenshots/webgpu_compute_reduce.jpg differ diff --git a/examples/screenshots/webgpu_compute_sort_bitonic.jpg b/examples/screenshots/webgpu_compute_sort_bitonic.jpg index a0a4d0c1c21099..62df1c8f2d9cf6 100644 Binary files a/examples/screenshots/webgpu_compute_sort_bitonic.jpg and b/examples/screenshots/webgpu_compute_sort_bitonic.jpg differ diff --git a/examples/screenshots/webgpu_compute_texture.jpg b/examples/screenshots/webgpu_compute_texture.jpg index 83942f79a4fb43..a8c3dc4c8e387f 100644 Binary files a/examples/screenshots/webgpu_compute_texture.jpg and b/examples/screenshots/webgpu_compute_texture.jpg differ diff --git a/examples/screenshots/webgpu_compute_texture_3d.jpg b/examples/screenshots/webgpu_compute_texture_3d.jpg index 0f418a4bdb1013..dfbba8872e2ad7 100644 Binary files a/examples/screenshots/webgpu_compute_texture_3d.jpg and b/examples/screenshots/webgpu_compute_texture_3d.jpg differ diff --git a/examples/screenshots/webgpu_compute_texture_pingpong.jpg b/examples/screenshots/webgpu_compute_texture_pingpong.jpg index 7aa982376111b6..45057766dd90cb 100644 Binary files a/examples/screenshots/webgpu_compute_texture_pingpong.jpg and b/examples/screenshots/webgpu_compute_texture_pingpong.jpg differ diff --git a/examples/screenshots/webgpu_compute_water.jpg b/examples/screenshots/webgpu_compute_water.jpg index 20356c0228cf6a..6d63c2b735906f 100644 Binary files a/examples/screenshots/webgpu_compute_water.jpg and b/examples/screenshots/webgpu_compute_water.jpg differ diff --git a/examples/screenshots/webgpu_cubemap_dynamic.jpg b/examples/screenshots/webgpu_cubemap_dynamic.jpg index 3db49ee540d93a..4a2b08a58101ec 100644 Binary files a/examples/screenshots/webgpu_cubemap_dynamic.jpg and b/examples/screenshots/webgpu_cubemap_dynamic.jpg differ diff --git a/examples/screenshots/webgpu_custom_fog.jpg b/examples/screenshots/webgpu_custom_fog.jpg index 48ada44aff90d9..fe4ef73ea90393 100644 Binary files a/examples/screenshots/webgpu_custom_fog.jpg and b/examples/screenshots/webgpu_custom_fog.jpg differ diff --git a/examples/screenshots/webgpu_custom_fog_scattering.jpg b/examples/screenshots/webgpu_custom_fog_scattering.jpg index 55bb2aba556f34..1150ca5c00059e 100644 Binary files a/examples/screenshots/webgpu_custom_fog_scattering.jpg and b/examples/screenshots/webgpu_custom_fog_scattering.jpg differ diff --git a/examples/screenshots/webgpu_depth_texture.jpg b/examples/screenshots/webgpu_depth_texture.jpg index e933313a051469..ee3997417130aa 100644 Binary files a/examples/screenshots/webgpu_depth_texture.jpg and b/examples/screenshots/webgpu_depth_texture.jpg differ diff --git a/examples/screenshots/webgpu_display_stereo.jpg b/examples/screenshots/webgpu_display_stereo.jpg index edf608b85fc4b0..e75aaca1fedd9e 100644 Binary files a/examples/screenshots/webgpu_display_stereo.jpg and b/examples/screenshots/webgpu_display_stereo.jpg differ diff --git a/examples/screenshots/webgpu_equirectangular.jpg b/examples/screenshots/webgpu_equirectangular.jpg index f8c27aa9b24bc0..79a234570e84e7 100644 Binary files a/examples/screenshots/webgpu_equirectangular.jpg and b/examples/screenshots/webgpu_equirectangular.jpg differ diff --git a/examples/screenshots/webgpu_fog_height.jpg b/examples/screenshots/webgpu_fog_height.jpg index 80573f9fa7f404..f89da126a2d1cc 100644 Binary files a/examples/screenshots/webgpu_fog_height.jpg and b/examples/screenshots/webgpu_fog_height.jpg differ diff --git a/examples/screenshots/webgpu_hdr.jpg b/examples/screenshots/webgpu_hdr.jpg index d91c7c48b3b8ef..ad233f2a2f1b78 100644 Binary files a/examples/screenshots/webgpu_hdr.jpg and b/examples/screenshots/webgpu_hdr.jpg differ diff --git a/examples/screenshots/webgpu_instance_mesh.jpg b/examples/screenshots/webgpu_instance_mesh.jpg index f09df1f160180c..7354a19980a86e 100644 Binary files a/examples/screenshots/webgpu_instance_mesh.jpg and b/examples/screenshots/webgpu_instance_mesh.jpg differ diff --git a/examples/screenshots/webgpu_instance_path.jpg b/examples/screenshots/webgpu_instance_path.jpg index e1305e868e6aa5..3bf5710bed5597 100644 Binary files a/examples/screenshots/webgpu_instance_path.jpg and b/examples/screenshots/webgpu_instance_path.jpg differ diff --git a/examples/screenshots/webgpu_instance_points.jpg b/examples/screenshots/webgpu_instance_points.jpg index e83ca659108f6c..d99a4bdd02aabb 100644 Binary files a/examples/screenshots/webgpu_instance_points.jpg and b/examples/screenshots/webgpu_instance_points.jpg differ diff --git a/examples/screenshots/webgpu_instance_sprites.jpg b/examples/screenshots/webgpu_instance_sprites.jpg index 050b315addac21..960245f4a9c785 100644 Binary files a/examples/screenshots/webgpu_instance_sprites.jpg and b/examples/screenshots/webgpu_instance_sprites.jpg differ diff --git a/examples/screenshots/webgpu_instance_uniform.jpg b/examples/screenshots/webgpu_instance_uniform.jpg index 4790d6d41677b6..41a71e727da057 100644 Binary files a/examples/screenshots/webgpu_instance_uniform.jpg and b/examples/screenshots/webgpu_instance_uniform.jpg differ diff --git a/examples/screenshots/webgpu_instancing_morph.jpg b/examples/screenshots/webgpu_instancing_morph.jpg index 800ff9b5f6a4fd..7b12c250e83e43 100644 Binary files a/examples/screenshots/webgpu_instancing_morph.jpg and b/examples/screenshots/webgpu_instancing_morph.jpg differ diff --git a/examples/screenshots/webgpu_layers.jpg b/examples/screenshots/webgpu_layers.jpg index 9affd4c2260c1d..0dd839da04de8b 100644 Binary files a/examples/screenshots/webgpu_layers.jpg and b/examples/screenshots/webgpu_layers.jpg differ diff --git a/examples/screenshots/webgpu_lensflares.jpg b/examples/screenshots/webgpu_lensflares.jpg index 44badd66289424..9d962a123cf094 100644 Binary files a/examples/screenshots/webgpu_lensflares.jpg and b/examples/screenshots/webgpu_lensflares.jpg differ diff --git a/examples/screenshots/webgpu_lightprobe.jpg b/examples/screenshots/webgpu_lightprobe.jpg index 5599d9f3d166cd..dcf587c63bc7a1 100644 Binary files a/examples/screenshots/webgpu_lightprobe.jpg and b/examples/screenshots/webgpu_lightprobe.jpg differ diff --git a/examples/screenshots/webgpu_lightprobe_cubecamera.jpg b/examples/screenshots/webgpu_lightprobe_cubecamera.jpg index 5d75a244773958..b928defcf6b0da 100644 Binary files a/examples/screenshots/webgpu_lightprobe_cubecamera.jpg and b/examples/screenshots/webgpu_lightprobe_cubecamera.jpg differ diff --git a/examples/screenshots/webgpu_lights_custom.jpg b/examples/screenshots/webgpu_lights_custom.jpg index 2ef916b0fabfec..6c4deb1d0c3eb7 100644 Binary files a/examples/screenshots/webgpu_lights_custom.jpg and b/examples/screenshots/webgpu_lights_custom.jpg differ diff --git a/examples/screenshots/webgpu_lights_dynamic.jpg b/examples/screenshots/webgpu_lights_dynamic.jpg index 00e7abad00f74d..9172d06169b3d8 100644 Binary files a/examples/screenshots/webgpu_lights_dynamic.jpg and b/examples/screenshots/webgpu_lights_dynamic.jpg differ diff --git a/examples/screenshots/webgpu_lights_ies_spotlight.jpg b/examples/screenshots/webgpu_lights_ies_spotlight.jpg index 068f5552314ae0..279cd84e75ae98 100644 Binary files a/examples/screenshots/webgpu_lights_ies_spotlight.jpg and b/examples/screenshots/webgpu_lights_ies_spotlight.jpg differ diff --git a/examples/screenshots/webgpu_lights_phong.jpg b/examples/screenshots/webgpu_lights_phong.jpg index 226bac44bb3b68..2ef84eec6849aa 100644 Binary files a/examples/screenshots/webgpu_lights_phong.jpg and b/examples/screenshots/webgpu_lights_phong.jpg differ diff --git a/examples/screenshots/webgpu_lights_physical.jpg b/examples/screenshots/webgpu_lights_physical.jpg index d5b848e4fcb50b..cf53c014ac3c4b 100644 Binary files a/examples/screenshots/webgpu_lights_physical.jpg and b/examples/screenshots/webgpu_lights_physical.jpg differ diff --git a/examples/screenshots/webgpu_lights_pointlights.jpg b/examples/screenshots/webgpu_lights_pointlights.jpg index 40fa29feb9c2ad..92c8d4ce9e97f6 100644 Binary files a/examples/screenshots/webgpu_lights_pointlights.jpg and b/examples/screenshots/webgpu_lights_pointlights.jpg differ diff --git a/examples/screenshots/webgpu_lights_projector.jpg b/examples/screenshots/webgpu_lights_projector.jpg index 470764498873bd..b8467c6d78c4f9 100644 Binary files a/examples/screenshots/webgpu_lights_projector.jpg and b/examples/screenshots/webgpu_lights_projector.jpg differ diff --git a/examples/screenshots/webgpu_lights_rectarealight.jpg b/examples/screenshots/webgpu_lights_rectarealight.jpg index 2eb772eee14944..8960b31e74c283 100644 Binary files a/examples/screenshots/webgpu_lights_rectarealight.jpg and b/examples/screenshots/webgpu_lights_rectarealight.jpg differ diff --git a/examples/screenshots/webgpu_lights_selective.jpg b/examples/screenshots/webgpu_lights_selective.jpg index 922450c4562998..ced6e113c4846f 100644 Binary files a/examples/screenshots/webgpu_lights_selective.jpg and b/examples/screenshots/webgpu_lights_selective.jpg differ diff --git a/examples/screenshots/webgpu_lights_spotlight.jpg b/examples/screenshots/webgpu_lights_spotlight.jpg index a2b41fdaa18c8a..6426992345e09b 100644 Binary files a/examples/screenshots/webgpu_lights_spotlight.jpg and b/examples/screenshots/webgpu_lights_spotlight.jpg differ diff --git a/examples/screenshots/webgpu_lights_tiled.jpg b/examples/screenshots/webgpu_lights_tiled.jpg index 44fbbdc24612b8..c86c0f3b4f980f 100644 Binary files a/examples/screenshots/webgpu_lights_tiled.jpg and b/examples/screenshots/webgpu_lights_tiled.jpg differ diff --git a/examples/screenshots/webgpu_lines_fat.jpg b/examples/screenshots/webgpu_lines_fat.jpg index f6692a14e55dbf..5fa7efc04e3884 100644 Binary files a/examples/screenshots/webgpu_lines_fat.jpg and b/examples/screenshots/webgpu_lines_fat.jpg differ diff --git a/examples/screenshots/webgpu_lines_fat_raycasting.jpg b/examples/screenshots/webgpu_lines_fat_raycasting.jpg index f03716ee60ae7c..db8ffa1d6f9a19 100644 Binary files a/examples/screenshots/webgpu_lines_fat_raycasting.jpg and b/examples/screenshots/webgpu_lines_fat_raycasting.jpg differ diff --git a/examples/screenshots/webgpu_lines_fat_wireframe.jpg b/examples/screenshots/webgpu_lines_fat_wireframe.jpg index 5ec818e32fb1b7..80c6557bcaf5f8 100644 Binary files a/examples/screenshots/webgpu_lines_fat_wireframe.jpg and b/examples/screenshots/webgpu_lines_fat_wireframe.jpg differ diff --git a/examples/screenshots/webgpu_loader_gltf_compressed.jpg b/examples/screenshots/webgpu_loader_gltf_compressed.jpg index 1728f997a0303c..385797b69c4edc 100644 Binary files a/examples/screenshots/webgpu_loader_gltf_compressed.jpg and b/examples/screenshots/webgpu_loader_gltf_compressed.jpg differ diff --git a/examples/screenshots/webgpu_loader_gltf_dispersion.jpg b/examples/screenshots/webgpu_loader_gltf_dispersion.jpg index 68d3b044daa285..d64015af2dcd75 100644 Binary files a/examples/screenshots/webgpu_loader_gltf_dispersion.jpg and b/examples/screenshots/webgpu_loader_gltf_dispersion.jpg differ diff --git a/examples/screenshots/webgpu_loader_gltf_iridescence.jpg b/examples/screenshots/webgpu_loader_gltf_iridescence.jpg index 63c92a72f05e07..2594e262a1567a 100644 Binary files a/examples/screenshots/webgpu_loader_gltf_iridescence.jpg and b/examples/screenshots/webgpu_loader_gltf_iridescence.jpg differ diff --git a/examples/screenshots/webgpu_loader_texture_ktx2.jpg b/examples/screenshots/webgpu_loader_texture_ktx2.jpg index a6c43ff026b112..7ce5a89ef423c4 100644 Binary files a/examples/screenshots/webgpu_loader_texture_ktx2.jpg and b/examples/screenshots/webgpu_loader_texture_ktx2.jpg differ diff --git a/examples/screenshots/webgpu_materials.jpg b/examples/screenshots/webgpu_materials.jpg index 46b2cfd42d5ca9..9a83af3ea8433b 100644 Binary files a/examples/screenshots/webgpu_materials.jpg and b/examples/screenshots/webgpu_materials.jpg differ diff --git a/examples/screenshots/webgpu_materials_alphahash.jpg b/examples/screenshots/webgpu_materials_alphahash.jpg index 1839c5fde427bc..41b0752ff19720 100644 Binary files a/examples/screenshots/webgpu_materials_alphahash.jpg and b/examples/screenshots/webgpu_materials_alphahash.jpg differ diff --git a/examples/screenshots/webgpu_materials_arrays.jpg b/examples/screenshots/webgpu_materials_arrays.jpg index aacbe09eddaa96..696682a0dddb1d 100644 Binary files a/examples/screenshots/webgpu_materials_arrays.jpg and b/examples/screenshots/webgpu_materials_arrays.jpg differ diff --git a/examples/screenshots/webgpu_materials_basic.jpg b/examples/screenshots/webgpu_materials_basic.jpg index dc8d8104a5c101..23e68c96aeccb7 100644 Binary files a/examples/screenshots/webgpu_materials_basic.jpg and b/examples/screenshots/webgpu_materials_basic.jpg differ diff --git a/examples/screenshots/webgpu_materials_cubemap_mipmaps.jpg b/examples/screenshots/webgpu_materials_cubemap_mipmaps.jpg index 68cfabad2d6966..cd5062b158de0d 100644 Binary files a/examples/screenshots/webgpu_materials_cubemap_mipmaps.jpg and b/examples/screenshots/webgpu_materials_cubemap_mipmaps.jpg differ diff --git a/examples/screenshots/webgpu_materials_envmaps.jpg b/examples/screenshots/webgpu_materials_envmaps.jpg index 8c7ff39b2004a4..9fe6ce8f1fb0e4 100644 Binary files a/examples/screenshots/webgpu_materials_envmaps.jpg and b/examples/screenshots/webgpu_materials_envmaps.jpg differ diff --git a/examples/screenshots/webgpu_materials_lightmap.jpg b/examples/screenshots/webgpu_materials_lightmap.jpg index 442a5977a0963d..ab219fe27bd8e7 100644 Binary files a/examples/screenshots/webgpu_materials_lightmap.jpg and b/examples/screenshots/webgpu_materials_lightmap.jpg differ diff --git a/examples/screenshots/webgpu_materials_sss.jpg b/examples/screenshots/webgpu_materials_sss.jpg index 3cbc0f29cec082..6eac364fa0ac57 100644 Binary files a/examples/screenshots/webgpu_materials_sss.jpg and b/examples/screenshots/webgpu_materials_sss.jpg differ diff --git a/examples/screenshots/webgpu_materials_texture_html.jpg b/examples/screenshots/webgpu_materials_texture_html.jpg index c5cc282edd59bd..ab425f0ad55d6d 100644 Binary files a/examples/screenshots/webgpu_materials_texture_html.jpg and b/examples/screenshots/webgpu_materials_texture_html.jpg differ diff --git a/examples/screenshots/webgpu_materials_texture_manualmipmap.jpg b/examples/screenshots/webgpu_materials_texture_manualmipmap.jpg index 3c3c5ef8a4e5e0..4c6f2b7df7beaa 100644 Binary files a/examples/screenshots/webgpu_materials_texture_manualmipmap.jpg and b/examples/screenshots/webgpu_materials_texture_manualmipmap.jpg differ diff --git a/examples/screenshots/webgpu_materials_toon.jpg b/examples/screenshots/webgpu_materials_toon.jpg index 8161b7091b92e7..75b18bc5fcb460 100644 Binary files a/examples/screenshots/webgpu_materials_toon.jpg and b/examples/screenshots/webgpu_materials_toon.jpg differ diff --git a/examples/screenshots/webgpu_mesh_batch.jpg b/examples/screenshots/webgpu_mesh_batch.jpg index 56498a574451ae..a143aba78bc6ee 100644 Binary files a/examples/screenshots/webgpu_mesh_batch.jpg and b/examples/screenshots/webgpu_mesh_batch.jpg differ diff --git a/examples/screenshots/webgpu_mirror.jpg b/examples/screenshots/webgpu_mirror.jpg index a0b67fec14d7dd..b7a8a79e81bd2f 100644 Binary files a/examples/screenshots/webgpu_mirror.jpg and b/examples/screenshots/webgpu_mirror.jpg differ diff --git a/examples/screenshots/webgpu_modifier_curve.jpg b/examples/screenshots/webgpu_modifier_curve.jpg index add6fa63298344..8c375923e0b3ad 100644 Binary files a/examples/screenshots/webgpu_modifier_curve.jpg and b/examples/screenshots/webgpu_modifier_curve.jpg differ diff --git a/examples/screenshots/webgpu_morphtargets.jpg b/examples/screenshots/webgpu_morphtargets.jpg index 92fd03def4e698..25d3faea437548 100644 Binary files a/examples/screenshots/webgpu_morphtargets.jpg and b/examples/screenshots/webgpu_morphtargets.jpg differ diff --git a/examples/screenshots/webgpu_mrt_mask.jpg b/examples/screenshots/webgpu_mrt_mask.jpg index 88d3bca8db4c98..9539ecb980ebf3 100644 Binary files a/examples/screenshots/webgpu_mrt_mask.jpg and b/examples/screenshots/webgpu_mrt_mask.jpg differ diff --git a/examples/screenshots/webgpu_multiple_canvas.jpg b/examples/screenshots/webgpu_multiple_canvas.jpg index 483b3073a95b7c..189326d5adffbd 100644 Binary files a/examples/screenshots/webgpu_multiple_canvas.jpg and b/examples/screenshots/webgpu_multiple_canvas.jpg differ diff --git a/examples/screenshots/webgpu_multiple_elements.jpg b/examples/screenshots/webgpu_multiple_elements.jpg index 0f699b773a14e1..fa6ed60a5204ee 100644 Binary files a/examples/screenshots/webgpu_multiple_elements.jpg and b/examples/screenshots/webgpu_multiple_elements.jpg differ diff --git a/examples/screenshots/webgpu_multiple_rendertargets.jpg b/examples/screenshots/webgpu_multiple_rendertargets.jpg index 933e252977ffb0..a40849baf95f97 100644 Binary files a/examples/screenshots/webgpu_multiple_rendertargets.jpg and b/examples/screenshots/webgpu_multiple_rendertargets.jpg differ diff --git a/examples/screenshots/webgpu_multiple_rendertargets_readback.jpg b/examples/screenshots/webgpu_multiple_rendertargets_readback.jpg index f6ff5520fc67ae..a305481b837d8f 100644 Binary files a/examples/screenshots/webgpu_multiple_rendertargets_readback.jpg and b/examples/screenshots/webgpu_multiple_rendertargets_readback.jpg differ diff --git a/examples/screenshots/webgpu_multisampled_renderbuffers.jpg b/examples/screenshots/webgpu_multisampled_renderbuffers.jpg index 3fb377bc4df692..71a08923881890 100644 Binary files a/examples/screenshots/webgpu_multisampled_renderbuffers.jpg and b/examples/screenshots/webgpu_multisampled_renderbuffers.jpg differ diff --git a/examples/screenshots/webgpu_occlusion.jpg b/examples/screenshots/webgpu_occlusion.jpg index d0c9cae3f47b68..53c8c46e21c66d 100644 Binary files a/examples/screenshots/webgpu_occlusion.jpg and b/examples/screenshots/webgpu_occlusion.jpg differ diff --git a/examples/screenshots/webgpu_ocean.jpg b/examples/screenshots/webgpu_ocean.jpg index ed9d8fc96862d0..7657ce710c4f36 100644 Binary files a/examples/screenshots/webgpu_ocean.jpg and b/examples/screenshots/webgpu_ocean.jpg differ diff --git a/examples/screenshots/webgpu_parallax_uv.jpg b/examples/screenshots/webgpu_parallax_uv.jpg index b2770a9dc08703..e940af1b30ec13 100644 Binary files a/examples/screenshots/webgpu_parallax_uv.jpg and b/examples/screenshots/webgpu_parallax_uv.jpg differ diff --git a/examples/screenshots/webgpu_particles.jpg b/examples/screenshots/webgpu_particles.jpg index 07aa4a4d3e2d5c..7368a92ee9a77c 100644 Binary files a/examples/screenshots/webgpu_particles.jpg and b/examples/screenshots/webgpu_particles.jpg differ diff --git a/examples/screenshots/webgpu_performance_renderbundle.jpg b/examples/screenshots/webgpu_performance_renderbundle.jpg index 2cc95c71faf73a..200dffa9eead9e 100644 Binary files a/examples/screenshots/webgpu_performance_renderbundle.jpg and b/examples/screenshots/webgpu_performance_renderbundle.jpg differ diff --git a/examples/screenshots/webgpu_pmrem_cubemap.jpg b/examples/screenshots/webgpu_pmrem_cubemap.jpg index 0afaabcda74a74..c776cbf42aa707 100644 Binary files a/examples/screenshots/webgpu_pmrem_cubemap.jpg and b/examples/screenshots/webgpu_pmrem_cubemap.jpg differ diff --git a/examples/screenshots/webgpu_pmrem_scene.jpg b/examples/screenshots/webgpu_pmrem_scene.jpg index 53aa9aaf8d1c65..cf2d94d64b6b80 100644 Binary files a/examples/screenshots/webgpu_pmrem_scene.jpg and b/examples/screenshots/webgpu_pmrem_scene.jpg differ diff --git a/examples/screenshots/webgpu_pmrem_test.jpg b/examples/screenshots/webgpu_pmrem_test.jpg index 6d3d99c67f274c..845b3aba90834f 100644 Binary files a/examples/screenshots/webgpu_pmrem_test.jpg and b/examples/screenshots/webgpu_pmrem_test.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing.jpg b/examples/screenshots/webgpu_postprocessing.jpg index f76244f15a5335..0f44bb69e95d7f 100644 Binary files a/examples/screenshots/webgpu_postprocessing.jpg and b/examples/screenshots/webgpu_postprocessing.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_3dlut.jpg b/examples/screenshots/webgpu_postprocessing_3dlut.jpg index 67cf64ce97fdc2..6cd73561ea8603 100644 Binary files a/examples/screenshots/webgpu_postprocessing_3dlut.jpg and b/examples/screenshots/webgpu_postprocessing_3dlut.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_afterimage.jpg b/examples/screenshots/webgpu_postprocessing_afterimage.jpg index 372caa887e2515..36bea79acacf4d 100644 Binary files a/examples/screenshots/webgpu_postprocessing_afterimage.jpg and b/examples/screenshots/webgpu_postprocessing_afterimage.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_anamorphic.jpg b/examples/screenshots/webgpu_postprocessing_anamorphic.jpg index 7f835539f69fce..8f41910256faf7 100644 Binary files a/examples/screenshots/webgpu_postprocessing_anamorphic.jpg and b/examples/screenshots/webgpu_postprocessing_anamorphic.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_bloom.jpg b/examples/screenshots/webgpu_postprocessing_bloom.jpg index 41ef3da51c1bc4..ebe12472c2b4a0 100644 Binary files a/examples/screenshots/webgpu_postprocessing_bloom.jpg and b/examples/screenshots/webgpu_postprocessing_bloom.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_bloom_emissive.jpg b/examples/screenshots/webgpu_postprocessing_bloom_emissive.jpg index a6386c07b75c6f..553f55d1afb7de 100644 Binary files a/examples/screenshots/webgpu_postprocessing_bloom_emissive.jpg and b/examples/screenshots/webgpu_postprocessing_bloom_emissive.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_bloom_selective.jpg b/examples/screenshots/webgpu_postprocessing_bloom_selective.jpg index 572c8955d109ab..8649eaaba37b56 100644 Binary files a/examples/screenshots/webgpu_postprocessing_bloom_selective.jpg and b/examples/screenshots/webgpu_postprocessing_bloom_selective.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_ca.jpg b/examples/screenshots/webgpu_postprocessing_ca.jpg index f80e364de33e3b..a77b5b992ff19a 100644 Binary files a/examples/screenshots/webgpu_postprocessing_ca.jpg and b/examples/screenshots/webgpu_postprocessing_ca.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_difference.jpg b/examples/screenshots/webgpu_postprocessing_difference.jpg index 572f02626401a5..e31942b6aa572a 100644 Binary files a/examples/screenshots/webgpu_postprocessing_difference.jpg and b/examples/screenshots/webgpu_postprocessing_difference.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_fxaa.jpg b/examples/screenshots/webgpu_postprocessing_fxaa.jpg index 7223a2ac004889..c1aeed370d5f74 100644 Binary files a/examples/screenshots/webgpu_postprocessing_fxaa.jpg and b/examples/screenshots/webgpu_postprocessing_fxaa.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_godrays.jpg b/examples/screenshots/webgpu_postprocessing_godrays.jpg index 0a8a358541c7bd..bf4a88623883a5 100644 Binary files a/examples/screenshots/webgpu_postprocessing_godrays.jpg and b/examples/screenshots/webgpu_postprocessing_godrays.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_masking.jpg b/examples/screenshots/webgpu_postprocessing_masking.jpg index e2dee1290c692b..e0f17edc6ed05a 100644 Binary files a/examples/screenshots/webgpu_postprocessing_masking.jpg and b/examples/screenshots/webgpu_postprocessing_masking.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_motion_blur.jpg b/examples/screenshots/webgpu_postprocessing_motion_blur.jpg index 58406759e95a72..0d748b68e188e3 100644 Binary files a/examples/screenshots/webgpu_postprocessing_motion_blur.jpg and b/examples/screenshots/webgpu_postprocessing_motion_blur.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_outline.jpg b/examples/screenshots/webgpu_postprocessing_outline.jpg index 6db47a10a3b052..5f4d7da6888fce 100644 Binary files a/examples/screenshots/webgpu_postprocessing_outline.jpg and b/examples/screenshots/webgpu_postprocessing_outline.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_pixel.jpg b/examples/screenshots/webgpu_postprocessing_pixel.jpg index d47a9eda72e607..10d341a7be639f 100644 Binary files a/examples/screenshots/webgpu_postprocessing_pixel.jpg and b/examples/screenshots/webgpu_postprocessing_pixel.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_radial_blur.jpg b/examples/screenshots/webgpu_postprocessing_radial_blur.jpg index ec913f7d6ea8d5..06b0361625d5c7 100644 Binary files a/examples/screenshots/webgpu_postprocessing_radial_blur.jpg and b/examples/screenshots/webgpu_postprocessing_radial_blur.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_retro.jpg b/examples/screenshots/webgpu_postprocessing_retro.jpg index 39626e76a86680..5c7a6af6b419f5 100644 Binary files a/examples/screenshots/webgpu_postprocessing_retro.jpg and b/examples/screenshots/webgpu_postprocessing_retro.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_smaa.jpg b/examples/screenshots/webgpu_postprocessing_smaa.jpg index 52b47aae5a63e5..5a76fd8fda078a 100644 Binary files a/examples/screenshots/webgpu_postprocessing_smaa.jpg and b/examples/screenshots/webgpu_postprocessing_smaa.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_sobel.jpg b/examples/screenshots/webgpu_postprocessing_sobel.jpg index 21c674e1e8d21c..90c2d42f2396a8 100644 Binary files a/examples/screenshots/webgpu_postprocessing_sobel.jpg and b/examples/screenshots/webgpu_postprocessing_sobel.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_ssaa.jpg b/examples/screenshots/webgpu_postprocessing_ssaa.jpg index 8b11bde1605d5a..d9bd8d2747aa8f 100644 Binary files a/examples/screenshots/webgpu_postprocessing_ssaa.jpg and b/examples/screenshots/webgpu_postprocessing_ssaa.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_ssr.jpg b/examples/screenshots/webgpu_postprocessing_ssr.jpg index c6756672594a05..0719027b3aba37 100644 Binary files a/examples/screenshots/webgpu_postprocessing_ssr.jpg and b/examples/screenshots/webgpu_postprocessing_ssr.jpg differ diff --git a/examples/screenshots/webgpu_postprocessing_transition.jpg b/examples/screenshots/webgpu_postprocessing_transition.jpg index a41b0327e7fa5a..e69d9bbba4b3a7 100644 Binary files a/examples/screenshots/webgpu_postprocessing_transition.jpg and b/examples/screenshots/webgpu_postprocessing_transition.jpg differ diff --git a/examples/screenshots/webgpu_procedural_texture.jpg b/examples/screenshots/webgpu_procedural_texture.jpg index 95dd70c5a2b1cd..1c84edab0cb3a9 100644 Binary files a/examples/screenshots/webgpu_procedural_texture.jpg and b/examples/screenshots/webgpu_procedural_texture.jpg differ diff --git a/examples/screenshots/webgpu_reflection.jpg b/examples/screenshots/webgpu_reflection.jpg index d6f343036ac72b..d1276ff841b35e 100644 Binary files a/examples/screenshots/webgpu_reflection.jpg and b/examples/screenshots/webgpu_reflection.jpg differ diff --git a/examples/screenshots/webgpu_reflection_blurred.jpg b/examples/screenshots/webgpu_reflection_blurred.jpg index d4560ba72ed391..14caa2dec4299b 100644 Binary files a/examples/screenshots/webgpu_reflection_blurred.jpg and b/examples/screenshots/webgpu_reflection_blurred.jpg differ diff --git a/examples/screenshots/webgpu_refraction.jpg b/examples/screenshots/webgpu_refraction.jpg index b8de79bc40502a..f9219be121b833 100644 Binary files a/examples/screenshots/webgpu_refraction.jpg and b/examples/screenshots/webgpu_refraction.jpg differ diff --git a/examples/screenshots/webgpu_rendertarget_2d-array_3d.jpg b/examples/screenshots/webgpu_rendertarget_2d-array_3d.jpg index 515972a47e1631..88cae7ed9ba438 100644 Binary files a/examples/screenshots/webgpu_rendertarget_2d-array_3d.jpg and b/examples/screenshots/webgpu_rendertarget_2d-array_3d.jpg differ diff --git a/examples/screenshots/webgpu_reversed_depth_buffer.jpg b/examples/screenshots/webgpu_reversed_depth_buffer.jpg index bd5fd217e4c8e7..acb8d198987cfa 100644 Binary files a/examples/screenshots/webgpu_reversed_depth_buffer.jpg and b/examples/screenshots/webgpu_reversed_depth_buffer.jpg differ diff --git a/examples/screenshots/webgpu_rtt.jpg b/examples/screenshots/webgpu_rtt.jpg index d078ef629485d9..6c85e5e61d7e74 100644 Binary files a/examples/screenshots/webgpu_rtt.jpg and b/examples/screenshots/webgpu_rtt.jpg differ diff --git a/examples/screenshots/webgpu_sandbox.jpg b/examples/screenshots/webgpu_sandbox.jpg index cf7d879fd68daa..d702bc9cf88972 100644 Binary files a/examples/screenshots/webgpu_sandbox.jpg and b/examples/screenshots/webgpu_sandbox.jpg differ diff --git a/examples/screenshots/webgpu_shadertoy.jpg b/examples/screenshots/webgpu_shadertoy.jpg index 5392af82c66537..8060f06d1822c5 100644 Binary files a/examples/screenshots/webgpu_shadertoy.jpg and b/examples/screenshots/webgpu_shadertoy.jpg differ diff --git a/examples/screenshots/webgpu_shadow_contact.jpg b/examples/screenshots/webgpu_shadow_contact.jpg index fd10102a9b1bc1..ed3495dd7d7d4c 100644 Binary files a/examples/screenshots/webgpu_shadow_contact.jpg and b/examples/screenshots/webgpu_shadow_contact.jpg differ diff --git a/examples/screenshots/webgpu_shadowmap_array.jpg b/examples/screenshots/webgpu_shadowmap_array.jpg index f307f072c983d6..db5178b2ebd74b 100644 Binary files a/examples/screenshots/webgpu_shadowmap_array.jpg and b/examples/screenshots/webgpu_shadowmap_array.jpg differ diff --git a/examples/screenshots/webgpu_shadowmap_csm.jpg b/examples/screenshots/webgpu_shadowmap_csm.jpg index f2b7baf9794621..09113409da95ae 100644 Binary files a/examples/screenshots/webgpu_shadowmap_csm.jpg and b/examples/screenshots/webgpu_shadowmap_csm.jpg differ diff --git a/examples/screenshots/webgpu_shadowmap_opacity.jpg b/examples/screenshots/webgpu_shadowmap_opacity.jpg index 4ee4da268f26b4..b329440676d53a 100644 Binary files a/examples/screenshots/webgpu_shadowmap_opacity.jpg and b/examples/screenshots/webgpu_shadowmap_opacity.jpg differ diff --git a/examples/screenshots/webgpu_shadowmap_pointlight.jpg b/examples/screenshots/webgpu_shadowmap_pointlight.jpg index 0589277c5042d4..8c5e2435982ced 100644 Binary files a/examples/screenshots/webgpu_shadowmap_pointlight.jpg and b/examples/screenshots/webgpu_shadowmap_pointlight.jpg differ diff --git a/examples/screenshots/webgpu_shadowmap_vsm.jpg b/examples/screenshots/webgpu_shadowmap_vsm.jpg index 3f867333b3d390..18118a29ac33b9 100644 Binary files a/examples/screenshots/webgpu_shadowmap_vsm.jpg and b/examples/screenshots/webgpu_shadowmap_vsm.jpg differ diff --git a/examples/screenshots/webgpu_skinning.jpg b/examples/screenshots/webgpu_skinning.jpg index 17e7ad2834b65a..e3eb49adda014d 100644 Binary files a/examples/screenshots/webgpu_skinning.jpg and b/examples/screenshots/webgpu_skinning.jpg differ diff --git a/examples/screenshots/webgpu_skinning_instancing.jpg b/examples/screenshots/webgpu_skinning_instancing.jpg index 174bc83883369c..ec13edbe7468d4 100644 Binary files a/examples/screenshots/webgpu_skinning_instancing.jpg and b/examples/screenshots/webgpu_skinning_instancing.jpg differ diff --git a/examples/screenshots/webgpu_skinning_points.jpg b/examples/screenshots/webgpu_skinning_points.jpg index 62a405c22932c9..de5f9606c7980d 100644 Binary files a/examples/screenshots/webgpu_skinning_points.jpg and b/examples/screenshots/webgpu_skinning_points.jpg differ diff --git a/examples/screenshots/webgpu_sky.jpg b/examples/screenshots/webgpu_sky.jpg index b65eb5a25422a5..e6f3351c202437 100644 Binary files a/examples/screenshots/webgpu_sky.jpg and b/examples/screenshots/webgpu_sky.jpg differ diff --git a/examples/screenshots/webgpu_sprites.jpg b/examples/screenshots/webgpu_sprites.jpg index 212282e83f9d14..475da15c59f75d 100644 Binary files a/examples/screenshots/webgpu_sprites.jpg and b/examples/screenshots/webgpu_sprites.jpg differ diff --git a/examples/screenshots/webgpu_storage_buffer.jpg b/examples/screenshots/webgpu_storage_buffer.jpg index 63528468083d07..037645f4ba94be 100644 Binary files a/examples/screenshots/webgpu_storage_buffer.jpg and b/examples/screenshots/webgpu_storage_buffer.jpg differ diff --git a/examples/screenshots/webgpu_struct_drawindirect.jpg b/examples/screenshots/webgpu_struct_drawindirect.jpg index 58ceae7f0eb0a5..7c7a00b03525c9 100644 Binary files a/examples/screenshots/webgpu_struct_drawindirect.jpg and b/examples/screenshots/webgpu_struct_drawindirect.jpg differ diff --git a/examples/screenshots/webgpu_texturegrad.jpg b/examples/screenshots/webgpu_texturegrad.jpg index bb15abb82c2fd7..13b52e4b4ea320 100644 Binary files a/examples/screenshots/webgpu_texturegrad.jpg and b/examples/screenshots/webgpu_texturegrad.jpg differ diff --git a/examples/screenshots/webgpu_textures_2d-array.jpg b/examples/screenshots/webgpu_textures_2d-array.jpg index 096bc4255063d5..620e0a9bab0fdf 100644 Binary files a/examples/screenshots/webgpu_textures_2d-array.jpg and b/examples/screenshots/webgpu_textures_2d-array.jpg differ diff --git a/examples/screenshots/webgpu_textures_2d-array_compressed.jpg b/examples/screenshots/webgpu_textures_2d-array_compressed.jpg index c92bba94c8d2d4..c7834c502d4328 100644 Binary files a/examples/screenshots/webgpu_textures_2d-array_compressed.jpg and b/examples/screenshots/webgpu_textures_2d-array_compressed.jpg differ diff --git a/examples/screenshots/webgpu_textures_anisotropy.jpg b/examples/screenshots/webgpu_textures_anisotropy.jpg index 580f46555fdd48..1e3ae626a2a65f 100644 Binary files a/examples/screenshots/webgpu_textures_anisotropy.jpg and b/examples/screenshots/webgpu_textures_anisotropy.jpg differ diff --git a/examples/screenshots/webgpu_textures_partialupdate.jpg b/examples/screenshots/webgpu_textures_partialupdate.jpg index 3ce2ba4d03fa04..3a69b056262f58 100644 Binary files a/examples/screenshots/webgpu_textures_partialupdate.jpg and b/examples/screenshots/webgpu_textures_partialupdate.jpg differ diff --git a/examples/screenshots/webgpu_tonemapping.jpg b/examples/screenshots/webgpu_tonemapping.jpg index fa3119aa6fe76c..167bdb096e31b9 100644 Binary files a/examples/screenshots/webgpu_tonemapping.jpg and b/examples/screenshots/webgpu_tonemapping.jpg differ diff --git a/examples/screenshots/webgpu_tsl_compute_attractors_particles.jpg b/examples/screenshots/webgpu_tsl_compute_attractors_particles.jpg index 45f3893c5e836c..f2079b0751e3a6 100644 Binary files a/examples/screenshots/webgpu_tsl_compute_attractors_particles.jpg and b/examples/screenshots/webgpu_tsl_compute_attractors_particles.jpg differ diff --git a/examples/screenshots/webgpu_tsl_earth.jpg b/examples/screenshots/webgpu_tsl_earth.jpg index d56ce6e5bac0bf..f83e2607249a58 100644 Binary files a/examples/screenshots/webgpu_tsl_earth.jpg and b/examples/screenshots/webgpu_tsl_earth.jpg differ diff --git a/examples/screenshots/webgpu_tsl_editor.jpg b/examples/screenshots/webgpu_tsl_editor.jpg index bf39078fbd9008..1448be098b17f5 100644 Binary files a/examples/screenshots/webgpu_tsl_editor.jpg and b/examples/screenshots/webgpu_tsl_editor.jpg differ diff --git a/examples/screenshots/webgpu_tsl_galaxy.jpg b/examples/screenshots/webgpu_tsl_galaxy.jpg index f92277d7b5764f..4a19e9379a3346 100644 Binary files a/examples/screenshots/webgpu_tsl_galaxy.jpg and b/examples/screenshots/webgpu_tsl_galaxy.jpg differ diff --git a/examples/screenshots/webgpu_tsl_halftone.jpg b/examples/screenshots/webgpu_tsl_halftone.jpg index 33448ddb7c7c40..eb51d2daacc898 100644 Binary files a/examples/screenshots/webgpu_tsl_halftone.jpg and b/examples/screenshots/webgpu_tsl_halftone.jpg differ diff --git a/examples/screenshots/webgpu_tsl_interoperability.jpg b/examples/screenshots/webgpu_tsl_interoperability.jpg index 7beccd938d84b9..63e56ad30598d8 100644 Binary files a/examples/screenshots/webgpu_tsl_interoperability.jpg and b/examples/screenshots/webgpu_tsl_interoperability.jpg differ diff --git a/examples/screenshots/webgpu_tsl_procedural_terrain.jpg b/examples/screenshots/webgpu_tsl_procedural_terrain.jpg index bc370f2ad46430..d004d5b8f22525 100644 Binary files a/examples/screenshots/webgpu_tsl_procedural_terrain.jpg and b/examples/screenshots/webgpu_tsl_procedural_terrain.jpg differ diff --git a/examples/screenshots/webgpu_tsl_transpiler.jpg b/examples/screenshots/webgpu_tsl_transpiler.jpg index 555ccc1a45aafd..f588a09a21bb00 100644 Binary files a/examples/screenshots/webgpu_tsl_transpiler.jpg and b/examples/screenshots/webgpu_tsl_transpiler.jpg differ diff --git a/examples/screenshots/webgpu_tsl_vfx_flames.jpg b/examples/screenshots/webgpu_tsl_vfx_flames.jpg index b88d11e11ba2b6..c055af4fddd2b9 100644 Binary files a/examples/screenshots/webgpu_tsl_vfx_flames.jpg and b/examples/screenshots/webgpu_tsl_vfx_flames.jpg differ diff --git a/examples/screenshots/webgpu_tsl_vfx_tornado.jpg b/examples/screenshots/webgpu_tsl_vfx_tornado.jpg index 13c1442f4d6aab..ca23cffc104c47 100644 Binary files a/examples/screenshots/webgpu_tsl_vfx_tornado.jpg and b/examples/screenshots/webgpu_tsl_vfx_tornado.jpg differ diff --git a/examples/screenshots/webgpu_upscaling_fsr1.jpg b/examples/screenshots/webgpu_upscaling_fsr1.jpg index 4139487ea49fe1..020eb291dd7b4a 100644 Binary files a/examples/screenshots/webgpu_upscaling_fsr1.jpg and b/examples/screenshots/webgpu_upscaling_fsr1.jpg differ diff --git a/examples/screenshots/webgpu_upscaling_taau.jpg b/examples/screenshots/webgpu_upscaling_taau.jpg index a1c68a3ec951eb..894082c218a998 100644 Binary files a/examples/screenshots/webgpu_upscaling_taau.jpg and b/examples/screenshots/webgpu_upscaling_taau.jpg differ diff --git a/examples/screenshots/webgpu_video_frame.jpg b/examples/screenshots/webgpu_video_frame.jpg index 0f418a4bdb1013..001fe203e0b94e 100644 Binary files a/examples/screenshots/webgpu_video_frame.jpg and b/examples/screenshots/webgpu_video_frame.jpg differ diff --git a/examples/screenshots/webgpu_video_panorama.jpg b/examples/screenshots/webgpu_video_panorama.jpg index ecee62aa0416b7..91d486a4b229c3 100644 Binary files a/examples/screenshots/webgpu_video_panorama.jpg and b/examples/screenshots/webgpu_video_panorama.jpg differ diff --git a/examples/screenshots/webgpu_volume_caustics.jpg b/examples/screenshots/webgpu_volume_caustics.jpg index aa82186eb8e693..1dbbef938359a1 100644 Binary files a/examples/screenshots/webgpu_volume_caustics.jpg and b/examples/screenshots/webgpu_volume_caustics.jpg differ diff --git a/examples/screenshots/webgpu_volume_cloud.jpg b/examples/screenshots/webgpu_volume_cloud.jpg index 10b8e16b42d955..a99a8bbc4ae367 100644 Binary files a/examples/screenshots/webgpu_volume_cloud.jpg and b/examples/screenshots/webgpu_volume_cloud.jpg differ diff --git a/examples/screenshots/webgpu_volume_lighting.jpg b/examples/screenshots/webgpu_volume_lighting.jpg index 05c8f089d1a88c..75e427118ea762 100644 Binary files a/examples/screenshots/webgpu_volume_lighting.jpg and b/examples/screenshots/webgpu_volume_lighting.jpg differ diff --git a/examples/screenshots/webgpu_volume_lighting_rectarea.jpg b/examples/screenshots/webgpu_volume_lighting_rectarea.jpg index 4209d39279f186..c17cffbf04e7f8 100644 Binary files a/examples/screenshots/webgpu_volume_lighting_rectarea.jpg and b/examples/screenshots/webgpu_volume_lighting_rectarea.jpg differ diff --git a/examples/screenshots/webgpu_volume_perlin.jpg b/examples/screenshots/webgpu_volume_perlin.jpg index 60e771f9ada2cc..0871f12b0e96bf 100644 Binary files a/examples/screenshots/webgpu_volume_perlin.jpg and b/examples/screenshots/webgpu_volume_perlin.jpg differ diff --git a/examples/screenshots/webgpu_xr_cubes.jpg b/examples/screenshots/webgpu_xr_cubes.jpg index 55bd1b0df9749a..8dfe2004e77912 100644 Binary files a/examples/screenshots/webgpu_xr_cubes.jpg and b/examples/screenshots/webgpu_xr_cubes.jpg differ diff --git a/examples/screenshots/webgpu_xr_native_layers.jpg b/examples/screenshots/webgpu_xr_native_layers.jpg index 77a1a91cd1dada..fe451f903eda0c 100644 Binary files a/examples/screenshots/webgpu_xr_native_layers.jpg and b/examples/screenshots/webgpu_xr_native_layers.jpg differ diff --git a/examples/screenshots/webgpu_xr_rollercoaster.jpg b/examples/screenshots/webgpu_xr_rollercoaster.jpg index ccaab2c7cb9b8d..02dbb2a2af89fa 100644 Binary files a/examples/screenshots/webgpu_xr_rollercoaster.jpg and b/examples/screenshots/webgpu_xr_rollercoaster.jpg differ diff --git a/examples/screenshots/webxr_ar_camera_access.jpg b/examples/screenshots/webxr_ar_camera_access.jpg index bb9e95e3e32f2b..e7f74d0591677b 100644 Binary files a/examples/screenshots/webxr_ar_camera_access.jpg and b/examples/screenshots/webxr_ar_camera_access.jpg differ diff --git a/examples/screenshots/webxr_ar_cones.jpg b/examples/screenshots/webxr_ar_cones.jpg index 0f418a4bdb1013..001fe203e0b94e 100644 Binary files a/examples/screenshots/webxr_ar_cones.jpg and b/examples/screenshots/webxr_ar_cones.jpg differ diff --git a/examples/screenshots/webxr_ar_hittest.jpg b/examples/screenshots/webxr_ar_hittest.jpg index 0f418a4bdb1013..001fe203e0b94e 100644 Binary files a/examples/screenshots/webxr_ar_hittest.jpg and b/examples/screenshots/webxr_ar_hittest.jpg differ diff --git a/examples/screenshots/webxr_ar_lighting.jpg b/examples/screenshots/webxr_ar_lighting.jpg index 15d2b11fdcd6c3..65c8b2fb6d08da 100644 Binary files a/examples/screenshots/webxr_ar_lighting.jpg and b/examples/screenshots/webxr_ar_lighting.jpg differ diff --git a/examples/screenshots/webxr_ar_plane_detection.jpg b/examples/screenshots/webxr_ar_plane_detection.jpg index 0f418a4bdb1013..001fe203e0b94e 100644 Binary files a/examples/screenshots/webxr_ar_plane_detection.jpg and b/examples/screenshots/webxr_ar_plane_detection.jpg differ diff --git a/examples/screenshots/webxr_vr_handinput.jpg b/examples/screenshots/webxr_vr_handinput.jpg index 3b652877d081ab..a967391c8a75cf 100644 Binary files a/examples/screenshots/webxr_vr_handinput.jpg and b/examples/screenshots/webxr_vr_handinput.jpg differ diff --git a/examples/screenshots/webxr_vr_handinput_cubes.jpg b/examples/screenshots/webxr_vr_handinput_cubes.jpg index 3b652877d081ab..a967391c8a75cf 100644 Binary files a/examples/screenshots/webxr_vr_handinput_cubes.jpg and b/examples/screenshots/webxr_vr_handinput_cubes.jpg differ diff --git a/examples/screenshots/webxr_vr_handinput_pointerclick.jpg b/examples/screenshots/webxr_vr_handinput_pointerclick.jpg index f213e50d9d3612..420e6b71dbc3f7 100644 Binary files a/examples/screenshots/webxr_vr_handinput_pointerclick.jpg and b/examples/screenshots/webxr_vr_handinput_pointerclick.jpg differ diff --git a/examples/screenshots/webxr_vr_handinput_pointerdrag.jpg b/examples/screenshots/webxr_vr_handinput_pointerdrag.jpg index 020293e08f94b9..abf5f13fc34d40 100644 Binary files a/examples/screenshots/webxr_vr_handinput_pointerdrag.jpg and b/examples/screenshots/webxr_vr_handinput_pointerdrag.jpg differ diff --git a/examples/screenshots/webxr_vr_handinput_pressbutton.jpg b/examples/screenshots/webxr_vr_handinput_pressbutton.jpg index b5137058515d59..189da2eff9c010 100644 Binary files a/examples/screenshots/webxr_vr_handinput_pressbutton.jpg and b/examples/screenshots/webxr_vr_handinput_pressbutton.jpg differ diff --git a/examples/screenshots/webxr_vr_handinput_profiles.jpg b/examples/screenshots/webxr_vr_handinput_profiles.jpg index 3b652877d081ab..a967391c8a75cf 100644 Binary files a/examples/screenshots/webxr_vr_handinput_profiles.jpg and b/examples/screenshots/webxr_vr_handinput_profiles.jpg differ diff --git a/examples/screenshots/webxr_vr_layers.jpg b/examples/screenshots/webxr_vr_layers.jpg index f8bcd418adc14a..3f9a9ad468a489 100755 Binary files a/examples/screenshots/webxr_vr_layers.jpg and b/examples/screenshots/webxr_vr_layers.jpg differ diff --git a/examples/screenshots/webxr_vr_panorama.jpg b/examples/screenshots/webxr_vr_panorama.jpg index ec6f2793a60e6a..9664b2675c137d 100644 Binary files a/examples/screenshots/webxr_vr_panorama.jpg and b/examples/screenshots/webxr_vr_panorama.jpg differ diff --git a/examples/screenshots/webxr_vr_panorama_depth.jpg b/examples/screenshots/webxr_vr_panorama_depth.jpg index ca5ef30c658788..f43cd7353e5270 100644 Binary files a/examples/screenshots/webxr_vr_panorama_depth.jpg and b/examples/screenshots/webxr_vr_panorama_depth.jpg differ diff --git a/examples/screenshots/webxr_vr_rollercoaster.jpg b/examples/screenshots/webxr_vr_rollercoaster.jpg index 81c53bc517fc84..60ee28ddebe5f5 100644 Binary files a/examples/screenshots/webxr_vr_rollercoaster.jpg and b/examples/screenshots/webxr_vr_rollercoaster.jpg differ diff --git a/examples/screenshots/webxr_vr_sandbox.jpg b/examples/screenshots/webxr_vr_sandbox.jpg index c3562ffc4be7b8..c1e61f305cd8f4 100644 Binary files a/examples/screenshots/webxr_vr_sandbox.jpg and b/examples/screenshots/webxr_vr_sandbox.jpg differ diff --git a/examples/screenshots/webxr_vr_teleport.jpg b/examples/screenshots/webxr_vr_teleport.jpg index 194ad896279773..a668639eb9bfb8 100644 Binary files a/examples/screenshots/webxr_vr_teleport.jpg and b/examples/screenshots/webxr_vr_teleport.jpg differ diff --git a/examples/screenshots/webxr_vr_video.jpg b/examples/screenshots/webxr_vr_video.jpg index ecdbcfec95049f..95eb00c3f4495f 100644 Binary files a/examples/screenshots/webxr_vr_video.jpg and b/examples/screenshots/webxr_vr_video.jpg differ diff --git a/examples/screenshots/webxr_xr_ballshooter.jpg b/examples/screenshots/webxr_xr_ballshooter.jpg index beaa96579054ab..73e45b20f0c205 100644 Binary files a/examples/screenshots/webxr_xr_ballshooter.jpg and b/examples/screenshots/webxr_xr_ballshooter.jpg differ diff --git a/examples/screenshots/webxr_xr_controls_transform.jpg b/examples/screenshots/webxr_xr_controls_transform.jpg index 1931b1b51cea28..387cc1a08adb37 100644 Binary files a/examples/screenshots/webxr_xr_controls_transform.jpg and b/examples/screenshots/webxr_xr_controls_transform.jpg differ diff --git a/examples/screenshots/webxr_xr_cubes.jpg b/examples/screenshots/webxr_xr_cubes.jpg index e50c7bc28483b2..bcd078ccd5fbeb 100644 Binary files a/examples/screenshots/webxr_xr_cubes.jpg and b/examples/screenshots/webxr_xr_cubes.jpg differ diff --git a/examples/screenshots/webxr_xr_dragging.jpg b/examples/screenshots/webxr_xr_dragging.jpg index ec657cea4a386f..b41d0bcc69fdb0 100644 Binary files a/examples/screenshots/webxr_xr_dragging.jpg and b/examples/screenshots/webxr_xr_dragging.jpg differ diff --git a/examples/screenshots/webxr_xr_dragging_custom_depth.jpg b/examples/screenshots/webxr_xr_dragging_custom_depth.jpg index 8870958e3e9c94..dbc983e5d0bbd8 100644 Binary files a/examples/screenshots/webxr_xr_dragging_custom_depth.jpg and b/examples/screenshots/webxr_xr_dragging_custom_depth.jpg differ diff --git a/examples/screenshots/webxr_xr_haptics.jpg b/examples/screenshots/webxr_xr_haptics.jpg index f74cc706d6f0a0..b76fc80e9155eb 100644 Binary files a/examples/screenshots/webxr_xr_haptics.jpg and b/examples/screenshots/webxr_xr_haptics.jpg differ diff --git a/examples/screenshots/webxr_xr_marchingcubes.jpg b/examples/screenshots/webxr_xr_marchingcubes.jpg index 7fbf0cd5ba6e4b..43fd820b5cc4db 100644 Binary files a/examples/screenshots/webxr_xr_marchingcubes.jpg and b/examples/screenshots/webxr_xr_marchingcubes.jpg differ diff --git a/examples/screenshots/webxr_xr_paint.jpg b/examples/screenshots/webxr_xr_paint.jpg index 7fbf0cd5ba6e4b..43fd820b5cc4db 100644 Binary files a/examples/screenshots/webxr_xr_paint.jpg and b/examples/screenshots/webxr_xr_paint.jpg differ diff --git a/examples/webgl_loader_ldraw.html b/examples/webgl_loader_ldraw.html index 49f1bf2b52c3cd..b19846aec419f8 100644 --- a/examples/webgl_loader_ldraw.html +++ b/examples/webgl_loader_ldraw.html @@ -66,7 +66,8 @@ 'TIE Interceptor': 'models/6965-1-TIEIntercep_4h4MXk5.mpd_Packed.mpd', 'Star fighter': 'models/6966-1-JediStarfighter-Mini.mpd_Packed.mpd', 'X-Wing': 'models/7140-1-X-wingFighter.mpd_Packed.mpd', - 'AT-ST': 'models/10174-1-ImperialAT-ST-UCS.mpd_Packed.mpd' + 'AT-ST': 'models/10174-1-ImperialAT-ST-UCS.mpd_Packed.mpd', + 'Window': 'models/6156-1-WindowBrick.mpd_Packed.mpd' }; init(); diff --git a/examples/webgl_materials_video.html b/examples/webgl_materials_video.html index abfd620aceb0f5..393ef799da96fe 100644 --- a/examples/webgl_materials_video.html +++ b/examples/webgl_materials_video.html @@ -8,9 +8,6 @@ -
- -
@@ -18,7 +15,7 @@ playing sintel trailer
-