From 37c98fa6bcf0289083926677eacea650ab6d6186 Mon Sep 17 00:00:00 2001 From: sunag Date: Sat, 21 Jun 2025 20:11:59 -0300 Subject: [PATCH 1/3] TSL Transpiler: Fix unary negate after arithmetic operator (#31297) * fix negate * cleanup * Update GLSLDecoder.js --- examples/jsm/transpiler/GLSLDecoder.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/jsm/transpiler/GLSLDecoder.js b/examples/jsm/transpiler/GLSLDecoder.js index 0f8fcbcd491be0..60864e5971690b 100644 --- a/examples/jsm/transpiler/GLSLDecoder.js +++ b/examples/jsm/transpiler/GLSLDecoder.js @@ -327,6 +327,9 @@ class GLSLDecoder { if ( ! token.isOperator || i === 0 || i === tokens.length - 1 ) return; + // important for negate operator after arithmetic operator: a * -1, a * -( b ) + if ( ( inverse && tokens[ i - 1 ].isOperator ) || ( ! inverse && tokens[ i + 1 ].isOperator ) ) return; + if ( groupIndex === 0 && token.str === operator ) { if ( operator === '?' ) { From cde19cf0bce6365b0d62dbaf90fc63b817d9d66e Mon Sep 17 00:00:00 2001 From: sunag Date: Sat, 21 Jun 2025 20:16:09 -0300 Subject: [PATCH 2/3] TSL: Introduce `tangentViewFrame` and `bitangentViewFrame` (#31282) * introduce tangentFrame * improve code style approach --- src/nodes/accessors/Bitangent.js | 26 ++++++++++- src/nodes/accessors/Tangent.js | 26 ++++++++++- src/nodes/accessors/TangentUtils.js | 46 +++++++++++++++++++ src/nodes/display/NormalMapNode.js | 69 +++++++---------------------- 4 files changed, 112 insertions(+), 55 deletions(-) create mode 100644 src/nodes/accessors/TangentUtils.js diff --git a/src/nodes/accessors/Bitangent.js b/src/nodes/accessors/Bitangent.js index 9d5180a02c21a7..fcece65095752d 100644 --- a/src/nodes/accessors/Bitangent.js +++ b/src/nodes/accessors/Bitangent.js @@ -1,6 +1,8 @@ import { Fn } from '../tsl/TSLCore.js'; import { normalGeometry, normalLocal, normalView, normalWorld } from './Normal.js'; import { tangentGeometry, tangentLocal, tangentView, tangentWorld } from './Tangent.js'; +import { bitangentViewFrame } from './TangentUtils.js'; +import { directionToFaceDirection } from '../display/FrontFacingNode.js'; /** * Returns the bitangent node and assigns it to a varying if the material is not flat shaded. @@ -47,7 +49,29 @@ export const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tan * @tsl * @type {Node} */ -export const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' ); +export const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => { + + let node; + + if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) { + + node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize(); + + } else { + + node = bitangentViewFrame; + + } + + if ( material.flatShading !== true ) { + + node = directionToFaceDirection( node ); + + } + + return node; + +}, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' ); /** * TSL object that represents the vertex bitangent in world space of the current rendered object. diff --git a/src/nodes/accessors/Tangent.js b/src/nodes/accessors/Tangent.js index 4b6795eefd4a7d..c7781ffc2d808c 100644 --- a/src/nodes/accessors/Tangent.js +++ b/src/nodes/accessors/Tangent.js @@ -2,6 +2,8 @@ import { attribute } from '../core/AttributeNode.js'; import { cameraViewMatrix } from './Camera.js'; import { modelViewMatrix } from './ModelNode.js'; import { Fn, vec4 } from '../tsl/TSLBase.js'; +import { tangentViewFrame } from './TangentUtils.js'; +import { directionToFaceDirection } from '../display/FrontFacingNode.js'; /** * TSL object that represents the tangent attribute of the current rendered object. @@ -35,7 +37,29 @@ export const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLoc * @tsl * @type {Node} */ -export const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' ); +export const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => { + + let node; + + if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) { + + node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize(); + + } else { + + node = tangentViewFrame; + + } + + if ( material.flatShading !== true ) { + + node = directionToFaceDirection( node ); + + } + + return node; + +}, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' ); /** * TSL object that represents the vertex tangent in world space of the current rendered object. diff --git a/src/nodes/accessors/TangentUtils.js b/src/nodes/accessors/TangentUtils.js new file mode 100644 index 00000000000000..a2bb5b766c8835 --- /dev/null +++ b/src/nodes/accessors/TangentUtils.js @@ -0,0 +1,46 @@ +import { uv as getUV } from './UV.js'; +import { positionView } from './Position.js'; +import { normalView } from './Normal.js'; + +// Normal Mapping Without Precomputed Tangents +// http://www.thetenthplanet.de/archives/1180 + +const uv = getUV(); + +const q0 = positionView.dFdx(); +const q1 = positionView.dFdy(); +const st0 = uv.dFdx(); +const st1 = uv.dFdy(); + +const N = normalView; + +const q1perp = q1.cross( N ); +const q0perp = N.cross( q0 ); + +const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) ); +const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) ); + +const det = T.dot( T ).max( B.dot( B ) ); +const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() ); + +/** + * Tangent vector in view space, computed dynamically from geometry and UV derivatives. + * Useful for normal mapping without precomputed tangents. + * + * Reference: http://www.thetenthplanet.de/archives/1180 + * + * @tsl + * @type {Node} + */ +export const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' ); + +/** + * Bitangent vector in view space, computed dynamically from geometry and UV derivatives. + * Complements the tangentViewFrame for constructing the tangent space basis. + * + * Reference: http://www.thetenthplanet.de/archives/1180 + * + * @tsl + * @type {Node} + */ +export const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' ); diff --git a/src/nodes/display/NormalMapNode.js b/src/nodes/display/NormalMapNode.js index ee5d06b2711c68..7c894becb0ced4 100644 --- a/src/nodes/display/NormalMapNode.js +++ b/src/nodes/display/NormalMapNode.js @@ -1,41 +1,11 @@ import TempNode from '../core/TempNode.js'; -import { add } from '../math/OperatorNode.js'; import { normalView, transformNormalToView } from '../accessors/Normal.js'; -import { positionView } from '../accessors/Position.js'; import { TBNViewMatrix } from '../accessors/AccessorsUtils.js'; -import { uv } from '../accessors/UV.js'; -import { faceDirection } from './FrontFacingNode.js'; -import { Fn, nodeProxy, vec3 } from '../tsl/TSLBase.js'; +import { nodeProxy, vec3 } from '../tsl/TSLBase.js'; import { TangentSpaceNormalMap, ObjectSpaceNormalMap } from '../../constants.js'; - -// Normal Mapping Without Precomputed Tangents -// http://www.thetenthplanet.de/archives/1180 - -const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => { - - const { eye_pos, surf_norm, mapN, uv } = inputs; - - const q0 = eye_pos.dFdx(); - const q1 = eye_pos.dFdy(); - const st0 = uv.dFdx(); - const st1 = uv.dFdy(); - - const N = surf_norm; // normalized - - const q1perp = q1.cross( N ); - const q0perp = N.cross( q0 ); - - const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) ); - const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) ); - - const det = T.dot( T ).max( B.dot( B ) ); - const scale = faceDirection.mul( det.inverseSqrt() ); - - return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize(); - -} ); +import { directionToFaceDirection } from './FrontFacingNode.js'; /** * This class can be used for applying normals maps to materials. @@ -89,7 +59,7 @@ class NormalMapNode extends TempNode { } - setup( builder ) { + setup( { material } ) { const { normalMapType, scaleNode } = this; @@ -97,44 +67,37 @@ class NormalMapNode extends TempNode { if ( scaleNode !== null ) { - normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z ); + let scale = scaleNode; - } - - let outputNode = null; + if ( material.flatShading === true ) { - if ( normalMapType === ObjectSpaceNormalMap ) { + scale = directionToFaceDirection( scale ); - outputNode = transformNormalToView( normalMap ); + } - } else if ( normalMapType === TangentSpaceNormalMap ) { + normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z ); - const tangent = builder.hasGeometryAttribute( 'tangent' ); + } - if ( tangent === true ) { + let output = null; - outputNode = TBNViewMatrix.mul( normalMap ).normalize(); + if ( normalMapType === ObjectSpaceNormalMap ) { - } else { + output = transformNormalToView( normalMap ); - outputNode = perturbNormal2Arb( { - eye_pos: positionView, - surf_norm: normalView, - mapN: normalMap, - uv: uv() - } ); + } else if ( normalMapType === TangentSpaceNormalMap ) { - } + output = TBNViewMatrix.mul( normalMap ).normalize(); } else { console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` ); - outputNode = normalView; // Fallback to default normal view + output = normalView; // Fallback to default normal view } - return outputNode; + return output; } From 8f21de2b812bc63d94044ef334ea6925b2f8326d Mon Sep 17 00:00:00 2001 From: sunag Date: Sat, 21 Jun 2025 20:23:30 -0300 Subject: [PATCH 3/3] Updated builds. --- build/three.cjs | 12 +- build/three.core.js | 10 +- build/three.core.min.js | 2 +- build/three.module.js | 2 + build/three.module.min.js | 2 +- build/three.tsl.js | 4 +- build/three.tsl.min.js | 2 +- build/three.webgpu.js | 571 +++++++++++++++++--------------- build/three.webgpu.min.js | 2 +- build/three.webgpu.nodes.js | 571 +++++++++++++++++--------------- build/three.webgpu.nodes.min.js | 2 +- 11 files changed, 612 insertions(+), 568 deletions(-) diff --git a/build/three.cjs b/build/three.cjs index a9c203de94ebc1..e514779abf6edc 100644 --- a/build/three.cjs +++ b/build/three.cjs @@ -49163,7 +49163,7 @@ class Clock { */ start() { - this.startTime = now(); + this.startTime = performance.now(); this.oldTime = this.startTime; this.elapsedTime = 0; @@ -49212,7 +49212,7 @@ class Clock { if ( this.running ) { - const newTime = now(); + const newTime = performance.now(); diff = ( newTime - this.oldTime ) / 1000; this.oldTime = newTime; @@ -49227,12 +49227,6 @@ class Clock { } -function now() { - - return performance.now(); - -} - const _position$1 = /*@__PURE__*/ new Vector3(); const _quaternion$1 = /*@__PURE__*/ new Quaternion(); const _scale$1 = /*@__PURE__*/ new Vector3(); @@ -65423,6 +65417,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 20 ); if ( parameters.batchingColor ) _programLayers.enable( 21 ); + if ( parameters.gradientMap ) + _programLayers.enable( 22 ); array.push( _programLayers.mask ); _programLayers.disableAll(); diff --git a/build/three.core.js b/build/three.core.js index ec7b33303e4bce..b0a427c0af087c 100644 --- a/build/three.core.js +++ b/build/three.core.js @@ -49161,7 +49161,7 @@ class Clock { */ start() { - this.startTime = now(); + this.startTime = performance.now(); this.oldTime = this.startTime; this.elapsedTime = 0; @@ -49210,7 +49210,7 @@ class Clock { if ( this.running ) { - const newTime = now(); + const newTime = performance.now(); diff = ( newTime - this.oldTime ) / 1000; this.oldTime = newTime; @@ -49225,12 +49225,6 @@ class Clock { } -function now() { - - return performance.now(); - -} - const _position$1 = /*@__PURE__*/ new Vector3(); const _quaternion$1 = /*@__PURE__*/ new Quaternion(); const _scale$1 = /*@__PURE__*/ new Vector3(); diff --git a/build/three.core.min.js b/build/three.core.min.js index 0b272d33364cd3..60f440b1e207b8 100644 --- a/build/three.core.min.js +++ b/build/three.core.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2025 Three.js Authors * SPDX-License-Identifier: MIT */ -const t="178dev",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=100,w=101,M=102,S=103,_=104,A=200,T=201,z=202,I=203,C=204,B=205,k=206,E=207,R=208,P=209,O=210,N=211,F=212,V=213,L=214,j=0,W=1,U=2,D=3,H=4,q=5,J=6,X=7,Y=0,Z=1,G=2,$=0,Q=1,K=2,tt=3,et=4,it=5,st=6,rt=7,nt="attached",at="detached",ot=300,ht=301,lt=302,ct=303,ut=304,dt=306,pt=1e3,mt=1001,yt=1002,gt=1003,ft=1004,xt=1004,bt=1005,vt=1005,wt=1006,Mt=1007,St=1007,_t=1008,At=1008,Tt=1009,zt=1010,It=1011,Ct=1012,Bt=1013,kt=1014,Et=1015,Rt=1016,Pt=1017,Ot=1018,Nt=1020,Ft=35902,Vt=1021,Lt=1022,jt=1023,Wt=1026,Ut=1027,Dt=1028,Ht=1029,qt=1030,Jt=1031,Xt=1032,Yt=1033,Zt=33776,Gt=33777,$t=33778,Qt=33779,Kt=35840,te=35841,ee=35842,ie=35843,se=36196,re=37492,ne=37496,ae=37808,oe=37809,he=37810,le=37811,ce=37812,ue=37813,de=37814,pe=37815,me=37816,ye=37817,ge=37818,fe=37819,xe=37820,be=37821,ve=36492,we=36494,Me=36495,Se=36283,_e=36284,Ae=36285,Te=36286,ze=2200,Ie=2201,Ce=2202,Be=2300,ke=2301,Ee=2302,Re=2400,Pe=2401,Oe=2402,Ne=2500,Fe=2501,Ve=0,Le=1,je=2,We=3200,Ue=3201,De=3202,He=3203,qe=0,Je=1,Xe="",Ye="srgb",Ze="srgb-linear",Ge="linear",$e="srgb",Qe=0,Ke=7680,ti=7681,ei=7682,ii=7683,si=34055,ri=34056,ni=5386,ai=512,oi=513,hi=514,li=515,ci=516,ui=517,di=518,pi=519,mi=512,yi=513,gi=514,fi=515,xi=516,bi=517,vi=518,wi=519,Mi=35044,Si=35048,_i=35040,Ai=35045,Ti=35049,zi=35041,Ii=35046,Ci=35050,Bi=35042,ki="100",Ei="300 es",Ri=2e3,Pi=2001,Oi={COMPUTE:"compute",RENDER:"render"},Ni={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Fi={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};class Vi{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]+Li[t>>16&255]+Li[t>>24&255]+"-"+Li[255&e]+Li[e>>8&255]+"-"+Li[e>>16&15|64]+Li[e>>24&255]+"-"+Li[63&i|128]+Li[i>>8&255]+"-"+Li[i>>16&255]+Li[i>>24&255]+Li[255&s]+Li[s>>8&255]+Li[s>>16&255]+Li[s>>24&255]).toLowerCase()}function Hi(t,e,i){return Math.max(e,Math.min(i,t))}function qi(t,e){return(t%e+e)%e}function Ji(t,e,i){return(1-i)*t+i*e}function Xi(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 Yi(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 Zi={DEG2RAD:Wi,RAD2DEG:Ui,generateUUID:Di,clamp:Hi,euclideanModulo:qi,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:Ji,damp:function(t,e,i,s){return Ji(t,e,1-Math.exp(-i*s))},pingpong:function(t,e=1){return e-Math.abs(qi(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&&(ji=t);let e=ji+=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*Wi},radToDeg:function(t){return t*Ui},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:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Yi,denormalize:Xi};class Gi{constructor(t=0,e=0){Gi.prototype.isVector2=!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=Hi(this.x,t.x,e.x),this.y=Hi(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=Hi(this.x,t,e),this.y=Hi(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hi(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(Hi(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 $i{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];const u=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(0===a)return t[e+0]=o,t[e+1]=h,t[e+2]=l,void(t[e+3]=c);if(1===a)return t[e+0]=u,t[e+1]=d,t[e+2]=p,void(t[e+3]=m);if(c!==m||o!==u||h!==d||l!==p){let t=1-a;const e=o*u+h*d+l*p+c*m,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const r=Math.sqrt(s),n=Math.atan2(r,e*i);t=Math.sin(t*n)/r,a=Math.sin(a*n)/r}const r=a*i;if(o=o*t+u*r,h=h*t+d*r,l=l*t+p*r,c=c*t+m*r,t===1-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:console.warn("THREE.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 iMath.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(Hi(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){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,r=this._z,n=this._w;let a=n*t._w+i*t._x+s*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=n,this._x=i,this._y=s,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*n+e*this._w,this._x=t*i+e*this._x,this._y=t*s+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const h=Math.sqrt(o),l=Math.atan2(h,a),c=Math.sin((1-e)*l)/h,u=Math.sin(e*l)/h;return this._w=n*c+this._w*u,this._x=i*c+this._x*u,this._y=s*c+this._y*u,this._z=r*c+this._z*u,this._onChangeCallback(),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 Qi{constructor(t=0,e=0,i=0){Qi.prototype.isVector3=!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(ts.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ts.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=Hi(this.x,t.x,e.x),this.y=Hi(this.y,t.y,e.y),this.z=Hi(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=Hi(this.x,t,e),this.y=Hi(this.y,t,e),this.z=Hi(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hi(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 Ki.copy(this).projectOnVector(t),this.sub(Ki)}reflect(t){return this.sub(Ki.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(Hi(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 Ki=new Qi,ts=new $i;class es{constructor(t,e,i,s,r,n,a,o,h){es.prototype.isMatrix3=!0,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(is.makeScale(t,e)),this}rotate(t){return this.premultiply(is.makeRotation(-t)),this}translate(t,e){return this.premultiply(is.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 is=new es;function ss(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const rs={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function ns(t,e){return new rs[t](e)}function as(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function os(){const t=as("canvas");return t.style.display="block",t}const hs={};function ls(t){t in hs||(hs[t]=!0,console.warn(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)}))}function us(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function ds(t){const e=t.elements;-1===e[11]?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=1-e[14])}const ps=(new es).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ms=(new es).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ys(){const t={enabled:!0,workingColorSpace:Ze,spaces:{},convert:function(t,e,i){return!1!==this.enabled&&e!==i&&e&&i?(this.spaces[e].transfer===$e&&(t.r=fs(t.r),t.g=fs(t.g),t.b=fs(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===$e&&(t.r=xs(t.r),t.g=xs(t.g),t.b=xs(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?Ge:this.spaces[t].transfer},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 ls("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(e,i)},toWorkingColorSpace:function(e,i){return ls("THREE.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({[Ze]:{primaries:e,whitePoint:s,transfer:Ge,toXYZ:ps,fromXYZ:ms,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:Ye},outputColorSpaceConfig:{drawingBufferColorSpace:Ye}},[Ye]:{primaries:e,whitePoint:s,transfer:$e,toXYZ:ps,fromXYZ:ms,luminanceCoefficients:i,outputColorSpaceConfig:{drawingBufferColorSpace:Ye}}}),t}const gs=ys();function fs(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function xs(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let bs;class vs{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===bs&&(bs=as("canvas")),bs.width=t.width,bs.height=t.height;const e=bs.getContext("2d");t instanceof ImageData?e.putImageData(t,0,0):e.drawImage(t,0,0,t.width,t.height),i=bs}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=as("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}get width(){return this.source.getSize(As).x}get height(){return this.source.getSize(As).y}get depth(){return this.source.getSize(As).z}get image(){return this.source.data}set image(t=null){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.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){console.warn(`THREE.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:console.warn(`THREE.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,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!==ot)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case pt:t.x=t.x-Math.floor(t.x);break;case mt:t.x=t.x<0?0:1;break;case yt: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 pt:t.y=t.y-Math.floor(t.y);break;case mt:t.y=t.y<0?0:1;break;case yt: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++}}Ts.DEFAULT_IMAGE=null,Ts.DEFAULT_MAPPING=ot,Ts.DEFAULT_ANISOTROPY=1;class zs{constructor(t=0,e=0,i=0,s=1){zs.prototype.isVector4=!0,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=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,Ns),Ns.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(Hs),qs.subVectors(this.max,Hs),Vs.subVectors(t.a,Hs),Ls.subVectors(t.b,Hs),js.subVectors(t.c,Hs),Ws.subVectors(Ls,Vs),Us.subVectors(js,Ls),Ds.subVectors(Vs,js);let e=[0,-Ws.z,Ws.y,0,-Us.z,Us.y,0,-Ds.z,Ds.y,Ws.z,0,-Ws.x,Us.z,0,-Us.x,Ds.z,0,-Ds.x,-Ws.y,Ws.x,0,-Us.y,Us.x,0,-Ds.y,Ds.x,0];return!!Ys(e,Vs,Ls,js,qs)&&(e=[1,0,0,0,1,0,0,0,1],!!Ys(e,Vs,Ls,js,qs)&&(Js.crossVectors(Ws,Us),e=[Js.x,Js.y,Js.z],Ys(e,Vs,Ls,js,qs)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Ns).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(Ns).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()||(Os[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Os[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Os[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Os[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Os[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Os[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Os[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Os[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Os)),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 Os=[new Qi,new Qi,new Qi,new Qi,new Qi,new Qi,new Qi,new Qi],Ns=new Qi,Fs=new Ps,Vs=new Qi,Ls=new Qi,js=new Qi,Ws=new Qi,Us=new Qi,Ds=new Qi,Hs=new Qi,qs=new Qi,Js=new Qi,Xs=new Qi;function Ys(t,e,i,s,r){for(let n=0,a=t.length-3;n<=a;n+=3){Xs.fromArray(t,n);const a=r.x*Math.abs(Xs.x)+r.y*Math.abs(Xs.y)+r.z*Math.abs(Xs.z),o=e.dot(Xs),h=i.dot(Xs),l=s.dot(Xs);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const Zs=new Ps,Gs=new Qi,$s=new Qi;class Qs{constructor(t=new Qi,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;void 0!==e?i.copy(e):Zs.setFromPoints(t).getCenter(i);let s=0;for(let e=0,r=t.length;ethis.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;Gs.subVectors(t,this.center);const e=Gs.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(Gs,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):($s.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Gs.copy(t.center).add($s)),this.expandByPoint(Gs.copy(t.center).sub($s))),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}}const Ks=new Qi,tr=new Qi,er=new Qi,ir=new Qi,sr=new Qi,rr=new Qi,nr=new Qi;class ar{constructor(t=new Qi,e=new Qi(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Ks)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Ks.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Ks.copy(this.origin).addScaledVector(this.direction,e),Ks.distanceToSquared(t))}distanceSqToSegment(t,e,i,s){tr.copy(t).add(e).multiplyScalar(.5),er.copy(e).sub(t).normalize(),ir.copy(this.origin).sub(tr);const r=.5*t.distanceTo(e),n=-this.direction.dot(er),a=ir.dot(this.direction),o=-ir.dot(er),h=ir.lengthSq(),l=Math.abs(1-n*n);let c,u,d,p;if(l>0)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(tr).addScaledVector(er,u),d}intersectSphere(t,e){Ks.subVectors(t.center,this.origin);const i=Ks.dot(this.direction),s=Ks.dot(Ks)-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,Ks)}intersectTriangle(t,e,i,s,r){sr.subVectors(e,t),rr.subVectors(i,t),nr.crossVectors(sr,rr);let n,a=this.direction.dot(nr);if(a>0){if(s)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}ir.subVectors(this.origin,t);const o=n*this.direction.dot(rr.crossVectors(ir,rr));if(o<0)return null;const h=n*this.direction.dot(sr.cross(ir));if(h<0)return null;if(o+h>a)return null;const l=-n*ir.dot(nr);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 or{constructor(t,e,i,s,r,n,a,o,h,l,c,u,d,p,m,y){or.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,i,s,r,n,a,o,h,l,c,u,d,p,m,y)}set(t,e,i,s,r,n,a,o,h,l,c,u,d,p,m,y){const g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=s,g[1]=r,g[5]=n,g[9]=a,g[13]=o,g[2]=h,g[6]=l,g[10]=c,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new or).fromArray(this.elements)}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],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/hr.setFromMatrixColumn(t,0).length(),r=1/hr.setFromMatrixColumn(t,1).length(),n=1/hr.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*r,e[5]=i[5]*r,e[6]=i[6]*r,e[7]=0,e[8]=i[8]*n,e[9]=i[9]*n,e[10]=i[10]*n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,n=Math.cos(i),a=Math.sin(i),o=Math.cos(s),h=Math.sin(s),l=Math.cos(r),c=Math.sin(r);if("XYZ"===t.order){const t=n*l,i=n*c,s=a*l,r=a*c;e[0]=o*l,e[4]=-o*c,e[8]=h,e[1]=i+s*h,e[5]=t-r*h,e[9]=-a*o,e[2]=r-t*h,e[6]=s+i*h,e[10]=n*o}else if("YXZ"===t.order){const t=o*l,i=o*c,s=h*l,r=h*c;e[0]=t+r*a,e[4]=s*a-i,e[8]=n*h,e[1]=n*c,e[5]=n*l,e[9]=-a,e[2]=i*a-s,e[6]=r+t*a,e[10]=n*o}else if("ZXY"===t.order){const t=o*l,i=o*c,s=h*l,r=h*c;e[0]=t-r*a,e[4]=-n*c,e[8]=s+i*a,e[1]=i+s*a,e[5]=n*l,e[9]=r-t*a,e[2]=-n*h,e[6]=a,e[10]=n*o}else if("ZYX"===t.order){const t=n*l,i=n*c,s=a*l,r=a*c;e[0]=o*l,e[4]=s*h-i,e[8]=t*h+r,e[1]=o*c,e[5]=r*h+t,e[9]=i*h-s,e[2]=-h,e[6]=a*o,e[10]=n*o}else if("YZX"===t.order){const t=n*o,i=n*h,s=a*o,r=a*h;e[0]=o*l,e[4]=r-t*c,e[8]=s*c+i,e[1]=c,e[5]=n*l,e[9]=-a*l,e[2]=-h*l,e[6]=i*c+s,e[10]=t-r*c}else if("XZY"===t.order){const t=n*o,i=n*h,s=a*o,r=a*h;e[0]=o*l,e[4]=-c,e[8]=h*l,e[1]=t*c+r,e[5]=n*l,e[9]=i*c-s,e[2]=s*c-i,e[6]=a*l,e[10]=r*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(cr,t,ur)}lookAt(t,e,i){const s=this.elements;return mr.subVectors(t,e),0===mr.lengthSq()&&(mr.z=1),mr.normalize(),dr.crossVectors(i,mr),0===dr.lengthSq()&&(1===Math.abs(i.z)?mr.x+=1e-4:mr.z+=1e-4,mr.normalize(),dr.crossVectors(i,mr)),dr.normalize(),pr.crossVectors(mr,dr),s[0]=dr.x,s[4]=pr.x,s[8]=mr.x,s[1]=dr.y,s[5]=pr.y,s[9]=mr.y,s[2]=dr.z,s[6]=pr.z,s[10]=mr.z,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[4],o=i[8],h=i[12],l=i[1],c=i[5],u=i[9],d=i[13],p=i[2],m=i[6],y=i[10],g=i[14],f=i[3],x=i[7],b=i[11],v=i[15],w=s[0],M=s[4],S=s[8],_=s[12],A=s[1],T=s[5],z=s[9],I=s[13],C=s[2],B=s[6],k=s[10],E=s[14],R=s[3],P=s[7],O=s[11],N=s[15];return r[0]=n*w+a*A+o*C+h*R,r[4]=n*M+a*T+o*B+h*P,r[8]=n*S+a*z+o*k+h*O,r[12]=n*_+a*I+o*E+h*N,r[1]=l*w+c*A+u*C+d*R,r[5]=l*M+c*T+u*B+d*P,r[9]=l*S+c*z+u*k+d*O,r[13]=l*_+c*I+u*E+d*N,r[2]=p*w+m*A+y*C+g*R,r[6]=p*M+m*T+y*B+g*P,r[10]=p*S+m*z+y*k+g*O,r[14]=p*_+m*I+y*E+g*N,r[3]=f*w+x*A+b*C+v*R,r[7]=f*M+x*T+b*B+v*P,r[11]=f*S+x*z+b*k+v*O,r[15]=f*_+x*I+b*E+v*N,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],r=t[12],n=t[1],a=t[5],o=t[9],h=t[13],l=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+r*o*c-s*h*c-r*a*u+i*h*u+s*a*d-i*o*d)+t[7]*(+e*o*d-e*h*u+r*n*u-s*n*d+s*h*l-r*o*l)+t[11]*(+e*h*c-e*a*d-r*n*c+i*n*d+r*a*l-i*h*l)+t[15]*(-s*a*l-e*o*c+e*a*u+s*n*c-i*n*u+i*o*l)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}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=t[9],u=t[10],d=t[11],p=t[12],m=t[13],y=t[14],g=t[15],f=c*y*h-m*u*h+m*o*d-a*y*d-c*o*g+a*u*g,x=p*u*h-l*y*h-p*o*d+n*y*d+l*o*g-n*u*g,b=l*m*h-p*c*h+p*a*d-n*m*d-l*a*g+n*c*g,v=p*c*o-l*m*o-p*a*u+n*m*u+l*a*y-n*c*y,w=e*f+i*x+s*b+r*v;if(0===w)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/w;return t[0]=f*M,t[1]=(m*u*r-c*y*r-m*s*d+i*y*d+c*s*g-i*u*g)*M,t[2]=(a*y*r-m*o*r+m*s*h-i*y*h-a*s*g+i*o*g)*M,t[3]=(c*o*r-a*u*r-c*s*h+i*u*h+a*s*d-i*o*d)*M,t[4]=x*M,t[5]=(l*y*r-p*u*r+p*s*d-e*y*d-l*s*g+e*u*g)*M,t[6]=(p*o*r-n*y*r-p*s*h+e*y*h+n*s*g-e*o*g)*M,t[7]=(n*u*r-l*o*r+l*s*h-e*u*h-n*s*d+e*o*d)*M,t[8]=b*M,t[9]=(p*c*r-l*m*r-p*i*d+e*m*d+l*i*g-e*c*g)*M,t[10]=(n*m*r-p*a*r+p*i*h-e*m*h-n*i*g+e*a*g)*M,t[11]=(l*a*r-n*c*r-l*i*h+e*c*h+n*i*d-e*a*d)*M,t[12]=v*M,t[13]=(l*m*s-p*c*s+p*i*u-e*m*u-l*i*y+e*c*y)*M,t[14]=(p*a*s-n*m*s-p*i*o+e*m*o+n*i*y-e*a*y)*M,t[15]=(n*c*s-l*a*s+l*i*o-e*c*o-n*i*u+e*a*u)*M,this}scale(t){const e=this.elements,i=t.x,s=t.y,r=t.z;return e[0]*=i,e[4]*=s,e[8]*=r,e[1]*=i,e[5]*=s,e[9]*=r,e[2]*=i,e[6]*=s,e[10]*=r,e[3]*=i,e[7]*=s,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),r=1-i,n=t.x,a=t.y,o=t.z,h=r*n,l=r*a;return this.set(h*n+i,h*a-s*o,h*o+s*a,0,h*a+s*o,l*a+i,l*o-s*n,0,h*o-s*a,l*o+s*n,r*o*o+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,r,n){return this.set(1,i,r,0,t,1,n,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,r=e._x,n=e._y,a=e._z,o=e._w,h=r+r,l=n+n,c=a+a,u=r*h,d=r*l,p=r*c,m=n*l,y=n*c,g=a*c,f=o*h,x=o*l,b=o*c,v=i.x,w=i.y,M=i.z;return s[0]=(1-(m+g))*v,s[1]=(d+b)*v,s[2]=(p-x)*v,s[3]=0,s[4]=(d-b)*w,s[5]=(1-(u+g))*w,s[6]=(y+f)*w,s[7]=0,s[8]=(p+x)*M,s[9]=(y-f)*M,s[10]=(1-(u+m))*M,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let r=hr.set(s[0],s[1],s[2]).length();const n=hr.set(s[4],s[5],s[6]).length(),a=hr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),t.x=s[12],t.y=s[13],t.z=s[14],lr.copy(this);const o=1/r,h=1/n,l=1/a;return lr.elements[0]*=o,lr.elements[1]*=o,lr.elements[2]*=o,lr.elements[4]*=h,lr.elements[5]*=h,lr.elements[6]*=h,lr.elements[8]*=l,lr.elements[9]*=l,lr.elements[10]*=l,e.setFromRotationMatrix(lr),i.x=r,i.y=n,i.z=a,this}makePerspective(t,e,i,s,r,n,a=2e3){const o=this.elements,h=2*r/(e-t),l=2*r/(i-s),c=(e+t)/(e-t),u=(i+s)/(i-s);let d,p;if(a===Ri)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(a!==Pi)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-n/(n-r),p=-n*r/(n-r)}return o[0]=h,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=l,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,i,s,r,n,a=2e3){const o=this.elements,h=1/(e-t),l=1/(i-s),c=1/(n-r),u=(e+t)*h,d=(i+s)*l;let p,m;if(a===Ri)p=(n+r)*c,m=-2*c;else{if(a!==Pi)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*c,m=-1*c}return o[0]=2*h,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*l,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;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[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const hr=new Qi,lr=new or,cr=new Qi(0,0,0),ur=new Qi(1,1,1),dr=new Qi,pr=new Qi,mr=new Qi,yr=new or,gr=new $i;class fr{constructor(t=0,e=0,i=0,s=fr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}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 order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,r=s[0],n=s[4],a=s[8],o=s[1],h=s[5],l=s[9],c=s[2],u=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(Hi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(u,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Hi(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,h)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(Hi(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Hi(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Hi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Hi(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(u,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return yr.makeRotationFromQuaternion(t),this.setFromRotationMatrix(yr,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return gr.setFromEuler(this),this.setFromQuaternion(gr,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[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._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}fr.DEFAULT_ORDER="XYZ";class xr{constructor(){this.mask=1}set(t){this.mask=1<>>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(),!1===this.matrixAutoUpdate&&(s.matrixAutoUpdate=!1),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.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.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,i,s,r){Or.subVectors(s,e),Nr.subVectors(i,e),Fr.subVectors(t,e);const n=Or.dot(Or),a=Or.dot(Nr),o=Or.dot(Fr),h=Nr.dot(Nr),l=Nr.dot(Fr),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,Vr)&&(Vr.x>=0&&Vr.y>=0&&Vr.x+Vr.y<=1)}static getInterpolation(t,e,i,s,r,n,a,o){return null===this.getBarycoord(t,e,i,s,Vr)?(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,Vr.x),o.addScaledVector(n,Vr.y),o.addScaledVector(a,Vr.z),o)}static getInterpolatedAttribute(t,e,i,s,r,n){return qr.setScalar(0),Jr.setScalar(0),Xr.setScalar(0),qr.fromBufferAttribute(t,e),Jr.fromBufferAttribute(t,i),Xr.fromBufferAttribute(t,s),n.setScalar(0),n.addScaledVector(qr,r.x),n.addScaledVector(Jr,r.y),n.addScaledVector(Xr,r.z),n}static isFrontFacing(t,e,i,s){return Or.subVectors(i,e),Nr.subVectors(t,e),Or.cross(Nr).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 Or.subVectors(this.c,this.b),Nr.subVectors(this.a,this.b),.5*Or.cross(Nr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Yr.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Yr.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,s,r){return Yr.getInterpolation(t,this.a,this.b,this.c,e,i,s,r)}containsPoint(t){return Yr.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Yr.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;Lr.subVectors(s,i),jr.subVectors(r,i),Ur.subVectors(t,i);const o=Lr.dot(Ur),h=jr.dot(Ur);if(o<=0&&h<=0)return e.copy(i);Dr.subVectors(t,s);const l=Lr.dot(Dr),c=jr.dot(Dr);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(Lr,n);Hr.subVectors(t,r);const d=Lr.dot(Hr),p=jr.dot(Hr);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(jr,a);const y=l*p-d*c;if(y<=0&&c-l>=0&&d-p>=0)return Wr.subVectors(r,s),a=(c-l)/(c-l+(d-p)),e.copy(s).addScaledVector(Wr,a);const g=1/(y+m+u);return n=m*g,a=u*g,e.copy(i).addScaledVector(Lr,n).addScaledVector(jr,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Zr={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},Gr={h:0,s:0,l:0},$r={h:0,s:0,l:0};function Qr(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 Kr{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=Ye){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,gs.colorSpaceToWorking(this,e),this}setRGB(t,e,i,s=gs.workingColorSpace){return this.r=t,this.g=e,this.b=i,gs.colorSpaceToWorking(this,s),this}setHSL(t,e,i,s=gs.workingColorSpace){if(t=qi(t,1),e=Hi(e,0,1),i=Hi(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=Qr(r,s,t+1/3),this.g=Qr(r,s,t),this.b=Qr(r,s,t-1/3)}return gs.colorSpaceToWorking(this,s),this}setStyle(t,e=Ye){function i(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.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:console.warn("THREE.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);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ye){const i=Zr[t.toLowerCase()];return void 0!==i?this.setHex(i,e):console.warn("THREE.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=fs(t.r),this.g=fs(t.g),this.b=fs(t.b),this}copyLinearToSRGB(t){return this.r=xs(t.r),this.g=xs(t.g),this.b=xs(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ye){return gs.workingToColorSpace(tn.copy(this),t),65536*Math.round(Hi(255*tn.r,0,255))+256*Math.round(Hi(255*tn.g,0,255))+Math.round(Hi(255*tn.b,0,255))}getHexString(t=Ye){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=gs.workingColorSpace){gs.workingToColorSpace(tn.copy(this),e);const i=tn.r,s=tn.g,r=tn.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!=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){console.warn(`THREE.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:console.warn(`THREE.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()),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!==Ke&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ke&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ke&&(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),!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.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 rn extends sn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Kr(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 fr,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 nn=an();function an(){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 on(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=Hi(t,-65504,65504),nn.floatView[0]=t;const e=nn.uint32View[0],i=e>>23&511;return nn.baseTable[i]+((8388607&e)>>nn.shiftTable[i])}function hn(t){const e=t>>10;return nn.uint32View[0]=nn.mantissaTable[nn.offsetTable[e]+(1023&t)]+nn.exponentTable[e],nn.floatView[0]}class ln{static toHalfFloat(t){return on(t)}static fromHalfFloat(t){return hn(t)}}const cn=new Qi,un=new Gi;let dn=0;class pn{constructor(t,e,i=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:dn++}),this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=Mi,this.updateRanges=[],this.gpuType=Et,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;se.count&&console.warn("THREE.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 Ps);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Qi(-1/0,-1/0,-1/0),new Qi(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){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}kn.copy(r).invert(),En.copy(t.ray).applyMatrix4(kn),null!==i.boundingBox&&!1===En.intersectsBox(i.boundingBox)||this._computeIntersections(t,e,En)}}_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:Wn.clone(),object:t}}(t,e,i,s,On,Nn,Fn,jn);if(c){const t=new Qi;Yr.getBarycoord(jn,On,Nn,Fn,t),r&&(c.uv=Yr.getInterpolatedAttribute(r,o,h,l,t,new Gi)),n&&(c.uv1=Yr.getInterpolatedAttribute(n,o,h,l,t,new Gi)),a&&(c.normal=Yr.getInterpolatedAttribute(a,o,h,l,t,new Qi),c.normal.dot(s.direction)>0&&c.normal.multiplyScalar(-1));const e={a:o,b:h,c:l,normal:new Qi,materialIndex:0};Yr.getNormal(On,Nn,Fn,e.normal),c.face=e,c.barycoord=t}return c}class Hn extends Bn{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 Qi;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&&(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 Gn extends Pr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new or,this.projectionMatrix=new or,this.projectionMatrixInverse=new or,this.coordinateSystem=Ri}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const $n=new Qi,Qn=new Gi,Kn=new Gi;class ta extends Gn{constructor(t=50,e=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Ui*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Wi*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Ui*Math.atan(Math.tan(.5*Wi*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,i){$n.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set($n.x,$n.y).multiplyScalar(-t/$n.z),$n.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set($n.x,$n.y).multiplyScalar(-t/$n.z)}getViewSize(t,e){return this.getViewBounds(t,Qn,Kn),e.subVectors(Kn,Qn)}setViewOffset(t,e,i,s,r,n){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=s,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*Wi*this.fov)/this.zoom,i=2*e,s=this.aspect*i,r=-.5*s;const n=this.view;if(null!==this.view&&this.view.enabled){const t=n.fullWidth,a=n.fullHeight;r+=n.offsetX*s/t,e-=n.offsetY*i/a,s*=n.width/t,i*=n.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,e,e-i,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const ea=-90;class ia extends Pr{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new ta(ea,1,t,e);s.layers=this.layers,this.add(s);const r=new ta(ea,1,t,e);r.layers=this.layers,this.add(r);const n=new ta(ea,1,t,e);n.layers=this.layers,this.add(n);const a=new ta(ea,1,t,e);a.layers=this.layers,this.add(a);const o=new ta(ea,1,t,e);o.layers=this.layers,this.add(o);const h=new ta(ea,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===Ri)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!==Pi)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,t.setRenderTarget(i,0,s),t.render(e,r),t.setRenderTarget(i,1,s),t.render(e,n),t.setRenderTarget(i,2,s),t.render(e,a),t.setRenderTarget(i,3,s),t.render(e,o),t.setRenderTarget(i,4,s),t.render(e,h),i.texture.generateMipmaps=m,t.setRenderTarget(i,5,s),t.render(e,l),t.setRenderTarget(c,u,d),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class sa extends Ts{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 ra extends Cs{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const i={width:t,height:t,depth:1},s=[i,i,i,i,i,i];this.texture=new sa(s),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},s=new Hn(5,5,5),r=new Zn({name:"CubemapFromEquirect",uniforms:qn(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const n=new Un(s,r),a=e.minFilter;e.minFilter===_t&&(e.minFilter=wt);return new ia(1,10,this).update(t,n),e.minFilter=a,n.geometry.dispose(),n.material.dispose(),this}clear(t,e=!0,i=!0,s=!0){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,i,s);t.setRenderTarget(r)}}class na extends Pr{constructor(){super(),this.isGroup=!0,this.type="Group"}}const aa={type:"move"};class oa{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new na,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new na,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Qi,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Qi),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new na,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Qi,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Qi),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,i){let s=null,r=null,n=null;const a=this._targetRay,o=this._grip,h=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState){if(h&&t.hand){n=!0;for(const s of t.hand.values()){const t=e.getJointPose(s,i),r=this._getHandJoint(h,s);null!==t&&(r.matrix.fromArray(t.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=t.radius),r.visible=null!==t}const s=h.joints["index-finger-tip"],r=h.joints["thumb-tip"],a=s.position.distanceTo(r.position),o=.02,l=.005;h.inputState.pinching&&a>o+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));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(aa)))}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 na;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}class ha{constructor(t,e=25e-5){this.isFogExp2=!0,this.name="",this.color=new Kr(t),this.density=e}clone(){return new ha(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class la{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new Kr(t),this.near=e,this.far=i}clone(){return new la(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class ca extends Pr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new fr,this.environmentIntensity=1,this.environmentRotation=new fr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(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}}class ua{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=Mi,this.updateRanges=[],this.version=0,this.uuid=Di()}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.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let s=0,r=this.stride;st.far||e.push({distance:o,point:ga.clone(),uv:Yr.getInterpolation(ga,Ma,Sa,_a,Aa,Ta,za,new Gi),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){ba.subVectors(t,i).addScalar(.5).multiply(s),void 0!==r?(va.x=n*ba.x-r*ba.y,va.y=r*ba.x+n*ba.y):va.copy(ba),t.copy(e),t.x+=va.x,t.y+=va.y,t.applyMatrix4(wa)}const Ba=new Qi,ka=new Qi;class Ea extends Pr{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){Ba.setFromMatrixPosition(this.matrixWorld);const i=t.ray.origin.distanceTo(Ba);this.getObjectForDistance(i).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){Ba.setFromMatrixPosition(t.matrixWorld),ka.setFromMatrixPosition(this.matrixWorld);const i=Ba.distanceTo(ka)/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;s1?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||no.getNormalMatrix(t),s=this.coplanarPoint(so).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 oo=new Qs,ho=new Qi;class lo{constructor(t=new ao,e=new ao,i=new ao,s=new ao,r=new ao,n=new ao){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){const i=this.planes,s=t.elements,r=s[0],n=s[1],a=s[2],o=s[3],h=s[4],l=s[5],c=s[6],u=s[7],d=s[8],p=s[9],m=s[10],y=s[11],g=s[12],f=s[13],x=s[14],b=s[15];if(i[0].setComponents(o-r,u-h,y-d,b-g).normalize(),i[1].setComponents(o+r,u+h,y+d,b+g).normalize(),i[2].setComponents(o+n,u+l,y+p,b+f).normalize(),i[3].setComponents(o-n,u-l,y-p,b-f).normalize(),i[4].setComponents(o-a,u-c,y-m,b-x).normalize(),e===Ri)i[5].setComponents(o+a,u+c,y+m,b+x).normalize();else{if(e!==Pi)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);i[5].setComponents(a,c,m,x).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),oo.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),oo.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(oo)}intersectsSprite(t){return oo.center.set(0,0,0),oo.radius=.7071067811865476,oo.applyMatrix4(t.matrixWorld),this.intersectsSphere(oo)}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,ho.y=s.normal.y>0?t.max.y:t.min.y,ho.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(ho)<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 co=new or,uo=new lo;class po{constructor(){this.coordinateSystem=Ri}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 xo=new or,bo=new Kr(1,1,1),vo=new lo,wo=new po,Mo=new Ps,So=new Qs,_o=new Qi,Ao=new Qi,To=new Qi,zo=new fo,Io=new Un,Co=[];function Bo(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 pn(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 Ps);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(mo),i=this._availableInstanceIds.shift(),this._instanceInfo[i]=e):(i=this._instanceInfo.length,this._instanceInfo.push(e));const s=this._matricesTexture;xo.identity().toArray(s.image.data,16*i),s.needsUpdate=!0;const r=this._colorsTexture;return r&&(bo.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(mo),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);Bo(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 Ps,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 Qs;this.getBoundingBoxAt(t,Mo),Mo.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 Bn,this._initializeGeometry(s));const r=this.geometry;s.index&&ko(s.index.array,r.index.array);for(const t in s.attributes)ko(s.attributes[t].array,r.attributes[t].array)}raycast(t,e){const i=this._instanceInfo,s=this._geometryInfo,r=this.matrixWorld,n=this.geometry;Io.material=this.material,Io.geometry.index=n.index,Io.geometry.attributes=n.attributes,null===Io.geometry.boundingBox&&(Io.geometry.boundingBox=new Ps),null===Io.geometry.boundingSphere&&(Io.geometry.boundingSphere=new Qs);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(),a=null===n?1:n.array.BYTES_PER_ELEMENT,o=this._instanceInfo,h=this._multiDrawStarts,l=this._multiDrawCounts,c=this._geometryInfo,u=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data,m=i.isArrayCamera?wo:vo;u&&!i.isArrayCamera&&(xo.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),vo.setFromProjectionMatrix(xo,t.coordinateSystem));let y=0;if(this.sortObjects){xo.copy(this.matrixWorld).invert(),_o.setFromMatrixPosition(i.matrixWorld).applyMatrix4(xo),Ao.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(xo);for(let t=0,e=o.length;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;ts)return;Lo.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(Lo);return he.far?void 0:{distance:h,point:jo.clone().applyMatrix4(t.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:t}}const Do=new Qi,Ho=new Qi;class qo extends Wo{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 th extends Ts{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;const l=this;"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback((function e(){l.needsUpdate=!0,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)}}class eh extends th{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 ih extends Ts{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=gt,this.minFilter=gt,this.generateMipmaps=!1,this.needsUpdate=!0}}class sh extends Ts{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 rh extends sh{constructor(t,e,i,s,r,n){super(t,e,i,r,n),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=mt,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class nh extends sh{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,ht),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class ah extends Ts{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 oh extends Ts{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 Ms(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 hh extends Bn{constructor(t=1,e=1,i=4,s=8,r=1){super(),this.type="CapsuleGeometry",this.parameters={radius:t,height:e,capSegments:i,radialSegments:s,heightSegments:r},e=Math.max(0,e),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),r=Math.max(1,Math.floor(r));const n=[],a=[],o=[],h=[],l=e/2,c=Math.PI/2*t,u=e,d=2*c+u,p=2*i+r,m=s+1,y=new Qi,g=new Qi;for(let f=0;f<=p;f++){let x=0,b=0,v=0,w=0;if(f<=i){const e=f/i,s=e*Math.PI/2;b=-l-t*Math.cos(s),v=t*Math.sin(s),w=-t*Math.cos(s),x=e*c}else if(f<=i+r){const s=(f-i)/r;b=s*e-l,v=t,w=0,x=c+s*u}else{const e=(f-i-r)/i,s=e*Math.PI/2;b=l+t*Math.sin(s),v=t*Math.cos(s),w=t*Math.sin(s),x=c+u+e*c}const M=Math.max(0,Math.min(1,x/d));let S=0;0===f?S=.5/s:f===p&&(S=-.5/s);for(let t=0;t<=s;t++){const e=t/s,i=e*Math.PI*2,r=Math.sin(i),n=Math.cos(i);g.x=-v*n,g.y=b,g.z=v*r,a.push(g.x,g.y,g.z),y.set(-v*n,w,v*r),y.normalize(),o.push(y.x,y.y,y.z),h.push(e+S,M)}if(f>0){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 Mn(c,3)),this.setAttribute("normal",new Mn(u,3)),this.setAttribute("uv",new Mn(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ch(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class uh extends ch{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 uh(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class dh extends Bn{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 Mn(r,3)),this.setAttribute("normal",new Mn(r.slice(),3)),this.setAttribute("uv",new Mn(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 dh(t.vertices,t.indices,t.radius,t.details)}}class ph extends dh{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 ph(t.radius,t.detail)}}const mh=new Qi,yh=new Qi,gh=new Qi,fh=new Yr;class xh extends Bn{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(Wi*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 Gi:new Qi);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 Qi,s=[],r=[],n=[],a=new Qi,o=new or;for(let e=0;e<=t;e++){const i=e/t;s[e]=this.getTangentAt(i,new Qi)}r[0]=new Qi,n[0]=new Qi;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(Hi(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(Hi(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 vh extends bh{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 Gi){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]:(Sh.subVectors(s[0],s[1]).add(s[0]),a=Sh);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(Ih(a,o.x,h.x,l.x,c.x),Ih(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 Wh extends jh{constructor(t){super(t),this.uuid=Di(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,s=this.holes.length;i80*i){o=1/0,h=1/0;let e=-1/0,s=-1/0;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 qh(n,a,i,o,h,l,0),a}function Dh(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=ul(r/s|0,t[r],t[r+1],n);return n&&nl(n,n.next)&&(dl(n),n=n.next),n}function Hh(t,e){if(!t)return t;e||(e=t);let i,s=t;do{if(i=!1,s.steiner||!nl(s,s.next)&&0!==rl(s.prev,s,s.next))s=s.next;else{if(dl(s),s=e=s.prev,s===s.next)break;i=!0}}while(i||s!==e);return e}function qh(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=Kh(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?Xh(t,s,r,n):Jh(t))e.push(h.i,t.i,l.i),dl(t),t=l.next,o=l.next;else if((t=l)===o){a?1===a?qh(t=Yh(Hh(t),e),e,i,s,r,n,2):2===a&&Zh(t,e,i,s,r,n):qh(Hh(t),e,i,s,r,n,1);break}}}function Jh(t){const e=t.prev,i=t,s=t.next;if(rl(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&&il(r,o,n,h,a,l,m.x,m.y)&&rl(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Xh(t,e,i,s){const r=t.prev,n=t,a=t.next;if(rl(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=Kh(p,m,e,i,s),x=Kh(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&&il(o,c,h,u,l,d,b.x,b.y)&&rl(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&&il(o,c,h,u,l,d,v.x,v.y)&&rl(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&&il(o,c,h,u,l,d,b.x,b.y)&&rl(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&&il(o,c,h,u,l,d,v.x,v.y)&&rl(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Yh(t,e){let i=t;do{const s=i.prev,r=i.next.next;!nl(s,r)&&al(s,i,i.next,r)&&ll(s,r)&&ll(r,s)&&(e.push(s.i,i.i,r.i),dl(i),dl(i.next),i=t=r),i=i.next}while(i!==t);return Hh(i)}function Zh(t,e,i,s,r,n){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&sl(a,t)){let o=cl(a,t);return a=Hh(a,a.next),o=Hh(o,o.next),qh(a,e,i,s,r,n,0),void qh(o,e,i,s,r,n,0)}t=t.next}a=a.next}while(a!==t)}function Gh(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 $h(t,e){const i=function(t,e){let i=e;const s=t.x,r=t.y;let n,a=-1/0;if(nl(t,i))return i;do{if(nl(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&&el(rn.x||i.x===n.x&&Qh(n,i)))&&(n=i,c=e)}i=i.next}while(i!==o);return n}(t,e);if(!i)return e;const s=cl(i,t);return Hh(s,s.next),Hh(i,i.next)}function Qh(t,e){return rl(t.prev,t,e.prev)<0&&rl(e.next,t,t.next)<0}function Kh(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 tl(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 il(t,e,i,s,r,n,a,o){return!(t===a&&e===o)&&el(t,e,i,s,r,n,a,o)}function sl(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&&al(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(ll(t,e)&&ll(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)&&(rl(t.prev,t,e.prev)||rl(t,e.prev,e))||nl(t,e)&&rl(t.prev,t,t.next)>0&&rl(e.prev,e,e.next)>0)}function rl(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function nl(t,e){return t.x===e.x&&t.y===e.y}function al(t,e,i,s){const r=hl(rl(t,e,i)),n=hl(rl(t,e,s)),a=hl(rl(i,s,t)),o=hl(rl(i,s,e));return r!==n&&a!==o||(!(0!==r||!ol(t,i,e))||(!(0!==n||!ol(t,s,e))||(!(0!==a||!ol(i,t,s))||!(0!==o||!ol(i,e,s)))))}function ol(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 hl(t){return t>0?1:t<0?-1:0}function ll(t,e){return rl(t.prev,t,t.next)<0?rl(t,e,t.next)>=0&&rl(t,t.prev,e)>=0:rl(t,e,t.prev)<0||rl(t,t.next,e)<0}function cl(t,e){const i=pl(t.i,t.x,t.y),s=pl(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 ul(t,e,i,s){const r=pl(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 dl(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 pl(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class ml{static triangulate(t,e,i=2){return Uh(t,e,i)}}class yl{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 fl(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 Gi(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 Gi(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!=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 Vl extends sn{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Kr(16777215),this.specular=new Kr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(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.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 Ll extends sn{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Kr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(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 jl extends sn{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(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 Wl extends sn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Kr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(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.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 Ul extends sn{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 Dl extends sn{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 Hl extends sn{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Kr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.flatShading=t.flatShading,this.fog=t.fog,this}}class ql extends Ro{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 Jl(t,e){return t&&t.constructor!==e?"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t):t}function Xl(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Yl(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 Zl(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 Gl(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 $l{static convertArray(t,e){return Jl(t,e)}static isTypedArray(t){return Xl(t)}static getKeyframeOrder(t){return Yl(t)}static sortedArray(t,e,i){return Zl(t,e,i)}static flattenJSON(t,e,i,s){Gl(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 $i).fromArray(d).normalize().conjugate().toArray(d);const p=a.times.length;for(let t=0;t=r)break t;{const a=e[1];t=r)break e}n=i,i=0}}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&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,s=this.values,r=i.length;0===r&&(console.error("THREE.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)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,s),t=!1;break}if(null!==n&&n>s){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,s,n),t=!1;break}n=s}if(void 0!==s&&Xl(s))for(let e=0,i=s.length;e!==i;++e){const i=s[e];if(isNaN(i)){console.error("THREE.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()===Ee,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}}ic.prototype.ValueTypeName="",ic.prototype.TimeBufferType=Float32Array,ic.prototype.ValueBufferType=Float32Array,ic.prototype.DefaultInterpolation=ke;class sc extends ic{constructor(t,e,i){super(t,e,i)}}sc.prototype.ValueTypeName="bool",sc.prototype.ValueBufferType=Array,sc.prototype.DefaultInterpolation=Be,sc.prototype.InterpolantFactoryMethodLinear=void 0,sc.prototype.InterpolantFactoryMethodSmooth=void 0;class rc extends ic{constructor(t,e,i,s){super(t,e,i,s)}}rc.prototype.ValueTypeName="color";class nc extends ic{constructor(t,e,i,s){super(t,e,i,s)}}nc.prototype.ValueTypeName="number";class ac extends Ql{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)$i.slerpFlat(r,0,n,h-a,n,h,o);return r}}class oc extends ic{constructor(t,e,i,s){super(t,e,i,s)}InterpolantFactoryMethodLinear(t){return new ac(this.times,this.values,this.getValueSize(),t)}}oc.prototype.ValueTypeName="quaternion",oc.prototype.InterpolantFactoryMethodSmooth=void 0;class hc extends ic{constructor(t,e,i){super(t,e,i)}}hc.prototype.ValueTypeName="string",hc.prototype.ValueBufferType=Array,hc.prototype.DefaultInterpolation=Be,hc.prototype.InterpolantFactoryMethodLinear=void 0,hc.prototype.InterpolantFactoryMethodSmooth=void 0;class lc extends ic{constructor(t,e,i,s){super(t,e,i,s)}}lc.prototype.ValueTypeName="vector";class cc{constructor(t="",e=-1,i=[],s=2500){this.name=t,this.tracks=i,this.duration=e,this.blendMode=s,this.uuid=Di(),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(uc(i[t]).scale(s));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],i=t.tracks,s={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,s=i.length;t!==s;++t)e.push(ic.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(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(t,e,i,s,r){if(0!==i.length){const n=[],a=[];Gl(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!==gc[t])return void gc[t].push({onLoad:e,onProgress:i,onError:s});gc[t]=[],gc[t].push({onLoad:e,onProgress:i,onError:s});const n=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(n).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const i=gc[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 fc(`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=>{dc.add(t,e);const i=gc[t];delete gc[t];for(let t=0,s=i.length;t{const i=gc[t];if(void 0===i)throw this.manager.itemError(t),e;delete gc[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}}class bc extends yc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new xc(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):console.error(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 Kr).setHex(r.value);break;case"v2":s.uniforms[e].value=(new Gi).fromArray(r.value);break;case"v3":s.uniforms[e].value=(new Qi).fromArray(r.value);break;case"v4":s.uniforms[e].value=(new zs).fromArray(r.value);break;case"m3":s.uniforms[e].value=(new es).fromArray(r.value);break;case"m4":s.uniforms[e].value=(new or).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 Gi).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 Gi).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 Jc.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:Pl,SpriteMaterial:ma,RawShaderMaterial:Ol,ShaderMaterial:Zn,PointsMaterial:Xo,MeshPhysicalMaterial:Fl,MeshStandardMaterial:Nl,MeshPhongMaterial:Vl,MeshToonMaterial:Ll,MeshNormalMaterial:jl,MeshLambertMaterial:Wl,MeshDepthMaterial:Ul,MeshDistanceMaterial:Dl,MeshBasicMaterial:rn,MeshMatcapMaterial:Hl,LineDashedMaterial:ql,LineBasicMaterial:Ro,Material:sn}[t]}}class Xc{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 Yc extends Bn{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 Zc extends yc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new xc(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):console.error(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=ns(r.type,n),o=new ua(a,r.stride);return o.uuid=r.uuid,e[s]=o,o}const r=t.isInstancedBufferGeometry?new Yc:new Bn,n=t.data.index;if(void 0!==n){const t=ns(n.type,n.array);r.setIndex(new pn(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 pa(e,i.itemSize,i.offset,i.normalized)}else{const t=ns(i.type,i.array);n=new(i.isInstancedBufferAttribute?Ya:pn)(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 pc(e);r=new Mc(i),r.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e0){s=new Mc(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 Ps).fromJSON(t.boundingBox)),void 0!==t.boundingSphere&&(i=(new Qs).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 Qs).fromJSON(t.boundingSphere)),void 0!==t.boundingBox&&(n.boundingBox=(new Ps).fromJSON(t.boundingBox));break;case"LOD":n=new Ea;break;case"Line":n=new Wo(h(t.geometry),l(t.material));break;case"LineLoop":n=new Jo(h(t.geometry),l(t.material));break;case"LineSegments":n=new qo(h(t.geometry),l(t.material));break;case"PointCloud":case"Points":n=new Qo(h(t.geometry),l(t.material));break;case"Sprite":n=new Ia(l(t.material));break;case"Group":n=new na;break;case"Bone":n=new Da;break;default:n=new Pr}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.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.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!==tu.has(n))return e&&e(i),r.manager.itemEnd(t),i;s&&s(tu.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;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 dc.add(t,i),e&&e(i),r.manager.itemEnd(t),i})).catch((function(e){s&&s(e),tu.set(o,e),dc.remove(t),r.manager.itemError(t),r.manager.itemEnd(t)}));dc.add(t,o),r.manager.itemStart(t)}}let iu;class su{static getContext(){return void 0===iu&&(iu=new(window.AudioContext||window.webkitAudioContext)),iu}static setContext(t){iu=t}}class ru extends yc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new xc(this.manager);function a(e){s?s(e):console.error(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);su.getContext().decodeAudioData(i,(function(t){e(t)})).catch(a)}catch(t){a(t)}}),i,s)}}const nu=new or,au=new or,ou=new or;class hu{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new ta,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ta,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,ou.copy(t.projectionMatrix);const i=e.eyeSep/2,s=i*e.near/e.focus,r=e.near*Math.tan(Wi*e.fov*.5)/e.zoom;let n,a;au.elements[12]=-i,nu.elements[12]=i,n=-r*e.aspect+s,a=r*e.aspect+s,ou.elements[0]=2*e.near/(a-n),ou.elements[8]=(a+n)/(a-n),this.cameraL.projectionMatrix.copy(ou),n=-r*e.aspect-s,a=r*e.aspect-s,ou.elements[0]=2*e.near/(a-n),ou.elements[8]=(a+n)/(a-n),this.cameraR.projectionMatrix.copy(ou)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(au),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(nu)}}class lu extends ta{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class cu{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=uu(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=uu();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}function uu(){return performance.now()}const du=new Qi,pu=new $i,mu=new Qi,yu=new Qi,gu=new Qi;class fu extends Pr{constructor(){super(),this.type="AudioListener",this.context=su.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new cu}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);const e=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(du,pu,mu),yu.set(0,0,-1).applyQuaternion(pu),gu.set(0,1,0).applyQuaternion(pu),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(du.x,t),e.positionY.linearRampToValueAtTime(du.y,t),e.positionZ.linearRampToValueAtTime(du.z,t),e.forwardX.linearRampToValueAtTime(yu.x,t),e.forwardY.linearRampToValueAtTime(yu.y,t),e.forwardZ.linearRampToValueAtTime(yu.z,t),e.upX.linearRampToValueAtTime(gu.x,t),e.upY.linearRampToValueAtTime(gu.y,t),e.upZ.linearRampToValueAtTime(gu.z,t)}else e.setPosition(du.x,du.y,du.z),e.setOrientation(yu.x,yu.y,yu.z,gu.x,gu.y,gu.z)}}class xu extends Pr{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 console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.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;console.warn("THREE.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;console.warn("THREE.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){$i.slerpFlat(t,e,t,e,t,i,s)}_slerpAdditive(t,e,i,s,r){const n=this._workIndex*r;$i.multiplyQuaternionsFlat(t,n,t,e,t,i),$i.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 Tu="\\[\\]\\.:\\/",zu=new RegExp("["+Tu+"]","g"),Iu="[^"+Tu+"]",Cu="[^"+Tu.replace("\\.","")+"]",Bu=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Iu)+/(WCOD+)?/.source.replace("WCOD",Cu)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Iu)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Iu)+"$"),ku=["material","materials","bones","map"];class Eu{constructor(t,e,i){this.path=e,this.parsedPath=i||Eu.parseTrackName(e),this.node=Eu.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 Eu.Composite(t,e,i):new Eu(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(zu,"")}static parseTrackName(t){const e=Bu.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!==ku.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 Eu(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 Pu{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:Re,endingEnd:Re};for(let t=0;t!==n;++t){const e=r[t].createInterpolant(null);a[t]=e,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===Fe)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.time=s;if(n&&!(1&~r))return e-s}return s}_setEndings(t,e,i){const s=this._interpolantSettings;i?(s.endingStart=Pe,s.endingEnd=Pe):(s.endingStart=t?this.zeroSlopeAtStart?Pe:Re:Oe,s.endingEnd=e?this.zeroSlopeAtEnd?Pe:Re:Oe)}_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 Ou=new Float32Array(1);class Nu extends Vi{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_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 Au(Eu.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,Gu).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 Qu=new Qi,Ku=new Qi;class td{constructor(t=new Qi,e=new Qi){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){Qu.subVectors(t,this.start),Ku.subVectors(this.end,this.start);const i=Ku.dot(Ku);let s=Ku.dot(Qu)/i;return e&&(s=Hi(s,0,1)),s}closestPointToPoint(t,e,i){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(s).add(this.start)}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 ed=new Qi;class id extends Pr{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const i=new Bn,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{zd.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(zd,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 kd extends qo{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 Bn;i.setAttribute("position",new Mn(e,3)),i.setAttribute("color",new Mn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(i,new Ro({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,i){const s=new Kr,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 Ed{constructor(){this.type="ShapePath",this.color=new Kr,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new jh,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=yl.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 Wh,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 Pd(t,e,i,s)}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:t}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=t);export{et as ACESFilmicToneMapping,v as AddEquation,G as AddOperation,Fe as AdditiveAnimationBlendMode,g as AdditiveBlending,st as AgXToneMapping,Vt as AlphaFormat,wi as AlwaysCompare,W as AlwaysDepth,pi as AlwaysStencilFunc,Uc as AmbientLight,Pu as AnimationAction,cc as AnimationClip,bc as AnimationLoader,Nu as AnimationMixer,Ru as AnimationObjectGroup,$l as AnimationUtils,wh as ArcCurve,lu as ArrayCamera,Bd as ArrowHelper,nt as AttachedBindMode,xu as Audio,_u as AudioAnalyser,su as AudioContext,fu as AudioListener,ru as AudioLoader,kd as AxesHelper,d as BackSide,We as BasicDepthPacking,o as BasicShadowMap,Eo as BatchedMesh,Da as Bone,sc as BooleanKeyframeTrack,$u as Box2,Ps as Box3,Ad as Box3Helper,Hn as BoxGeometry,_d as BoxHelper,pn as BufferAttribute,Bn as BufferGeometry,Zc as BufferGeometryLoader,zt as ByteType,dc as Cache,Gn as Camera,wd as CameraHelper,ah as CanvasTexture,hh as CapsuleGeometry,zh as CatmullRomCurve3,tt as CineonToneMapping,lh as CircleGeometry,mt as ClampToEdgeWrapping,cu as Clock,Kr as Color,rc as ColorKeyframeTrack,gs as ColorManagement,rh as CompressedArrayTexture,nh as CompressedCubeTexture,sh as CompressedTexture,vc as CompressedTextureLoader,uh as ConeGeometry,V as ConstantAlphaFactor,N as ConstantColorFactor,Rd as Controls,ia as CubeCamera,ht as CubeReflectionMapping,lt as CubeRefractionMapping,sa as CubeTexture,Sc as CubeTextureLoader,dt as CubeUVReflectionMapping,kh as CubicBezierCurve,Eh as CubicBezierCurve3,Kl as CubicInterpolant,r as CullFaceBack,n as CullFaceFront,a as CullFaceFrontBack,s as CullFaceNone,bh as Curve,Lh as CurvePath,b as CustomBlending,it as CustomToneMapping,ch as CylinderGeometry,Yu as Cylindrical,Es as Data3DTexture,Bs as DataArrayTexture,Ha as DataTexture,_c as DataTextureLoader,ln as DataUtils,ii as DecrementStencilOp,ri as DecrementWrapStencilOp,mc as DefaultLoadingManager,Wt as DepthFormat,Ut as DepthStencilFormat,oh as DepthTexture,at as DetachedBindMode,Wc as DirectionalLight,xd as DirectionalLightHelper,ec as DiscreteInterpolant,ph as DodecahedronGeometry,p as DoubleSide,k as DstAlphaFactor,R as DstColorFactor,Ci as DynamicCopyUsage,Si as DynamicDrawUsage,Ti as DynamicReadUsage,xh as EdgesGeometry,vh as EllipseCurve,gi as EqualCompare,H as EqualDepth,hi as EqualStencilFunc,ct as EquirectangularReflectionMapping,ut as EquirectangularRefractionMapping,fr as Euler,Vi as EventDispatcher,xl as ExtrudeGeometry,xc as FileLoader,wn as Float16BufferAttribute,Mn as Float32BufferAttribute,Et as FloatType,la as Fog,ha as FogExp2,ih as FramebufferTexture,u as FrontSide,lo as Frustum,po as FrustumArray,Uu as GLBufferAttribute,ki as GLSL1,Ei as GLSL3,xi as GreaterCompare,J as GreaterDepth,vi as GreaterEqualCompare,q as GreaterEqualDepth,di as GreaterEqualStencilFunc,ci as GreaterStencilFunc,pd as GridHelper,na as Group,Rt as HalfFloatType,zc as HemisphereLight,dd as HemisphereLightHelper,vl as IcosahedronGeometry,eu as ImageBitmapLoader,Mc as ImageLoader,vs as ImageUtils,ei as IncrementStencilOp,si as IncrementWrapStencilOp,Ya as InstancedBufferAttribute,Yc as InstancedBufferGeometry,Wu as InstancedInterleavedBuffer,io as InstancedMesh,fn as Int16BufferAttribute,bn as Int32BufferAttribute,mn as Int8BufferAttribute,Bt as IntType,ua as InterleavedBuffer,pa as InterleavedBufferAttribute,Ql as Interpolant,Be as InterpolateDiscrete,ke as InterpolateLinear,Ee as InterpolateSmooth,Fi as InterpolationSamplingMode,Ni as InterpolationSamplingType,ni as InvertStencilOp,Ke as KeepStencilOp,ic as KeyframeTrack,Ea as LOD,wl as LatheGeometry,xr as Layers,yi as LessCompare,U as LessDepth,fi as LessEqualCompare,D as LessEqualDepth,li as LessEqualStencilFunc,oi as LessStencilFunc,Tc as Light,qc as LightProbe,Wo as Line,td as Line3,Ro as LineBasicMaterial,Rh as LineCurve,Ph as LineCurve3,ql as LineDashedMaterial,Jo as LineLoop,qo as LineSegments,wt as LinearFilter,tc as LinearInterpolant,At as LinearMipMapLinearFilter,St as LinearMipMapNearestFilter,_t as LinearMipmapLinearFilter,Mt as LinearMipmapNearestFilter,Ze as LinearSRGBColorSpace,Q as LinearToneMapping,Ge as LinearTransfer,yc as Loader,Xc as LoaderUtils,pc as LoadingManager,ze as LoopOnce,Ce as LoopPingPong,Ie as LoopRepeat,e as MOUSE,sn as Material,Jc as MaterialLoader,Zi as MathUtils,Zu as Matrix2,es as Matrix3,or as Matrix4,_ as MaxEquation,Un as Mesh,rn as MeshBasicMaterial,Ul as MeshDepthMaterial,Dl as MeshDistanceMaterial,Wl as MeshLambertMaterial,Hl as MeshMatcapMaterial,jl as MeshNormalMaterial,Vl as MeshPhongMaterial,Fl as MeshPhysicalMaterial,Nl as MeshStandardMaterial,Ll as MeshToonMaterial,S as MinEquation,yt as MirroredRepeatWrapping,Z as MixOperation,x as MultiplyBlending,Y as MultiplyOperation,gt as NearestFilter,vt as NearestMipMapLinearFilter,xt as NearestMipMapNearestFilter,bt as NearestMipmapLinearFilter,ft as NearestMipmapNearestFilter,rt as NeutralToneMapping,mi as NeverCompare,j as NeverDepth,ai as NeverStencilFunc,m as NoBlending,Xe as NoColorSpace,$ as NoToneMapping,Ne as NormalAnimationBlendMode,y as NormalBlending,bi as NotEqualCompare,X as NotEqualDepth,ui as NotEqualStencilFunc,nc as NumberKeyframeTrack,Pr as Object3D,Gc as ObjectLoader,Je as ObjectSpaceNormalMap,Ml as OctahedronGeometry,T as OneFactor,L as OneMinusConstantAlphaFactor,F as OneMinusConstantColorFactor,E as OneMinusDstAlphaFactor,P as OneMinusDstColorFactor,B as OneMinusSrcAlphaFactor,I as OneMinusSrcColorFactor,Lc as OrthographicCamera,h as PCFShadowMap,l as PCFSoftShadowMap,jh as Path,ta as PerspectiveCamera,ao as Plane,Sl as PlaneGeometry,Td as PlaneHelper,Vc as PointLight,hd as PointLightHelper,Qo as Points,Xo as PointsMaterial,md as PolarGridHelper,dh as PolyhedronGeometry,Su as PositionalAudio,Eu as PropertyBinding,Au as PropertyMixer,Oh as QuadraticBezierCurve,Nh as QuadraticBezierCurve3,$i as Quaternion,oc as QuaternionKeyframeTrack,ac as QuaternionLinearInterpolant,Ui as RAD2DEG,Ae as RED_GREEN_RGTC2_Format,Se as RED_RGTC1_Format,t as REVISION,Ue as RGBADepthPacking,jt as RGBAFormat,Yt as RGBAIntegerFormat,fe as RGBA_ASTC_10x10_Format,me as RGBA_ASTC_10x5_Format,ye as RGBA_ASTC_10x6_Format,ge as RGBA_ASTC_10x8_Format,xe as RGBA_ASTC_12x10_Format,be as RGBA_ASTC_12x12_Format,ae as RGBA_ASTC_4x4_Format,oe as RGBA_ASTC_5x4_Format,he as RGBA_ASTC_5x5_Format,le as RGBA_ASTC_6x5_Format,ce as RGBA_ASTC_6x6_Format,ue as RGBA_ASTC_8x5_Format,de as RGBA_ASTC_8x6_Format,pe as RGBA_ASTC_8x8_Format,ve as RGBA_BPTC_Format,ne as RGBA_ETC2_EAC_Format,ie as RGBA_PVRTC_2BPPV1_Format,ee as RGBA_PVRTC_4BPPV1_Format,Gt as RGBA_S3TC_DXT1_Format,$t as RGBA_S3TC_DXT3_Format,Qt as RGBA_S3TC_DXT5_Format,De as RGBDepthPacking,Lt as RGBFormat,Xt as RGBIntegerFormat,we as RGB_BPTC_SIGNED_Format,Me as RGB_BPTC_UNSIGNED_Format,se as RGB_ETC1_Format,re as RGB_ETC2_Format,te as RGB_PVRTC_2BPPV1_Format,Kt as RGB_PVRTC_4BPPV1_Format,Zt as RGB_S3TC_DXT1_Format,He as RGDepthPacking,qt as RGFormat,Jt as RGIntegerFormat,Ol as RawShaderMaterial,ar as Ray,Hu as Raycaster,Dc as RectAreaLight,Dt as RedFormat,Ht as RedIntegerFormat,K as ReinhardToneMapping,Is as RenderTarget,Fu as RenderTarget3D,pt as RepeatWrapping,ti as ReplaceStencilOp,M as ReverseSubtractEquation,_l as RingGeometry,Te as SIGNED_RED_GREEN_RGTC2_Format,_e as SIGNED_RED_RGTC1_Format,Ye as SRGBColorSpace,$e as SRGBTransfer,ca as Scene,Zn as ShaderMaterial,Pl as ShadowMaterial,Wh as Shape,Al as ShapeGeometry,Ed as ShapePath,yl as ShapeUtils,It as ShortType,Xa as Skeleton,ad as SkeletonHelper,Ua as SkinnedMesh,Ms as Source,Qs as Sphere,Tl as SphereGeometry,Xu as Spherical,Hc as SphericalHarmonics3,Fh as SplineCurve,Rc as SpotLight,id as SpotLightHelper,Ia as Sprite,ma as SpriteMaterial,C as SrcAlphaFactor,O as SrcAlphaSaturateFactor,z as SrcColorFactor,Ii as StaticCopyUsage,Mi as StaticDrawUsage,Ai as StaticReadUsage,hu as StereoCamera,Bi as StreamCopyUsage,_i as StreamDrawUsage,zi as StreamReadUsage,hc as StringKeyframeTrack,w as SubtractEquation,f as SubtractiveBlending,i as TOUCH,qe as TangentSpaceNormalMap,zl as TetrahedronGeometry,Ts as Texture,Ac as TextureLoader,Od as TextureUtils,Oi as TimestampQuery,Il as TorusGeometry,Cl as TorusKnotGeometry,Yr as Triangle,je as TriangleFanDrawMode,Le as TriangleStripDrawMode,Ve as TrianglesDrawMode,Bl as TubeGeometry,ot as UVMapping,xn as Uint16BufferAttribute,vn as Uint32BufferAttribute,yn as Uint8BufferAttribute,gn as Uint8ClampedBufferAttribute,Vu as Uniform,ju as UniformsGroup,Yn as UniformsUtils,Tt as UnsignedByteType,Nt as UnsignedInt248Type,Ft as UnsignedInt5999Type,kt as UnsignedIntType,Pt as UnsignedShort4444Type,Ot as UnsignedShort5551Type,Ct as UnsignedShortType,c as VSMShadowMap,Gi as Vector2,Qi as Vector3,zs as Vector4,lc as VectorKeyframeTrack,eh as VideoFrameTexture,th as VideoTexture,Rs as WebGL3DRenderTarget,ks as WebGLArrayRenderTarget,Ri as WebGLCoordinateSystem,ra as WebGLCubeRenderTarget,Cs as WebGLRenderTarget,Pi as WebGPUCoordinateSystem,oa as WebXRController,kl as WireframeGeometry,Oe as WrapAroundEnding,Re as ZeroCurvatureEnding,A as ZeroFactor,Pe as ZeroSlopeEnding,Qe as ZeroStencilOp,ss as arrayNeedsUint32,qn as cloneUniforms,os as createCanvasElement,as as createElementNS,Pd as getByteLength,Xn as getUnlitUniformColorSpace,Jn as mergeUniforms,cs as probeAsync,us as toNormalizedProjectionMatrix,ds as toReversedProjectionMatrix,ls as warnOnce}; +const t="178dev",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=100,w=101,M=102,S=103,_=104,A=200,T=201,z=202,I=203,C=204,B=205,k=206,E=207,R=208,P=209,O=210,N=211,F=212,V=213,L=214,j=0,W=1,U=2,D=3,H=4,q=5,J=6,X=7,Y=0,Z=1,G=2,$=0,Q=1,K=2,tt=3,et=4,it=5,st=6,rt=7,nt="attached",at="detached",ot=300,ht=301,lt=302,ct=303,ut=304,dt=306,pt=1e3,mt=1001,yt=1002,gt=1003,ft=1004,xt=1004,bt=1005,vt=1005,wt=1006,Mt=1007,St=1007,_t=1008,At=1008,Tt=1009,zt=1010,It=1011,Ct=1012,Bt=1013,kt=1014,Et=1015,Rt=1016,Pt=1017,Ot=1018,Nt=1020,Ft=35902,Vt=1021,Lt=1022,jt=1023,Wt=1026,Ut=1027,Dt=1028,Ht=1029,qt=1030,Jt=1031,Xt=1032,Yt=1033,Zt=33776,Gt=33777,$t=33778,Qt=33779,Kt=35840,te=35841,ee=35842,ie=35843,se=36196,re=37492,ne=37496,ae=37808,oe=37809,he=37810,le=37811,ce=37812,ue=37813,de=37814,pe=37815,me=37816,ye=37817,ge=37818,fe=37819,xe=37820,be=37821,ve=36492,we=36494,Me=36495,Se=36283,_e=36284,Ae=36285,Te=36286,ze=2200,Ie=2201,Ce=2202,Be=2300,ke=2301,Ee=2302,Re=2400,Pe=2401,Oe=2402,Ne=2500,Fe=2501,Ve=0,Le=1,je=2,We=3200,Ue=3201,De=3202,He=3203,qe=0,Je=1,Xe="",Ye="srgb",Ze="srgb-linear",Ge="linear",$e="srgb",Qe=0,Ke=7680,ti=7681,ei=7682,ii=7683,si=34055,ri=34056,ni=5386,ai=512,oi=513,hi=514,li=515,ci=516,ui=517,di=518,pi=519,mi=512,yi=513,gi=514,fi=515,xi=516,bi=517,vi=518,wi=519,Mi=35044,Si=35048,_i=35040,Ai=35045,Ti=35049,zi=35041,Ii=35046,Ci=35050,Bi=35042,ki="100",Ei="300 es",Ri=2e3,Pi=2001,Oi={COMPUTE:"compute",RENDER:"render"},Ni={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Fi={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};class Vi{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]+Li[t>>16&255]+Li[t>>24&255]+"-"+Li[255&e]+Li[e>>8&255]+"-"+Li[e>>16&15|64]+Li[e>>24&255]+"-"+Li[63&i|128]+Li[i>>8&255]+"-"+Li[i>>16&255]+Li[i>>24&255]+Li[255&s]+Li[s>>8&255]+Li[s>>16&255]+Li[s>>24&255]).toLowerCase()}function Hi(t,e,i){return Math.max(e,Math.min(i,t))}function qi(t,e){return(t%e+e)%e}function Ji(t,e,i){return(1-i)*t+i*e}function Xi(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 Yi(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 Zi={DEG2RAD:Wi,RAD2DEG:Ui,generateUUID:Di,clamp:Hi,euclideanModulo:qi,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:Ji,damp:function(t,e,i,s){return Ji(t,e,1-Math.exp(-i*s))},pingpong:function(t,e=1){return e-Math.abs(qi(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&&(ji=t);let e=ji+=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*Wi},radToDeg:function(t){return t*Ui},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:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Yi,denormalize:Xi};class Gi{constructor(t=0,e=0){Gi.prototype.isVector2=!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=Hi(this.x,t.x,e.x),this.y=Hi(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=Hi(this.x,t,e),this.y=Hi(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hi(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(Hi(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 $i{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];const u=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(0===a)return t[e+0]=o,t[e+1]=h,t[e+2]=l,void(t[e+3]=c);if(1===a)return t[e+0]=u,t[e+1]=d,t[e+2]=p,void(t[e+3]=m);if(c!==m||o!==u||h!==d||l!==p){let t=1-a;const e=o*u+h*d+l*p+c*m,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const r=Math.sqrt(s),n=Math.atan2(r,e*i);t=Math.sin(t*n)/r,a=Math.sin(a*n)/r}const r=a*i;if(o=o*t+u*r,h=h*t+d*r,l=l*t+p*r,c=c*t+m*r,t===1-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:console.warn("THREE.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 iMath.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(Hi(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){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,r=this._z,n=this._w;let a=n*t._w+i*t._x+s*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=n,this._x=i,this._y=s,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*n+e*this._w,this._x=t*i+e*this._x,this._y=t*s+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const h=Math.sqrt(o),l=Math.atan2(h,a),c=Math.sin((1-e)*l)/h,u=Math.sin(e*l)/h;return this._w=n*c+this._w*u,this._x=i*c+this._x*u,this._y=s*c+this._y*u,this._z=r*c+this._z*u,this._onChangeCallback(),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 Qi{constructor(t=0,e=0,i=0){Qi.prototype.isVector3=!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(ts.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ts.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=Hi(this.x,t.x,e.x),this.y=Hi(this.y,t.y,e.y),this.z=Hi(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=Hi(this.x,t,e),this.y=Hi(this.y,t,e),this.z=Hi(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hi(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 Ki.copy(this).projectOnVector(t),this.sub(Ki)}reflect(t){return this.sub(Ki.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(Hi(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 Ki=new Qi,ts=new $i;class es{constructor(t,e,i,s,r,n,a,o,h){es.prototype.isMatrix3=!0,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(is.makeScale(t,e)),this}rotate(t){return this.premultiply(is.makeRotation(-t)),this}translate(t,e){return this.premultiply(is.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 is=new es;function ss(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const rs={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function ns(t,e){return new rs[t](e)}function as(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function os(){const t=as("canvas");return t.style.display="block",t}const hs={};function ls(t){t in hs||(hs[t]=!0,console.warn(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)}))}function us(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function ds(t){const e=t.elements;-1===e[11]?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=1-e[14])}const ps=(new es).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ms=(new es).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ys(){const t={enabled:!0,workingColorSpace:Ze,spaces:{},convert:function(t,e,i){return!1!==this.enabled&&e!==i&&e&&i?(this.spaces[e].transfer===$e&&(t.r=fs(t.r),t.g=fs(t.g),t.b=fs(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===$e&&(t.r=xs(t.r),t.g=xs(t.g),t.b=xs(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?Ge:this.spaces[t].transfer},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 ls("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(e,i)},toWorkingColorSpace:function(e,i){return ls("THREE.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({[Ze]:{primaries:e,whitePoint:s,transfer:Ge,toXYZ:ps,fromXYZ:ms,luminanceCoefficients:i,workingColorSpaceConfig:{unpackColorSpace:Ye},outputColorSpaceConfig:{drawingBufferColorSpace:Ye}},[Ye]:{primaries:e,whitePoint:s,transfer:$e,toXYZ:ps,fromXYZ:ms,luminanceCoefficients:i,outputColorSpaceConfig:{drawingBufferColorSpace:Ye}}}),t}const gs=ys();function fs(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function xs(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let bs;class vs{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===bs&&(bs=as("canvas")),bs.width=t.width,bs.height=t.height;const e=bs.getContext("2d");t instanceof ImageData?e.putImageData(t,0,0):e.drawImage(t,0,0,t.width,t.height),i=bs}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=as("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}get width(){return this.source.getSize(As).x}get height(){return this.source.getSize(As).y}get depth(){return this.source.getSize(As).z}get image(){return this.source.data}set image(t=null){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.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){console.warn(`THREE.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:console.warn(`THREE.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,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!==ot)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case pt:t.x=t.x-Math.floor(t.x);break;case mt:t.x=t.x<0?0:1;break;case yt: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 pt:t.y=t.y-Math.floor(t.y);break;case mt:t.y=t.y<0?0:1;break;case yt: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++}}Ts.DEFAULT_IMAGE=null,Ts.DEFAULT_MAPPING=ot,Ts.DEFAULT_ANISOTROPY=1;class zs{constructor(t=0,e=0,i=0,s=1){zs.prototype.isVector4=!0,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=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,Ns),Ns.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(Hs),qs.subVectors(this.max,Hs),Vs.subVectors(t.a,Hs),Ls.subVectors(t.b,Hs),js.subVectors(t.c,Hs),Ws.subVectors(Ls,Vs),Us.subVectors(js,Ls),Ds.subVectors(Vs,js);let e=[0,-Ws.z,Ws.y,0,-Us.z,Us.y,0,-Ds.z,Ds.y,Ws.z,0,-Ws.x,Us.z,0,-Us.x,Ds.z,0,-Ds.x,-Ws.y,Ws.x,0,-Us.y,Us.x,0,-Ds.y,Ds.x,0];return!!Ys(e,Vs,Ls,js,qs)&&(e=[1,0,0,0,1,0,0,0,1],!!Ys(e,Vs,Ls,js,qs)&&(Js.crossVectors(Ws,Us),e=[Js.x,Js.y,Js.z],Ys(e,Vs,Ls,js,qs)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Ns).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(Ns).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()||(Os[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Os[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Os[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Os[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Os[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Os[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Os[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Os[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Os)),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 Os=[new Qi,new Qi,new Qi,new Qi,new Qi,new Qi,new Qi,new Qi],Ns=new Qi,Fs=new Ps,Vs=new Qi,Ls=new Qi,js=new Qi,Ws=new Qi,Us=new Qi,Ds=new Qi,Hs=new Qi,qs=new Qi,Js=new Qi,Xs=new Qi;function Ys(t,e,i,s,r){for(let n=0,a=t.length-3;n<=a;n+=3){Xs.fromArray(t,n);const a=r.x*Math.abs(Xs.x)+r.y*Math.abs(Xs.y)+r.z*Math.abs(Xs.z),o=e.dot(Xs),h=i.dot(Xs),l=s.dot(Xs);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const Zs=new Ps,Gs=new Qi,$s=new Qi;class Qs{constructor(t=new Qi,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;void 0!==e?i.copy(e):Zs.setFromPoints(t).getCenter(i);let s=0;for(let e=0,r=t.length;ethis.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;Gs.subVectors(t,this.center);const e=Gs.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(Gs,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):($s.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Gs.copy(t.center).add($s)),this.expandByPoint(Gs.copy(t.center).sub($s))),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}}const Ks=new Qi,tr=new Qi,er=new Qi,ir=new Qi,sr=new Qi,rr=new Qi,nr=new Qi;class ar{constructor(t=new Qi,e=new Qi(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Ks)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Ks.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Ks.copy(this.origin).addScaledVector(this.direction,e),Ks.distanceToSquared(t))}distanceSqToSegment(t,e,i,s){tr.copy(t).add(e).multiplyScalar(.5),er.copy(e).sub(t).normalize(),ir.copy(this.origin).sub(tr);const r=.5*t.distanceTo(e),n=-this.direction.dot(er),a=ir.dot(this.direction),o=-ir.dot(er),h=ir.lengthSq(),l=Math.abs(1-n*n);let c,u,d,p;if(l>0)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(tr).addScaledVector(er,u),d}intersectSphere(t,e){Ks.subVectors(t.center,this.origin);const i=Ks.dot(this.direction),s=Ks.dot(Ks)-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,Ks)}intersectTriangle(t,e,i,s,r){sr.subVectors(e,t),rr.subVectors(i,t),nr.crossVectors(sr,rr);let n,a=this.direction.dot(nr);if(a>0){if(s)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}ir.subVectors(this.origin,t);const o=n*this.direction.dot(rr.crossVectors(ir,rr));if(o<0)return null;const h=n*this.direction.dot(sr.cross(ir));if(h<0)return null;if(o+h>a)return null;const l=-n*ir.dot(nr);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 or{constructor(t,e,i,s,r,n,a,o,h,l,c,u,d,p,m,y){or.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,i,s,r,n,a,o,h,l,c,u,d,p,m,y)}set(t,e,i,s,r,n,a,o,h,l,c,u,d,p,m,y){const g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=s,g[1]=r,g[5]=n,g[9]=a,g[13]=o,g[2]=h,g[6]=l,g[10]=c,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new or).fromArray(this.elements)}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],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/hr.setFromMatrixColumn(t,0).length(),r=1/hr.setFromMatrixColumn(t,1).length(),n=1/hr.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*r,e[5]=i[5]*r,e[6]=i[6]*r,e[7]=0,e[8]=i[8]*n,e[9]=i[9]*n,e[10]=i[10]*n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,n=Math.cos(i),a=Math.sin(i),o=Math.cos(s),h=Math.sin(s),l=Math.cos(r),c=Math.sin(r);if("XYZ"===t.order){const t=n*l,i=n*c,s=a*l,r=a*c;e[0]=o*l,e[4]=-o*c,e[8]=h,e[1]=i+s*h,e[5]=t-r*h,e[9]=-a*o,e[2]=r-t*h,e[6]=s+i*h,e[10]=n*o}else if("YXZ"===t.order){const t=o*l,i=o*c,s=h*l,r=h*c;e[0]=t+r*a,e[4]=s*a-i,e[8]=n*h,e[1]=n*c,e[5]=n*l,e[9]=-a,e[2]=i*a-s,e[6]=r+t*a,e[10]=n*o}else if("ZXY"===t.order){const t=o*l,i=o*c,s=h*l,r=h*c;e[0]=t-r*a,e[4]=-n*c,e[8]=s+i*a,e[1]=i+s*a,e[5]=n*l,e[9]=r-t*a,e[2]=-n*h,e[6]=a,e[10]=n*o}else if("ZYX"===t.order){const t=n*l,i=n*c,s=a*l,r=a*c;e[0]=o*l,e[4]=s*h-i,e[8]=t*h+r,e[1]=o*c,e[5]=r*h+t,e[9]=i*h-s,e[2]=-h,e[6]=a*o,e[10]=n*o}else if("YZX"===t.order){const t=n*o,i=n*h,s=a*o,r=a*h;e[0]=o*l,e[4]=r-t*c,e[8]=s*c+i,e[1]=c,e[5]=n*l,e[9]=-a*l,e[2]=-h*l,e[6]=i*c+s,e[10]=t-r*c}else if("XZY"===t.order){const t=n*o,i=n*h,s=a*o,r=a*h;e[0]=o*l,e[4]=-c,e[8]=h*l,e[1]=t*c+r,e[5]=n*l,e[9]=i*c-s,e[2]=s*c-i,e[6]=a*l,e[10]=r*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(cr,t,ur)}lookAt(t,e,i){const s=this.elements;return mr.subVectors(t,e),0===mr.lengthSq()&&(mr.z=1),mr.normalize(),dr.crossVectors(i,mr),0===dr.lengthSq()&&(1===Math.abs(i.z)?mr.x+=1e-4:mr.z+=1e-4,mr.normalize(),dr.crossVectors(i,mr)),dr.normalize(),pr.crossVectors(mr,dr),s[0]=dr.x,s[4]=pr.x,s[8]=mr.x,s[1]=dr.y,s[5]=pr.y,s[9]=mr.y,s[2]=dr.z,s[6]=pr.z,s[10]=mr.z,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[4],o=i[8],h=i[12],l=i[1],c=i[5],u=i[9],d=i[13],p=i[2],m=i[6],y=i[10],g=i[14],f=i[3],x=i[7],b=i[11],v=i[15],w=s[0],M=s[4],S=s[8],_=s[12],A=s[1],T=s[5],z=s[9],I=s[13],C=s[2],B=s[6],k=s[10],E=s[14],R=s[3],P=s[7],O=s[11],N=s[15];return r[0]=n*w+a*A+o*C+h*R,r[4]=n*M+a*T+o*B+h*P,r[8]=n*S+a*z+o*k+h*O,r[12]=n*_+a*I+o*E+h*N,r[1]=l*w+c*A+u*C+d*R,r[5]=l*M+c*T+u*B+d*P,r[9]=l*S+c*z+u*k+d*O,r[13]=l*_+c*I+u*E+d*N,r[2]=p*w+m*A+y*C+g*R,r[6]=p*M+m*T+y*B+g*P,r[10]=p*S+m*z+y*k+g*O,r[14]=p*_+m*I+y*E+g*N,r[3]=f*w+x*A+b*C+v*R,r[7]=f*M+x*T+b*B+v*P,r[11]=f*S+x*z+b*k+v*O,r[15]=f*_+x*I+b*E+v*N,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],r=t[12],n=t[1],a=t[5],o=t[9],h=t[13],l=t[2],c=t[6],u=t[10],d=t[14];return t[3]*(+r*o*c-s*h*c-r*a*u+i*h*u+s*a*d-i*o*d)+t[7]*(+e*o*d-e*h*u+r*n*u-s*n*d+s*h*l-r*o*l)+t[11]*(+e*h*c-e*a*d-r*n*c+i*n*d+r*a*l-i*h*l)+t[15]*(-s*a*l-e*o*c+e*a*u+s*n*c-i*n*u+i*o*l)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}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=t[9],u=t[10],d=t[11],p=t[12],m=t[13],y=t[14],g=t[15],f=c*y*h-m*u*h+m*o*d-a*y*d-c*o*g+a*u*g,x=p*u*h-l*y*h-p*o*d+n*y*d+l*o*g-n*u*g,b=l*m*h-p*c*h+p*a*d-n*m*d-l*a*g+n*c*g,v=p*c*o-l*m*o-p*a*u+n*m*u+l*a*y-n*c*y,w=e*f+i*x+s*b+r*v;if(0===w)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/w;return t[0]=f*M,t[1]=(m*u*r-c*y*r-m*s*d+i*y*d+c*s*g-i*u*g)*M,t[2]=(a*y*r-m*o*r+m*s*h-i*y*h-a*s*g+i*o*g)*M,t[3]=(c*o*r-a*u*r-c*s*h+i*u*h+a*s*d-i*o*d)*M,t[4]=x*M,t[5]=(l*y*r-p*u*r+p*s*d-e*y*d-l*s*g+e*u*g)*M,t[6]=(p*o*r-n*y*r-p*s*h+e*y*h+n*s*g-e*o*g)*M,t[7]=(n*u*r-l*o*r+l*s*h-e*u*h-n*s*d+e*o*d)*M,t[8]=b*M,t[9]=(p*c*r-l*m*r-p*i*d+e*m*d+l*i*g-e*c*g)*M,t[10]=(n*m*r-p*a*r+p*i*h-e*m*h-n*i*g+e*a*g)*M,t[11]=(l*a*r-n*c*r-l*i*h+e*c*h+n*i*d-e*a*d)*M,t[12]=v*M,t[13]=(l*m*s-p*c*s+p*i*u-e*m*u-l*i*y+e*c*y)*M,t[14]=(p*a*s-n*m*s-p*i*o+e*m*o+n*i*y-e*a*y)*M,t[15]=(n*c*s-l*a*s+l*i*o-e*c*o-n*i*u+e*a*u)*M,this}scale(t){const e=this.elements,i=t.x,s=t.y,r=t.z;return e[0]*=i,e[4]*=s,e[8]*=r,e[1]*=i,e[5]*=s,e[9]*=r,e[2]*=i,e[6]*=s,e[10]*=r,e[3]*=i,e[7]*=s,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),r=1-i,n=t.x,a=t.y,o=t.z,h=r*n,l=r*a;return this.set(h*n+i,h*a-s*o,h*o+s*a,0,h*a+s*o,l*a+i,l*o-s*n,0,h*o-s*a,l*o+s*n,r*o*o+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,r,n){return this.set(1,i,r,0,t,1,n,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,r=e._x,n=e._y,a=e._z,o=e._w,h=r+r,l=n+n,c=a+a,u=r*h,d=r*l,p=r*c,m=n*l,y=n*c,g=a*c,f=o*h,x=o*l,b=o*c,v=i.x,w=i.y,M=i.z;return s[0]=(1-(m+g))*v,s[1]=(d+b)*v,s[2]=(p-x)*v,s[3]=0,s[4]=(d-b)*w,s[5]=(1-(u+g))*w,s[6]=(y+f)*w,s[7]=0,s[8]=(p+x)*M,s[9]=(y-f)*M,s[10]=(1-(u+m))*M,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let r=hr.set(s[0],s[1],s[2]).length();const n=hr.set(s[4],s[5],s[6]).length(),a=hr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),t.x=s[12],t.y=s[13],t.z=s[14],lr.copy(this);const o=1/r,h=1/n,l=1/a;return lr.elements[0]*=o,lr.elements[1]*=o,lr.elements[2]*=o,lr.elements[4]*=h,lr.elements[5]*=h,lr.elements[6]*=h,lr.elements[8]*=l,lr.elements[9]*=l,lr.elements[10]*=l,e.setFromRotationMatrix(lr),i.x=r,i.y=n,i.z=a,this}makePerspective(t,e,i,s,r,n,a=2e3){const o=this.elements,h=2*r/(e-t),l=2*r/(i-s),c=(e+t)/(e-t),u=(i+s)/(i-s);let d,p;if(a===Ri)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(a!==Pi)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-n/(n-r),p=-n*r/(n-r)}return o[0]=h,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=l,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,i,s,r,n,a=2e3){const o=this.elements,h=1/(e-t),l=1/(i-s),c=1/(n-r),u=(e+t)*h,d=(i+s)*l;let p,m;if(a===Ri)p=(n+r)*c,m=-2*c;else{if(a!==Pi)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*c,m=-1*c}return o[0]=2*h,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*l,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;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[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const hr=new Qi,lr=new or,cr=new Qi(0,0,0),ur=new Qi(1,1,1),dr=new Qi,pr=new Qi,mr=new Qi,yr=new or,gr=new $i;class fr{constructor(t=0,e=0,i=0,s=fr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}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 order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,r=s[0],n=s[4],a=s[8],o=s[1],h=s[5],l=s[9],c=s[2],u=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(Hi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(u,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Hi(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,h)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(Hi(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Hi(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Hi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Hi(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(u,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return yr.makeRotationFromQuaternion(t),this.setFromRotationMatrix(yr,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return gr.setFromEuler(this),this.setFromQuaternion(gr,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[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._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}fr.DEFAULT_ORDER="XYZ";class xr{constructor(){this.mask=1}set(t){this.mask=1<>>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(),!1===this.matrixAutoUpdate&&(s.matrixAutoUpdate=!1),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.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.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,i,s,r){Or.subVectors(s,e),Nr.subVectors(i,e),Fr.subVectors(t,e);const n=Or.dot(Or),a=Or.dot(Nr),o=Or.dot(Fr),h=Nr.dot(Nr),l=Nr.dot(Fr),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,Vr)&&(Vr.x>=0&&Vr.y>=0&&Vr.x+Vr.y<=1)}static getInterpolation(t,e,i,s,r,n,a,o){return null===this.getBarycoord(t,e,i,s,Vr)?(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,Vr.x),o.addScaledVector(n,Vr.y),o.addScaledVector(a,Vr.z),o)}static getInterpolatedAttribute(t,e,i,s,r,n){return qr.setScalar(0),Jr.setScalar(0),Xr.setScalar(0),qr.fromBufferAttribute(t,e),Jr.fromBufferAttribute(t,i),Xr.fromBufferAttribute(t,s),n.setScalar(0),n.addScaledVector(qr,r.x),n.addScaledVector(Jr,r.y),n.addScaledVector(Xr,r.z),n}static isFrontFacing(t,e,i,s){return Or.subVectors(i,e),Nr.subVectors(t,e),Or.cross(Nr).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 Or.subVectors(this.c,this.b),Nr.subVectors(this.a,this.b),.5*Or.cross(Nr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Yr.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Yr.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,s,r){return Yr.getInterpolation(t,this.a,this.b,this.c,e,i,s,r)}containsPoint(t){return Yr.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Yr.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;Lr.subVectors(s,i),jr.subVectors(r,i),Ur.subVectors(t,i);const o=Lr.dot(Ur),h=jr.dot(Ur);if(o<=0&&h<=0)return e.copy(i);Dr.subVectors(t,s);const l=Lr.dot(Dr),c=jr.dot(Dr);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(Lr,n);Hr.subVectors(t,r);const d=Lr.dot(Hr),p=jr.dot(Hr);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(jr,a);const y=l*p-d*c;if(y<=0&&c-l>=0&&d-p>=0)return Wr.subVectors(r,s),a=(c-l)/(c-l+(d-p)),e.copy(s).addScaledVector(Wr,a);const g=1/(y+m+u);return n=m*g,a=u*g,e.copy(i).addScaledVector(Lr,n).addScaledVector(jr,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Zr={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},Gr={h:0,s:0,l:0},$r={h:0,s:0,l:0};function Qr(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 Kr{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=Ye){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,gs.colorSpaceToWorking(this,e),this}setRGB(t,e,i,s=gs.workingColorSpace){return this.r=t,this.g=e,this.b=i,gs.colorSpaceToWorking(this,s),this}setHSL(t,e,i,s=gs.workingColorSpace){if(t=qi(t,1),e=Hi(e,0,1),i=Hi(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=Qr(r,s,t+1/3),this.g=Qr(r,s,t),this.b=Qr(r,s,t-1/3)}return gs.colorSpaceToWorking(this,s),this}setStyle(t,e=Ye){function i(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.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:console.warn("THREE.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);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ye){const i=Zr[t.toLowerCase()];return void 0!==i?this.setHex(i,e):console.warn("THREE.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=fs(t.r),this.g=fs(t.g),this.b=fs(t.b),this}copyLinearToSRGB(t){return this.r=xs(t.r),this.g=xs(t.g),this.b=xs(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ye){return gs.workingToColorSpace(tn.copy(this),t),65536*Math.round(Hi(255*tn.r,0,255))+256*Math.round(Hi(255*tn.g,0,255))+Math.round(Hi(255*tn.b,0,255))}getHexString(t=Ye){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=gs.workingColorSpace){gs.workingToColorSpace(tn.copy(this),e);const i=tn.r,s=tn.g,r=tn.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!=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){console.warn(`THREE.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:console.warn(`THREE.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()),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!==Ke&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ke&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ke&&(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),!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.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 rn extends sn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Kr(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 fr,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 nn=an();function an(){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 on(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=Hi(t,-65504,65504),nn.floatView[0]=t;const e=nn.uint32View[0],i=e>>23&511;return nn.baseTable[i]+((8388607&e)>>nn.shiftTable[i])}function hn(t){const e=t>>10;return nn.uint32View[0]=nn.mantissaTable[nn.offsetTable[e]+(1023&t)]+nn.exponentTable[e],nn.floatView[0]}class ln{static toHalfFloat(t){return on(t)}static fromHalfFloat(t){return hn(t)}}const cn=new Qi,un=new Gi;let dn=0;class pn{constructor(t,e,i=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:dn++}),this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=Mi,this.updateRanges=[],this.gpuType=Et,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;se.count&&console.warn("THREE.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 Ps);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Qi(-1/0,-1/0,-1/0),new Qi(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){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}kn.copy(r).invert(),En.copy(t.ray).applyMatrix4(kn),null!==i.boundingBox&&!1===En.intersectsBox(i.boundingBox)||this._computeIntersections(t,e,En)}}_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:Wn.clone(),object:t}}(t,e,i,s,On,Nn,Fn,jn);if(c){const t=new Qi;Yr.getBarycoord(jn,On,Nn,Fn,t),r&&(c.uv=Yr.getInterpolatedAttribute(r,o,h,l,t,new Gi)),n&&(c.uv1=Yr.getInterpolatedAttribute(n,o,h,l,t,new Gi)),a&&(c.normal=Yr.getInterpolatedAttribute(a,o,h,l,t,new Qi),c.normal.dot(s.direction)>0&&c.normal.multiplyScalar(-1));const e={a:o,b:h,c:l,normal:new Qi,materialIndex:0};Yr.getNormal(On,Nn,Fn,e.normal),c.face=e,c.barycoord=t}return c}class Hn extends Bn{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 Qi;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&&(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 Gn extends Pr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new or,this.projectionMatrix=new or,this.projectionMatrixInverse=new or,this.coordinateSystem=Ri}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const $n=new Qi,Qn=new Gi,Kn=new Gi;class ta extends Gn{constructor(t=50,e=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Ui*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Wi*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Ui*Math.atan(Math.tan(.5*Wi*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,i){$n.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set($n.x,$n.y).multiplyScalar(-t/$n.z),$n.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set($n.x,$n.y).multiplyScalar(-t/$n.z)}getViewSize(t,e){return this.getViewBounds(t,Qn,Kn),e.subVectors(Kn,Qn)}setViewOffset(t,e,i,s,r,n){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=s,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*Wi*this.fov)/this.zoom,i=2*e,s=this.aspect*i,r=-.5*s;const n=this.view;if(null!==this.view&&this.view.enabled){const t=n.fullWidth,a=n.fullHeight;r+=n.offsetX*s/t,e-=n.offsetY*i/a,s*=n.width/t,i*=n.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,e,e-i,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const ea=-90;class ia extends Pr{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new ta(ea,1,t,e);s.layers=this.layers,this.add(s);const r=new ta(ea,1,t,e);r.layers=this.layers,this.add(r);const n=new ta(ea,1,t,e);n.layers=this.layers,this.add(n);const a=new ta(ea,1,t,e);a.layers=this.layers,this.add(a);const o=new ta(ea,1,t,e);o.layers=this.layers,this.add(o);const h=new ta(ea,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===Ri)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!==Pi)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,t.setRenderTarget(i,0,s),t.render(e,r),t.setRenderTarget(i,1,s),t.render(e,n),t.setRenderTarget(i,2,s),t.render(e,a),t.setRenderTarget(i,3,s),t.render(e,o),t.setRenderTarget(i,4,s),t.render(e,h),i.texture.generateMipmaps=m,t.setRenderTarget(i,5,s),t.render(e,l),t.setRenderTarget(c,u,d),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class sa extends Ts{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 ra extends Cs{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const i={width:t,height:t,depth:1},s=[i,i,i,i,i,i];this.texture=new sa(s),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},s=new Hn(5,5,5),r=new Zn({name:"CubemapFromEquirect",uniforms:qn(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const n=new Un(s,r),a=e.minFilter;e.minFilter===_t&&(e.minFilter=wt);return new ia(1,10,this).update(t,n),e.minFilter=a,n.geometry.dispose(),n.material.dispose(),this}clear(t,e=!0,i=!0,s=!0){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,i,s);t.setRenderTarget(r)}}class na extends Pr{constructor(){super(),this.isGroup=!0,this.type="Group"}}const aa={type:"move"};class oa{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new na,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new na,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Qi,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Qi),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new na,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Qi,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Qi),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,i){let s=null,r=null,n=null;const a=this._targetRay,o=this._grip,h=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState){if(h&&t.hand){n=!0;for(const s of t.hand.values()){const t=e.getJointPose(s,i),r=this._getHandJoint(h,s);null!==t&&(r.matrix.fromArray(t.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=t.radius),r.visible=null!==t}const s=h.joints["index-finger-tip"],r=h.joints["thumb-tip"],a=s.position.distanceTo(r.position),o=.02,l=.005;h.inputState.pinching&&a>o+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));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(aa)))}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 na;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}class ha{constructor(t,e=25e-5){this.isFogExp2=!0,this.name="",this.color=new Kr(t),this.density=e}clone(){return new ha(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class la{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new Kr(t),this.near=e,this.far=i}clone(){return new la(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class ca extends Pr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new fr,this.environmentIntensity=1,this.environmentRotation=new fr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(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}}class ua{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=Mi,this.updateRanges=[],this.version=0,this.uuid=Di()}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.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let s=0,r=this.stride;st.far||e.push({distance:o,point:ga.clone(),uv:Yr.getInterpolation(ga,Ma,Sa,_a,Aa,Ta,za,new Gi),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){ba.subVectors(t,i).addScalar(.5).multiply(s),void 0!==r?(va.x=n*ba.x-r*ba.y,va.y=r*ba.x+n*ba.y):va.copy(ba),t.copy(e),t.x+=va.x,t.y+=va.y,t.applyMatrix4(wa)}const Ba=new Qi,ka=new Qi;class Ea extends Pr{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){Ba.setFromMatrixPosition(this.matrixWorld);const i=t.ray.origin.distanceTo(Ba);this.getObjectForDistance(i).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){Ba.setFromMatrixPosition(t.matrixWorld),ka.setFromMatrixPosition(this.matrixWorld);const i=Ba.distanceTo(ka)/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;s1?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||no.getNormalMatrix(t),s=this.coplanarPoint(so).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 oo=new Qs,ho=new Qi;class lo{constructor(t=new ao,e=new ao,i=new ao,s=new ao,r=new ao,n=new ao){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){const i=this.planes,s=t.elements,r=s[0],n=s[1],a=s[2],o=s[3],h=s[4],l=s[5],c=s[6],u=s[7],d=s[8],p=s[9],m=s[10],y=s[11],g=s[12],f=s[13],x=s[14],b=s[15];if(i[0].setComponents(o-r,u-h,y-d,b-g).normalize(),i[1].setComponents(o+r,u+h,y+d,b+g).normalize(),i[2].setComponents(o+n,u+l,y+p,b+f).normalize(),i[3].setComponents(o-n,u-l,y-p,b-f).normalize(),i[4].setComponents(o-a,u-c,y-m,b-x).normalize(),e===Ri)i[5].setComponents(o+a,u+c,y+m,b+x).normalize();else{if(e!==Pi)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);i[5].setComponents(a,c,m,x).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),oo.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),oo.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(oo)}intersectsSprite(t){return oo.center.set(0,0,0),oo.radius=.7071067811865476,oo.applyMatrix4(t.matrixWorld),this.intersectsSphere(oo)}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,ho.y=s.normal.y>0?t.max.y:t.min.y,ho.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(ho)<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 co=new or,uo=new lo;class po{constructor(){this.coordinateSystem=Ri}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 xo=new or,bo=new Kr(1,1,1),vo=new lo,wo=new po,Mo=new Ps,So=new Qs,_o=new Qi,Ao=new Qi,To=new Qi,zo=new fo,Io=new Un,Co=[];function Bo(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 pn(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 Ps);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(mo),i=this._availableInstanceIds.shift(),this._instanceInfo[i]=e):(i=this._instanceInfo.length,this._instanceInfo.push(e));const s=this._matricesTexture;xo.identity().toArray(s.image.data,16*i),s.needsUpdate=!0;const r=this._colorsTexture;return r&&(bo.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(mo),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);Bo(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 Ps,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 Qs;this.getBoundingBoxAt(t,Mo),Mo.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 Bn,this._initializeGeometry(s));const r=this.geometry;s.index&&ko(s.index.array,r.index.array);for(const t in s.attributes)ko(s.attributes[t].array,r.attributes[t].array)}raycast(t,e){const i=this._instanceInfo,s=this._geometryInfo,r=this.matrixWorld,n=this.geometry;Io.material=this.material,Io.geometry.index=n.index,Io.geometry.attributes=n.attributes,null===Io.geometry.boundingBox&&(Io.geometry.boundingBox=new Ps),null===Io.geometry.boundingSphere&&(Io.geometry.boundingSphere=new Qs);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(),a=null===n?1:n.array.BYTES_PER_ELEMENT,o=this._instanceInfo,h=this._multiDrawStarts,l=this._multiDrawCounts,c=this._geometryInfo,u=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data,m=i.isArrayCamera?wo:vo;u&&!i.isArrayCamera&&(xo.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),vo.setFromProjectionMatrix(xo,t.coordinateSystem));let y=0;if(this.sortObjects){xo.copy(this.matrixWorld).invert(),_o.setFromMatrixPosition(i.matrixWorld).applyMatrix4(xo),Ao.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(xo);for(let t=0,e=o.length;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;ts)return;Lo.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(Lo);return he.far?void 0:{distance:h,point:jo.clone().applyMatrix4(t.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:t}}const Do=new Qi,Ho=new Qi;class qo extends Wo{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 th extends Ts{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;const l=this;"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback((function e(){l.needsUpdate=!0,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)}}class eh extends th{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 ih extends Ts{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=gt,this.minFilter=gt,this.generateMipmaps=!1,this.needsUpdate=!0}}class sh extends Ts{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 rh extends sh{constructor(t,e,i,s,r,n){super(t,e,i,r,n),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=mt,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class nh extends sh{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,ht),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class ah extends Ts{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 oh extends Ts{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 Ms(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 hh extends Bn{constructor(t=1,e=1,i=4,s=8,r=1){super(),this.type="CapsuleGeometry",this.parameters={radius:t,height:e,capSegments:i,radialSegments:s,heightSegments:r},e=Math.max(0,e),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),r=Math.max(1,Math.floor(r));const n=[],a=[],o=[],h=[],l=e/2,c=Math.PI/2*t,u=e,d=2*c+u,p=2*i+r,m=s+1,y=new Qi,g=new Qi;for(let f=0;f<=p;f++){let x=0,b=0,v=0,w=0;if(f<=i){const e=f/i,s=e*Math.PI/2;b=-l-t*Math.cos(s),v=t*Math.sin(s),w=-t*Math.cos(s),x=e*c}else if(f<=i+r){const s=(f-i)/r;b=s*e-l,v=t,w=0,x=c+s*u}else{const e=(f-i-r)/i,s=e*Math.PI/2;b=l+t*Math.sin(s),v=t*Math.cos(s),w=t*Math.sin(s),x=c+u+e*c}const M=Math.max(0,Math.min(1,x/d));let S=0;0===f?S=.5/s:f===p&&(S=-.5/s);for(let t=0;t<=s;t++){const e=t/s,i=e*Math.PI*2,r=Math.sin(i),n=Math.cos(i);g.x=-v*n,g.y=b,g.z=v*r,a.push(g.x,g.y,g.z),y.set(-v*n,w,v*r),y.normalize(),o.push(y.x,y.y,y.z),h.push(e+S,M)}if(f>0){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 Mn(c,3)),this.setAttribute("normal",new Mn(u,3)),this.setAttribute("uv",new Mn(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ch(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class uh extends ch{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 uh(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class dh extends Bn{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 Mn(r,3)),this.setAttribute("normal",new Mn(r.slice(),3)),this.setAttribute("uv",new Mn(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 dh(t.vertices,t.indices,t.radius,t.details)}}class ph extends dh{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 ph(t.radius,t.detail)}}const mh=new Qi,yh=new Qi,gh=new Qi,fh=new Yr;class xh extends Bn{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(Wi*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 Gi:new Qi);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 Qi,s=[],r=[],n=[],a=new Qi,o=new or;for(let e=0;e<=t;e++){const i=e/t;s[e]=this.getTangentAt(i,new Qi)}r[0]=new Qi,n[0]=new Qi;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(Hi(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(Hi(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 vh extends bh{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 Gi){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]:(Sh.subVectors(s[0],s[1]).add(s[0]),a=Sh);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(Ih(a,o.x,h.x,l.x,c.x),Ih(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 Wh extends jh{constructor(t){super(t),this.uuid=Di(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,s=this.holes.length;i80*i){o=1/0,h=1/0;let e=-1/0,s=-1/0;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 qh(n,a,i,o,h,l,0),a}function Dh(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=ul(r/s|0,t[r],t[r+1],n);return n&&nl(n,n.next)&&(dl(n),n=n.next),n}function Hh(t,e){if(!t)return t;e||(e=t);let i,s=t;do{if(i=!1,s.steiner||!nl(s,s.next)&&0!==rl(s.prev,s,s.next))s=s.next;else{if(dl(s),s=e=s.prev,s===s.next)break;i=!0}}while(i||s!==e);return e}function qh(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=Kh(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?Xh(t,s,r,n):Jh(t))e.push(h.i,t.i,l.i),dl(t),t=l.next,o=l.next;else if((t=l)===o){a?1===a?qh(t=Yh(Hh(t),e),e,i,s,r,n,2):2===a&&Zh(t,e,i,s,r,n):qh(Hh(t),e,i,s,r,n,1);break}}}function Jh(t){const e=t.prev,i=t,s=t.next;if(rl(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&&il(r,o,n,h,a,l,m.x,m.y)&&rl(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Xh(t,e,i,s){const r=t.prev,n=t,a=t.next;if(rl(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=Kh(p,m,e,i,s),x=Kh(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&&il(o,c,h,u,l,d,b.x,b.y)&&rl(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&&il(o,c,h,u,l,d,v.x,v.y)&&rl(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&&il(o,c,h,u,l,d,b.x,b.y)&&rl(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&&il(o,c,h,u,l,d,v.x,v.y)&&rl(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Yh(t,e){let i=t;do{const s=i.prev,r=i.next.next;!nl(s,r)&&al(s,i,i.next,r)&&ll(s,r)&&ll(r,s)&&(e.push(s.i,i.i,r.i),dl(i),dl(i.next),i=t=r),i=i.next}while(i!==t);return Hh(i)}function Zh(t,e,i,s,r,n){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&sl(a,t)){let o=cl(a,t);return a=Hh(a,a.next),o=Hh(o,o.next),qh(a,e,i,s,r,n,0),void qh(o,e,i,s,r,n,0)}t=t.next}a=a.next}while(a!==t)}function Gh(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 $h(t,e){const i=function(t,e){let i=e;const s=t.x,r=t.y;let n,a=-1/0;if(nl(t,i))return i;do{if(nl(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&&el(rn.x||i.x===n.x&&Qh(n,i)))&&(n=i,c=e)}i=i.next}while(i!==o);return n}(t,e);if(!i)return e;const s=cl(i,t);return Hh(s,s.next),Hh(i,i.next)}function Qh(t,e){return rl(t.prev,t,e.prev)<0&&rl(e.next,t,t.next)<0}function Kh(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 tl(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 il(t,e,i,s,r,n,a,o){return!(t===a&&e===o)&&el(t,e,i,s,r,n,a,o)}function sl(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&&al(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(ll(t,e)&&ll(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)&&(rl(t.prev,t,e.prev)||rl(t,e.prev,e))||nl(t,e)&&rl(t.prev,t,t.next)>0&&rl(e.prev,e,e.next)>0)}function rl(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function nl(t,e){return t.x===e.x&&t.y===e.y}function al(t,e,i,s){const r=hl(rl(t,e,i)),n=hl(rl(t,e,s)),a=hl(rl(i,s,t)),o=hl(rl(i,s,e));return r!==n&&a!==o||(!(0!==r||!ol(t,i,e))||(!(0!==n||!ol(t,s,e))||(!(0!==a||!ol(i,t,s))||!(0!==o||!ol(i,e,s)))))}function ol(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 hl(t){return t>0?1:t<0?-1:0}function ll(t,e){return rl(t.prev,t,t.next)<0?rl(t,e,t.next)>=0&&rl(t,t.prev,e)>=0:rl(t,e,t.prev)<0||rl(t,t.next,e)<0}function cl(t,e){const i=pl(t.i,t.x,t.y),s=pl(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 ul(t,e,i,s){const r=pl(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 dl(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 pl(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class ml{static triangulate(t,e,i=2){return Uh(t,e,i)}}class yl{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 fl(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 Gi(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 Gi(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!=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 Vl extends sn{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Kr(16777215),this.specular=new Kr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(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.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 Ll extends sn{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Kr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(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 jl extends sn{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(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 Wl extends sn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Kr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(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.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 Ul extends sn{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 Dl extends sn{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 Hl extends sn{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Kr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Gi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.flatShading=t.flatShading,this.fog=t.fog,this}}class ql extends Ro{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 Jl(t,e){return t&&t.constructor!==e?"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t):t}function Xl(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Yl(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 Zl(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 Gl(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 $l{static convertArray(t,e){return Jl(t,e)}static isTypedArray(t){return Xl(t)}static getKeyframeOrder(t){return Yl(t)}static sortedArray(t,e,i){return Zl(t,e,i)}static flattenJSON(t,e,i,s){Gl(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 $i).fromArray(d).normalize().conjugate().toArray(d);const p=a.times.length;for(let t=0;t=r)break t;{const a=e[1];t=r)break e}n=i,i=0}}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&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,s=this.values,r=i.length;0===r&&(console.error("THREE.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)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,s),t=!1;break}if(null!==n&&n>s){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,s,n),t=!1;break}n=s}if(void 0!==s&&Xl(s))for(let e=0,i=s.length;e!==i;++e){const i=s[e];if(isNaN(i)){console.error("THREE.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()===Ee,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}}ic.prototype.ValueTypeName="",ic.prototype.TimeBufferType=Float32Array,ic.prototype.ValueBufferType=Float32Array,ic.prototype.DefaultInterpolation=ke;class sc extends ic{constructor(t,e,i){super(t,e,i)}}sc.prototype.ValueTypeName="bool",sc.prototype.ValueBufferType=Array,sc.prototype.DefaultInterpolation=Be,sc.prototype.InterpolantFactoryMethodLinear=void 0,sc.prototype.InterpolantFactoryMethodSmooth=void 0;class rc extends ic{constructor(t,e,i,s){super(t,e,i,s)}}rc.prototype.ValueTypeName="color";class nc extends ic{constructor(t,e,i,s){super(t,e,i,s)}}nc.prototype.ValueTypeName="number";class ac extends Ql{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)$i.slerpFlat(r,0,n,h-a,n,h,o);return r}}class oc extends ic{constructor(t,e,i,s){super(t,e,i,s)}InterpolantFactoryMethodLinear(t){return new ac(this.times,this.values,this.getValueSize(),t)}}oc.prototype.ValueTypeName="quaternion",oc.prototype.InterpolantFactoryMethodSmooth=void 0;class hc extends ic{constructor(t,e,i){super(t,e,i)}}hc.prototype.ValueTypeName="string",hc.prototype.ValueBufferType=Array,hc.prototype.DefaultInterpolation=Be,hc.prototype.InterpolantFactoryMethodLinear=void 0,hc.prototype.InterpolantFactoryMethodSmooth=void 0;class lc extends ic{constructor(t,e,i,s){super(t,e,i,s)}}lc.prototype.ValueTypeName="vector";class cc{constructor(t="",e=-1,i=[],s=2500){this.name=t,this.tracks=i,this.duration=e,this.blendMode=s,this.uuid=Di(),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(uc(i[t]).scale(s));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],i=t.tracks,s={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,s=i.length;t!==s;++t)e.push(ic.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(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(t,e,i,s,r){if(0!==i.length){const n=[],a=[];Gl(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!==gc[t])return void gc[t].push({onLoad:e,onProgress:i,onError:s});gc[t]=[],gc[t].push({onLoad:e,onProgress:i,onError:s});const n=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(n).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const i=gc[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 fc(`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=>{dc.add(t,e);const i=gc[t];delete gc[t];for(let t=0,s=i.length;t{const i=gc[t];if(void 0===i)throw this.manager.itemError(t),e;delete gc[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}}class bc extends yc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new xc(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):console.error(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 Kr).setHex(r.value);break;case"v2":s.uniforms[e].value=(new Gi).fromArray(r.value);break;case"v3":s.uniforms[e].value=(new Qi).fromArray(r.value);break;case"v4":s.uniforms[e].value=(new zs).fromArray(r.value);break;case"m3":s.uniforms[e].value=(new es).fromArray(r.value);break;case"m4":s.uniforms[e].value=(new or).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 Gi).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 Gi).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 Jc.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:Pl,SpriteMaterial:ma,RawShaderMaterial:Ol,ShaderMaterial:Zn,PointsMaterial:Xo,MeshPhysicalMaterial:Fl,MeshStandardMaterial:Nl,MeshPhongMaterial:Vl,MeshToonMaterial:Ll,MeshNormalMaterial:jl,MeshLambertMaterial:Wl,MeshDepthMaterial:Ul,MeshDistanceMaterial:Dl,MeshBasicMaterial:rn,MeshMatcapMaterial:Hl,LineDashedMaterial:ql,LineBasicMaterial:Ro,Material:sn}[t]}}class Xc{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 Yc extends Bn{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 Zc extends yc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new xc(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):console.error(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=ns(r.type,n),o=new ua(a,r.stride);return o.uuid=r.uuid,e[s]=o,o}const r=t.isInstancedBufferGeometry?new Yc:new Bn,n=t.data.index;if(void 0!==n){const t=ns(n.type,n.array);r.setIndex(new pn(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 pa(e,i.itemSize,i.offset,i.normalized)}else{const t=ns(i.type,i.array);n=new(i.isInstancedBufferAttribute?Ya:pn)(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 pc(e);r=new Mc(i),r.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e0){s=new Mc(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 Ps).fromJSON(t.boundingBox)),void 0!==t.boundingSphere&&(i=(new Qs).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 Qs).fromJSON(t.boundingSphere)),void 0!==t.boundingBox&&(n.boundingBox=(new Ps).fromJSON(t.boundingBox));break;case"LOD":n=new Ea;break;case"Line":n=new Wo(h(t.geometry),l(t.material));break;case"LineLoop":n=new Jo(h(t.geometry),l(t.material));break;case"LineSegments":n=new qo(h(t.geometry),l(t.material));break;case"PointCloud":case"Points":n=new Qo(h(t.geometry),l(t.material));break;case"Sprite":n=new Ia(l(t.material));break;case"Group":n=new na;break;case"Bone":n=new Da;break;default:n=new Pr}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.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.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!==tu.has(n))return e&&e(i),r.manager.itemEnd(t),i;s&&s(tu.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;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 dc.add(t,i),e&&e(i),r.manager.itemEnd(t),i})).catch((function(e){s&&s(e),tu.set(o,e),dc.remove(t),r.manager.itemError(t),r.manager.itemEnd(t)}));dc.add(t,o),r.manager.itemStart(t)}}let iu;class su{static getContext(){return void 0===iu&&(iu=new(window.AudioContext||window.webkitAudioContext)),iu}static setContext(t){iu=t}}class ru extends yc{constructor(t){super(t)}load(t,e,i,s){const r=this,n=new xc(this.manager);function a(e){s?s(e):console.error(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);su.getContext().decodeAudioData(i,(function(t){e(t)})).catch(a)}catch(t){a(t)}}),i,s)}}const nu=new or,au=new or,ou=new or;class hu{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new ta,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ta,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,ou.copy(t.projectionMatrix);const i=e.eyeSep/2,s=i*e.near/e.focus,r=e.near*Math.tan(Wi*e.fov*.5)/e.zoom;let n,a;au.elements[12]=-i,nu.elements[12]=i,n=-r*e.aspect+s,a=r*e.aspect+s,ou.elements[0]=2*e.near/(a-n),ou.elements[8]=(a+n)/(a-n),this.cameraL.projectionMatrix.copy(ou),n=-r*e.aspect-s,a=r*e.aspect-s,ou.elements[0]=2*e.near/(a-n),ou.elements[8]=(a+n)/(a-n),this.cameraR.projectionMatrix.copy(ou)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(au),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(nu)}}class lu extends ta{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class cu{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=performance.now();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}const uu=new Qi,du=new $i,pu=new Qi,mu=new Qi,yu=new Qi;class gu extends Pr{constructor(){super(),this.type="AudioListener",this.context=su.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new cu}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);const e=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(uu,du,pu),mu.set(0,0,-1).applyQuaternion(du),yu.set(0,1,0).applyQuaternion(du),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(uu.x,t),e.positionY.linearRampToValueAtTime(uu.y,t),e.positionZ.linearRampToValueAtTime(uu.z,t),e.forwardX.linearRampToValueAtTime(mu.x,t),e.forwardY.linearRampToValueAtTime(mu.y,t),e.forwardZ.linearRampToValueAtTime(mu.z,t),e.upX.linearRampToValueAtTime(yu.x,t),e.upY.linearRampToValueAtTime(yu.y,t),e.upZ.linearRampToValueAtTime(yu.z,t)}else e.setPosition(uu.x,uu.y,uu.z),e.setOrientation(mu.x,mu.y,mu.z,yu.x,yu.y,yu.z)}}class fu extends Pr{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 console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.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;console.warn("THREE.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;console.warn("THREE.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){$i.slerpFlat(t,e,t,e,t,i,s)}_slerpAdditive(t,e,i,s,r){const n=this._workIndex*r;$i.multiplyQuaternionsFlat(t,n,t,e,t,i),$i.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 Au="\\[\\]\\.:\\/",Tu=new RegExp("["+Au+"]","g"),zu="[^"+Au+"]",Iu="[^"+Au.replace("\\.","")+"]",Cu=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",zu)+/(WCOD+)?/.source.replace("WCOD",Iu)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",zu)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",zu)+"$"),Bu=["material","materials","bones","map"];class ku{constructor(t,e,i){this.path=e,this.parsedPath=i||ku.parseTrackName(e),this.node=ku.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 ku.Composite(t,e,i):new ku(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(Tu,"")}static parseTrackName(t){const e=Cu.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!==Bu.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 ku(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 Ru{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:Re,endingEnd:Re};for(let t=0;t!==n;++t){const e=r[t].createInterpolant(null);a[t]=e,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===Fe)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.time=s;if(n&&!(1&~r))return e-s}return s}_setEndings(t,e,i){const s=this._interpolantSettings;i?(s.endingStart=Pe,s.endingEnd=Pe):(s.endingStart=t?this.zeroSlopeAtStart?Pe:Re:Oe,s.endingEnd=e?this.zeroSlopeAtEnd?Pe:Re:Oe)}_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 Pu=new Float32Array(1);class Ou extends Vi{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_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 _u(ku.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,Zu).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 $u=new Qi,Qu=new Qi;class Ku{constructor(t=new Qi,e=new Qi){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){$u.subVectors(t,this.start),Qu.subVectors(this.end,this.start);const i=Qu.dot(Qu);let s=Qu.dot($u)/i;return e&&(s=Hi(s,0,1)),s}closestPointToPoint(t,e,i){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(s).add(this.start)}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 td=new Qi;class ed extends Pr{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const i=new Bn,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{Td.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(Td,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 Bd extends qo{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 Bn;i.setAttribute("position",new Mn(e,3)),i.setAttribute("color",new Mn([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(i,new Ro({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,i){const s=new Kr,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 kd{constructor(){this.type="ShapePath",this.color=new Kr,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new jh,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=yl.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 Wh,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 Rd(t,e,i,s)}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:t}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=t);export{et as ACESFilmicToneMapping,v as AddEquation,G as AddOperation,Fe as AdditiveAnimationBlendMode,g as AdditiveBlending,st as AgXToneMapping,Vt as AlphaFormat,wi as AlwaysCompare,W as AlwaysDepth,pi as AlwaysStencilFunc,Uc as AmbientLight,Ru as AnimationAction,cc as AnimationClip,bc as AnimationLoader,Ou as AnimationMixer,Eu as AnimationObjectGroup,$l as AnimationUtils,wh as ArcCurve,lu as ArrayCamera,Cd as ArrowHelper,nt as AttachedBindMode,fu as Audio,Su as AudioAnalyser,su as AudioContext,gu as AudioListener,ru as AudioLoader,Bd as AxesHelper,d as BackSide,We as BasicDepthPacking,o as BasicShadowMap,Eo as BatchedMesh,Da as Bone,sc as BooleanKeyframeTrack,Gu as Box2,Ps as Box3,_d as Box3Helper,Hn as BoxGeometry,Sd as BoxHelper,pn as BufferAttribute,Bn as BufferGeometry,Zc as BufferGeometryLoader,zt as ByteType,dc as Cache,Gn as Camera,vd as CameraHelper,ah as CanvasTexture,hh as CapsuleGeometry,zh as CatmullRomCurve3,tt as CineonToneMapping,lh as CircleGeometry,mt as ClampToEdgeWrapping,cu as Clock,Kr as Color,rc as ColorKeyframeTrack,gs as ColorManagement,rh as CompressedArrayTexture,nh as CompressedCubeTexture,sh as CompressedTexture,vc as CompressedTextureLoader,uh as ConeGeometry,V as ConstantAlphaFactor,N as ConstantColorFactor,Ed as Controls,ia as CubeCamera,ht as CubeReflectionMapping,lt as CubeRefractionMapping,sa as CubeTexture,Sc as CubeTextureLoader,dt as CubeUVReflectionMapping,kh as CubicBezierCurve,Eh as CubicBezierCurve3,Kl as CubicInterpolant,r as CullFaceBack,n as CullFaceFront,a as CullFaceFrontBack,s as CullFaceNone,bh as Curve,Lh as CurvePath,b as CustomBlending,it as CustomToneMapping,ch as CylinderGeometry,Xu as Cylindrical,Es as Data3DTexture,Bs as DataArrayTexture,Ha as DataTexture,_c as DataTextureLoader,ln as DataUtils,ii as DecrementStencilOp,ri as DecrementWrapStencilOp,mc as DefaultLoadingManager,Wt as DepthFormat,Ut as DepthStencilFormat,oh as DepthTexture,at as DetachedBindMode,Wc as DirectionalLight,fd as DirectionalLightHelper,ec as DiscreteInterpolant,ph as DodecahedronGeometry,p as DoubleSide,k as DstAlphaFactor,R as DstColorFactor,Ci as DynamicCopyUsage,Si as DynamicDrawUsage,Ti as DynamicReadUsage,xh as EdgesGeometry,vh as EllipseCurve,gi as EqualCompare,H as EqualDepth,hi as EqualStencilFunc,ct as EquirectangularReflectionMapping,ut as EquirectangularRefractionMapping,fr as Euler,Vi as EventDispatcher,xl as ExtrudeGeometry,xc as FileLoader,wn as Float16BufferAttribute,Mn as Float32BufferAttribute,Et as FloatType,la as Fog,ha as FogExp2,ih as FramebufferTexture,u as FrontSide,lo as Frustum,po as FrustumArray,Wu as GLBufferAttribute,ki as GLSL1,Ei as GLSL3,xi as GreaterCompare,J as GreaterDepth,vi as GreaterEqualCompare,q as GreaterEqualDepth,di as GreaterEqualStencilFunc,ci as GreaterStencilFunc,dd as GridHelper,na as Group,Rt as HalfFloatType,zc as HemisphereLight,ud as HemisphereLightHelper,vl as IcosahedronGeometry,eu as ImageBitmapLoader,Mc as ImageLoader,vs as ImageUtils,ei as IncrementStencilOp,si as IncrementWrapStencilOp,Ya as InstancedBufferAttribute,Yc as InstancedBufferGeometry,ju as InstancedInterleavedBuffer,io as InstancedMesh,fn as Int16BufferAttribute,bn as Int32BufferAttribute,mn as Int8BufferAttribute,Bt as IntType,ua as InterleavedBuffer,pa as InterleavedBufferAttribute,Ql as Interpolant,Be as InterpolateDiscrete,ke as InterpolateLinear,Ee as InterpolateSmooth,Fi as InterpolationSamplingMode,Ni as InterpolationSamplingType,ni as InvertStencilOp,Ke as KeepStencilOp,ic as KeyframeTrack,Ea as LOD,wl as LatheGeometry,xr as Layers,yi as LessCompare,U as LessDepth,fi as LessEqualCompare,D as LessEqualDepth,li as LessEqualStencilFunc,oi as LessStencilFunc,Tc as Light,qc as LightProbe,Wo as Line,Ku as Line3,Ro as LineBasicMaterial,Rh as LineCurve,Ph as LineCurve3,ql as LineDashedMaterial,Jo as LineLoop,qo as LineSegments,wt as LinearFilter,tc as LinearInterpolant,At as LinearMipMapLinearFilter,St as LinearMipMapNearestFilter,_t as LinearMipmapLinearFilter,Mt as LinearMipmapNearestFilter,Ze as LinearSRGBColorSpace,Q as LinearToneMapping,Ge as LinearTransfer,yc as Loader,Xc as LoaderUtils,pc as LoadingManager,ze as LoopOnce,Ce as LoopPingPong,Ie as LoopRepeat,e as MOUSE,sn as Material,Jc as MaterialLoader,Zi as MathUtils,Yu as Matrix2,es as Matrix3,or as Matrix4,_ as MaxEquation,Un as Mesh,rn as MeshBasicMaterial,Ul as MeshDepthMaterial,Dl as MeshDistanceMaterial,Wl as MeshLambertMaterial,Hl as MeshMatcapMaterial,jl as MeshNormalMaterial,Vl as MeshPhongMaterial,Fl as MeshPhysicalMaterial,Nl as MeshStandardMaterial,Ll as MeshToonMaterial,S as MinEquation,yt as MirroredRepeatWrapping,Z as MixOperation,x as MultiplyBlending,Y as MultiplyOperation,gt as NearestFilter,vt as NearestMipMapLinearFilter,xt as NearestMipMapNearestFilter,bt as NearestMipmapLinearFilter,ft as NearestMipmapNearestFilter,rt as NeutralToneMapping,mi as NeverCompare,j as NeverDepth,ai as NeverStencilFunc,m as NoBlending,Xe as NoColorSpace,$ as NoToneMapping,Ne as NormalAnimationBlendMode,y as NormalBlending,bi as NotEqualCompare,X as NotEqualDepth,ui as NotEqualStencilFunc,nc as NumberKeyframeTrack,Pr as Object3D,Gc as ObjectLoader,Je as ObjectSpaceNormalMap,Ml as OctahedronGeometry,T as OneFactor,L as OneMinusConstantAlphaFactor,F as OneMinusConstantColorFactor,E as OneMinusDstAlphaFactor,P as OneMinusDstColorFactor,B as OneMinusSrcAlphaFactor,I as OneMinusSrcColorFactor,Lc as OrthographicCamera,h as PCFShadowMap,l as PCFSoftShadowMap,jh as Path,ta as PerspectiveCamera,ao as Plane,Sl as PlaneGeometry,Ad as PlaneHelper,Vc as PointLight,od as PointLightHelper,Qo as Points,Xo as PointsMaterial,pd as PolarGridHelper,dh as PolyhedronGeometry,Mu as PositionalAudio,ku as PropertyBinding,_u as PropertyMixer,Oh as QuadraticBezierCurve,Nh as QuadraticBezierCurve3,$i as Quaternion,oc as QuaternionKeyframeTrack,ac as QuaternionLinearInterpolant,Ui as RAD2DEG,Ae as RED_GREEN_RGTC2_Format,Se as RED_RGTC1_Format,t as REVISION,Ue as RGBADepthPacking,jt as RGBAFormat,Yt as RGBAIntegerFormat,fe as RGBA_ASTC_10x10_Format,me as RGBA_ASTC_10x5_Format,ye as RGBA_ASTC_10x6_Format,ge as RGBA_ASTC_10x8_Format,xe as RGBA_ASTC_12x10_Format,be as RGBA_ASTC_12x12_Format,ae as RGBA_ASTC_4x4_Format,oe as RGBA_ASTC_5x4_Format,he as RGBA_ASTC_5x5_Format,le as RGBA_ASTC_6x5_Format,ce as RGBA_ASTC_6x6_Format,ue as RGBA_ASTC_8x5_Format,de as RGBA_ASTC_8x6_Format,pe as RGBA_ASTC_8x8_Format,ve as RGBA_BPTC_Format,ne as RGBA_ETC2_EAC_Format,ie as RGBA_PVRTC_2BPPV1_Format,ee as RGBA_PVRTC_4BPPV1_Format,Gt as RGBA_S3TC_DXT1_Format,$t as RGBA_S3TC_DXT3_Format,Qt as RGBA_S3TC_DXT5_Format,De as RGBDepthPacking,Lt as RGBFormat,Xt as RGBIntegerFormat,we as RGB_BPTC_SIGNED_Format,Me as RGB_BPTC_UNSIGNED_Format,se as RGB_ETC1_Format,re as RGB_ETC2_Format,te as RGB_PVRTC_2BPPV1_Format,Kt as RGB_PVRTC_4BPPV1_Format,Zt as RGB_S3TC_DXT1_Format,He as RGDepthPacking,qt as RGFormat,Jt as RGIntegerFormat,Ol as RawShaderMaterial,ar as Ray,Du as Raycaster,Dc as RectAreaLight,Dt as RedFormat,Ht as RedIntegerFormat,K as ReinhardToneMapping,Is as RenderTarget,Nu as RenderTarget3D,pt as RepeatWrapping,ti as ReplaceStencilOp,M as ReverseSubtractEquation,_l as RingGeometry,Te as SIGNED_RED_GREEN_RGTC2_Format,_e as SIGNED_RED_RGTC1_Format,Ye as SRGBColorSpace,$e as SRGBTransfer,ca as Scene,Zn as ShaderMaterial,Pl as ShadowMaterial,Wh as Shape,Al as ShapeGeometry,kd as ShapePath,yl as ShapeUtils,It as ShortType,Xa as Skeleton,nd as SkeletonHelper,Ua as SkinnedMesh,Ms as Source,Qs as Sphere,Tl as SphereGeometry,Ju as Spherical,Hc as SphericalHarmonics3,Fh as SplineCurve,Rc as SpotLight,ed as SpotLightHelper,Ia as Sprite,ma as SpriteMaterial,C as SrcAlphaFactor,O as SrcAlphaSaturateFactor,z as SrcColorFactor,Ii as StaticCopyUsage,Mi as StaticDrawUsage,Ai as StaticReadUsage,hu as StereoCamera,Bi as StreamCopyUsage,_i as StreamDrawUsage,zi as StreamReadUsage,hc as StringKeyframeTrack,w as SubtractEquation,f as SubtractiveBlending,i as TOUCH,qe as TangentSpaceNormalMap,zl as TetrahedronGeometry,Ts as Texture,Ac as TextureLoader,Pd as TextureUtils,Oi as TimestampQuery,Il as TorusGeometry,Cl as TorusKnotGeometry,Yr as Triangle,je as TriangleFanDrawMode,Le as TriangleStripDrawMode,Ve as TrianglesDrawMode,Bl as TubeGeometry,ot as UVMapping,xn as Uint16BufferAttribute,vn as Uint32BufferAttribute,yn as Uint8BufferAttribute,gn as Uint8ClampedBufferAttribute,Fu as Uniform,Lu as UniformsGroup,Yn as UniformsUtils,Tt as UnsignedByteType,Nt as UnsignedInt248Type,Ft as UnsignedInt5999Type,kt as UnsignedIntType,Pt as UnsignedShort4444Type,Ot as UnsignedShort5551Type,Ct as UnsignedShortType,c as VSMShadowMap,Gi as Vector2,Qi as Vector3,zs as Vector4,lc as VectorKeyframeTrack,eh as VideoFrameTexture,th as VideoTexture,Rs as WebGL3DRenderTarget,ks as WebGLArrayRenderTarget,Ri as WebGLCoordinateSystem,ra as WebGLCubeRenderTarget,Cs as WebGLRenderTarget,Pi as WebGPUCoordinateSystem,oa as WebXRController,kl as WireframeGeometry,Oe as WrapAroundEnding,Re as ZeroCurvatureEnding,A as ZeroFactor,Pe as ZeroSlopeEnding,Qe as ZeroStencilOp,ss as arrayNeedsUint32,qn as cloneUniforms,os as createCanvasElement,as as createElementNS,Rd as getByteLength,Xn as getUnlitUniformColorSpace,Jn as mergeUniforms,cs as probeAsync,us as toNormalizedProjectionMatrix,ds as toReversedProjectionMatrix,ls as warnOnce}; diff --git a/build/three.module.js b/build/three.module.js index 85cecd2d2e4497..26ebf5f7db4166 100644 --- a/build/three.module.js +++ b/build/three.module.js @@ -7271,6 +7271,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 20 ); if ( parameters.batchingColor ) _programLayers.enable( 21 ); + if ( parameters.gradientMap ) + _programLayers.enable( 22 ); array.push( _programLayers.mask ); _programLayers.disableAll(); diff --git a/build/three.module.min.js b/build/three.module.min.js index 6cb05553b549f4..4483b51c074574 100644 --- a/build/three.module.min.js +++ b/build/three.module.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2025 Three.js Authors * SPDX-License-Identifier: MIT */ -import{Matrix3 as e,Vector2 as t,Color as n,mergeUniforms as r,Vector3 as i,CubeUVReflectionMapping as a,Mesh as o,BoxGeometry as s,ShaderMaterial as l,BackSide as c,cloneUniforms as d,Euler as u,Matrix4 as f,ColorManagement as p,SRGBTransfer as m,PlaneGeometry as h,FrontSide as _,getUnlitUniformColorSpace as g,IntType as v,HalfFloatType as E,UnsignedByteType as S,FloatType as T,RGBAFormat as M,Plane as x,EquirectangularReflectionMapping as R,EquirectangularRefractionMapping as A,WebGLCubeRenderTarget as b,CubeReflectionMapping as C,CubeRefractionMapping as L,OrthographicCamera as P,PerspectiveCamera as U,NoToneMapping as D,MeshBasicMaterial as w,NoBlending as y,WebGLRenderTarget as I,BufferGeometry as N,BufferAttribute as O,LinearSRGBColorSpace as F,LinearFilter as B,warnOnce as H,Uint32BufferAttribute as G,Uint16BufferAttribute as V,arrayNeedsUint32 as z,Vector4 as k,DataArrayTexture as W,CubeTexture as X,Data3DTexture as Y,LessEqualCompare as K,DepthTexture as j,Texture as q,GLSL3 as Z,PCFShadowMap as $,PCFSoftShadowMap as Q,VSMShadowMap as J,CustomToneMapping as ee,NeutralToneMapping as te,AgXToneMapping as ne,ACESFilmicToneMapping as re,CineonToneMapping as ie,ReinhardToneMapping as ae,LinearToneMapping as oe,LinearTransfer as se,AddOperation as le,MixOperation as ce,MultiplyOperation as de,UniformsUtils as ue,DoubleSide as fe,NormalBlending as pe,TangentSpaceNormalMap as me,ObjectSpaceNormalMap as he,Layers as _e,Frustum as ge,MeshDepthMaterial as ve,RGBADepthPacking as Ee,MeshDistanceMaterial as Se,NearestFilter as Te,LessEqualDepth as Me,ReverseSubtractEquation as xe,SubtractEquation as Re,AddEquation as Ae,OneMinusConstantAlphaFactor as be,ConstantAlphaFactor as Ce,OneMinusConstantColorFactor as Le,ConstantColorFactor as Pe,OneMinusDstAlphaFactor as Ue,OneMinusDstColorFactor as De,OneMinusSrcAlphaFactor as we,OneMinusSrcColorFactor as ye,DstAlphaFactor as Ie,DstColorFactor as Ne,SrcAlphaSaturateFactor as Oe,SrcAlphaFactor as Fe,SrcColorFactor as Be,OneFactor as He,ZeroFactor as Ge,NotEqualDepth as Ve,GreaterDepth as ze,GreaterEqualDepth as ke,EqualDepth as We,LessDepth as Xe,AlwaysDepth as Ye,NeverDepth as Ke,CullFaceNone as je,CullFaceBack as qe,CullFaceFront as Ze,CustomBlending as $e,MultiplyBlending as Qe,SubtractiveBlending as Je,AdditiveBlending as et,MinEquation as tt,MaxEquation as nt,MirroredRepeatWrapping as rt,ClampToEdgeWrapping as it,RepeatWrapping as at,LinearMipmapLinearFilter as ot,LinearMipmapNearestFilter as st,NearestMipmapLinearFilter as lt,NearestMipmapNearestFilter as ct,NotEqualCompare as dt,GreaterCompare as ut,GreaterEqualCompare as ft,EqualCompare as pt,LessCompare as mt,AlwaysCompare as ht,NeverCompare as _t,NoColorSpace as gt,DepthStencilFormat as vt,getByteLength as Et,DepthFormat as St,UnsignedIntType as Tt,UnsignedInt248Type as Mt,UnsignedShortType as xt,createElementNS as Rt,UnsignedShort4444Type as At,UnsignedShort5551Type as bt,UnsignedInt5999Type as Ct,ByteType as Lt,ShortType as Pt,AlphaFormat as Ut,RGBFormat as Dt,RedFormat as wt,RedIntegerFormat as yt,RGFormat as It,RGIntegerFormat as Nt,RGBAIntegerFormat as Ot,RGB_S3TC_DXT1_Format as Ft,RGBA_S3TC_DXT1_Format as Bt,RGBA_S3TC_DXT3_Format as Ht,RGBA_S3TC_DXT5_Format as Gt,RGB_PVRTC_4BPPV1_Format as Vt,RGB_PVRTC_2BPPV1_Format as zt,RGBA_PVRTC_4BPPV1_Format as kt,RGBA_PVRTC_2BPPV1_Format as Wt,RGB_ETC1_Format as Xt,RGB_ETC2_Format as Yt,RGBA_ETC2_EAC_Format as Kt,RGBA_ASTC_4x4_Format as jt,RGBA_ASTC_5x4_Format as qt,RGBA_ASTC_5x5_Format as Zt,RGBA_ASTC_6x5_Format as $t,RGBA_ASTC_6x6_Format as Qt,RGBA_ASTC_8x5_Format as Jt,RGBA_ASTC_8x6_Format as en,RGBA_ASTC_8x8_Format as tn,RGBA_ASTC_10x5_Format as nn,RGBA_ASTC_10x6_Format as rn,RGBA_ASTC_10x8_Format as an,RGBA_ASTC_10x10_Format as on,RGBA_ASTC_12x10_Format as sn,RGBA_ASTC_12x12_Format as ln,RGBA_BPTC_Format as cn,RGB_BPTC_SIGNED_Format as dn,RGB_BPTC_UNSIGNED_Format as un,RED_RGTC1_Format as fn,SIGNED_RED_RGTC1_Format as pn,RED_GREEN_RGTC2_Format as mn,SIGNED_RED_GREEN_RGTC2_Format as hn,EventDispatcher as _n,ArrayCamera as gn,WebXRController as vn,RAD2DEG as En,createCanvasElement as Sn,SRGBColorSpace as Tn,REVISION as Mn,toNormalizedProjectionMatrix as xn,toReversedProjectionMatrix as Rn,probeAsync as An,WebGLCoordinateSystem as bn}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AlwaysStencilFunc,AmbientLight,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BasicShadowMap,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,Controls,CubeCamera,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CylinderGeometry,Cylindrical,DataTexture,DataTextureLoader,DataUtils,DecrementStencilOp,DecrementWrapStencilOp,DefaultLoadingManager,DetachedBindMode,DirectionalLight,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicDrawUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,EqualStencilFunc,ExtrudeGeometry,FileLoader,Float16BufferAttribute,Float32BufferAttribute,Fog,FogExp2,FramebufferTexture,FrustumArray,GLBufferAttribute,GLSL1,GreaterEqualStencilFunc,GreaterStencilFunc,GridHelper,Group,HemisphereLight,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,IncrementStencilOp,IncrementWrapStencilOp,InstancedBufferAttribute,InstancedBufferGeometry,InstancedInterleavedBuffer,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,InterleavedBuffer,InterleavedBufferAttribute,Interpolant,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,InvertStencilOp,KeepStencilOp,KeyframeTrack,LOD,LatheGeometry,LessEqualStencilFunc,LessStencilFunc,Light,LightProbe,Line,Line3,LineBasicMaterial,LineCurve,LineCurve3,LineDashedMaterial,LineLoop,LineSegments,LinearInterpolant,LinearMipMapLinearFilter,LinearMipMapNearestFilter,Loader,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,Material,MaterialLoader,MathUtils,Matrix2,MeshLambertMaterial,MeshMatcapMaterial,MeshNormalMaterial,MeshPhongMaterial,MeshPhysicalMaterial,MeshStandardMaterial,MeshToonMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NeverStencilFunc,NormalAnimationBlendMode,NotEqualStencilFunc,NumberKeyframeTrack,Object3D,ObjectLoader,OctahedronGeometry,Path,PlaneHelper,PointLight,PointLightHelper,Points,PointsMaterial,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,Quaternion,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBDepthPacking,RGBIntegerFormat,RGDepthPacking,RawShaderMaterial,Ray,Raycaster,RectAreaLight,RenderTarget,RenderTarget3D,ReplaceStencilOp,RingGeometry,Scene,ShadowMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Sphere,SphereGeometry,Spherical,SphericalHarmonics3,SplineCurve,SpotLight,SpotLightHelper,Sprite,SpriteMaterial,StaticCopyUsage,StaticDrawUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,TimestampQuery,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,UVMapping,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGPUCoordinateSystem,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding,ZeroStencilOp}from"./three.core.min.js";function Cn(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){!0!==t&&null!==n&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Ln(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))},update:function(n,r){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const e=t.get(n);return void((!e||e.versione.start-t.start));let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},Un={common:{diffuse:{value:new n(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new e},alphaMap:{value:null},alphaMapTransform:{value:new e},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new e}},envmap:{envMap:{value:null},envMapRotation:{value:new e},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new e}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new e}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new e},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new e},normalScale:{value:new t(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new e},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new e}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new e}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new e}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new n(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new n(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new e},alphaTest:{value:0},uvTransform:{value:new e}},sprite:{diffuse:{value:new n(16777215)},opacity:{value:1},center:{value:new t(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new e},alphaMap:{value:null},alphaMapTransform:{value:new e},alphaTest:{value:0}}},Dn={basic:{uniforms:r([Un.common,Un.specularmap,Un.envmap,Un.aomap,Un.lightmap,Un.fog]),vertexShader:Pn.meshbasic_vert,fragmentShader:Pn.meshbasic_frag},lambert:{uniforms:r([Un.common,Un.specularmap,Un.envmap,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.fog,Un.lights,{emissive:{value:new n(0)}}]),vertexShader:Pn.meshlambert_vert,fragmentShader:Pn.meshlambert_frag},phong:{uniforms:r([Un.common,Un.specularmap,Un.envmap,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.fog,Un.lights,{emissive:{value:new n(0)},specular:{value:new n(1118481)},shininess:{value:30}}]),vertexShader:Pn.meshphong_vert,fragmentShader:Pn.meshphong_frag},standard:{uniforms:r([Un.common,Un.envmap,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.roughnessmap,Un.metalnessmap,Un.fog,Un.lights,{emissive:{value:new n(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Pn.meshphysical_vert,fragmentShader:Pn.meshphysical_frag},toon:{uniforms:r([Un.common,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.gradientmap,Un.fog,Un.lights,{emissive:{value:new n(0)}}]),vertexShader:Pn.meshtoon_vert,fragmentShader:Pn.meshtoon_frag},matcap:{uniforms:r([Un.common,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.fog,{matcap:{value:null}}]),vertexShader:Pn.meshmatcap_vert,fragmentShader:Pn.meshmatcap_frag},points:{uniforms:r([Un.points,Un.fog]),vertexShader:Pn.points_vert,fragmentShader:Pn.points_frag},dashed:{uniforms:r([Un.common,Un.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Pn.linedashed_vert,fragmentShader:Pn.linedashed_frag},depth:{uniforms:r([Un.common,Un.displacementmap]),vertexShader:Pn.depth_vert,fragmentShader:Pn.depth_frag},normal:{uniforms:r([Un.common,Un.bumpmap,Un.normalmap,Un.displacementmap,{opacity:{value:1}}]),vertexShader:Pn.meshnormal_vert,fragmentShader:Pn.meshnormal_frag},sprite:{uniforms:r([Un.sprite,Un.fog]),vertexShader:Pn.sprite_vert,fragmentShader:Pn.sprite_frag},background:{uniforms:{uvTransform:{value:new e},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Pn.background_vert,fragmentShader:Pn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new e}},vertexShader:Pn.backgroundCube_vert,fragmentShader:Pn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Pn.cube_vert,fragmentShader:Pn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Pn.equirect_vert,fragmentShader:Pn.equirect_frag},distanceRGBA:{uniforms:r([Un.common,Un.displacementmap,{referencePosition:{value:new i},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Pn.distanceRGBA_vert,fragmentShader:Pn.distanceRGBA_frag},shadow:{uniforms:r([Un.lights,Un.fog,{color:{value:new n(0)},opacity:{value:1}}]),vertexShader:Pn.shadow_vert,fragmentShader:Pn.shadow_frag}};Dn.physical={uniforms:r([Dn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new e},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new e},clearcoatNormalScale:{value:new t(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new e},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new e},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new e},sheen:{value:0},sheenColor:{value:new n(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new e},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new e},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new e},transmissionSamplerSize:{value:new t},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new e},attenuationDistance:{value:0},attenuationColor:{value:new n(0)},specularColor:{value:new n(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new e},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new e},anisotropyVector:{value:new t},anisotropyMap:{value:null},anisotropyMapTransform:{value:new e}}]),vertexShader:Pn.meshphysical_vert,fragmentShader:Pn.meshphysical_frag};const wn={r:0,b:0,g:0},yn=new u,In=new f;function Nn(e,t,r,i,u,f,v){const E=new n(0);let S,T,M=!0===f?0:1,x=null,R=0,A=null;function b(e){let n=!0===e.isScene?e.background:null;if(n&&n.isTexture){n=(e.backgroundBlurriness>0?r:t).get(n)}return n}function C(t,n){t.getRGB(wn,g(e)),i.buffers.color.setClear(wn.r,wn.g,wn.b,n,v)}return{getClearColor:function(){return E},setClearColor:function(e,t=1){E.set(e),M=t,C(E,M)},getClearAlpha:function(){return M},setClearAlpha:function(e){M=e,C(E,M)},render:function(t){let n=!1;const r=b(t);null===r?C(E,M):r&&r.isColor&&(C(r,1),n=!0);const a=e.xr.getEnvironmentBlendMode();"additive"===a?i.buffers.color.setClear(0,0,0,1,v):"alpha-blend"===a&&i.buffers.color.setClear(0,0,0,0,v),(e.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const r=b(n);r&&(r.isCubeTexture||r.mapping===a)?(void 0===T&&(T=new o(new s(1,1,1),new l({name:"BackgroundCubeMaterial",uniforms:d(Dn.backgroundCube.uniforms),vertexShader:Dn.backgroundCube.vertexShader,fragmentShader:Dn.backgroundCube.fragmentShader,side:c,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),T.geometry.deleteAttribute("normal"),T.geometry.deleteAttribute("uv"),T.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(T.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),u.update(T)),yn.copy(n.backgroundRotation),yn.x*=-1,yn.y*=-1,yn.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(yn.y*=-1,yn.z*=-1),T.material.uniforms.envMap.value=r,T.material.uniforms.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,T.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,T.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,T.material.uniforms.backgroundRotation.value.setFromMatrix4(In.makeRotationFromEuler(yn)),T.material.toneMapped=p.getTransfer(r.colorSpace)!==m,x===r&&R===r.version&&A===e.toneMapping||(T.material.needsUpdate=!0,x=r,R=r.version,A=e.toneMapping),T.layers.enableAll(),t.unshift(T,T.geometry,T.material,0,0,null)):r&&r.isTexture&&(void 0===S&&(S=new o(new h(2,2),new l({name:"BackgroundMaterial",uniforms:d(Dn.background.uniforms),vertexShader:Dn.background.vertexShader,fragmentShader:Dn.background.fragmentShader,side:_,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),S.geometry.deleteAttribute("normal"),Object.defineProperty(S.material,"map",{get:function(){return this.uniforms.t2D.value}}),u.update(S)),S.material.uniforms.t2D.value=r,S.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,S.material.toneMapped=p.getTransfer(r.colorSpace)!==m,!0===r.matrixAutoUpdate&&r.updateMatrix(),S.material.uniforms.uvTransform.value.copy(r.matrix),x===r&&R===r.version&&A===e.toneMapping||(S.material.needsUpdate=!0,x=r,R=r.version,A=e.toneMapping),S.layers.enableAll(),t.unshift(S,S.geometry,S.material,0,0,null))},dispose:function(){void 0!==T&&(T.geometry.dispose(),T.material.dispose(),T=void 0),void 0!==S&&(S.geometry.dispose(),S.material.dispose(),S=void 0)}}}function On(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=c(null);let a=i,o=!1;function s(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function c(e){const t=[],r=[],i=[];for(let e=0;e=0){const n=i[t];let r=o[t];if(void 0===r&&("instanceMatrix"===t&&e.instanceMatrix&&(r=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(r=e.instanceColor)),void 0===n)return!0;if(n.attribute!==r)return!0;if(r&&n.data!==r.data)return!0;s++}}return a.attributesNum!==s||a.index!==r}(n,h,l,_),g&&function(e,t,n,r){const i={},o=t.attributes;let s=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=o[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}}a.attributes=i,a.attributesNum=s,a.index=r}(n,h,l,_),null!==_&&t.update(_,e.ELEMENT_ARRAY_BUFFER),(g||o)&&(o=!1,function(n,r,i,a){d();const o=a.attributes,s=i.getAttributes(),l=r.defaultAttributeValues;for(const r in s){const i=s[r];if(i.location>=0){let s=o[r];if(void 0===s&&("instanceMatrix"===r&&n.instanceMatrix&&(s=n.instanceMatrix),"instanceColor"===r&&n.instanceColor&&(s=n.instanceColor)),void 0!==s){const r=s.normalized,o=s.itemSize,l=t.get(s);if(void 0===l)continue;const c=l.buffer,d=l.type,p=l.bytesPerElement,h=d===e.INT||d===e.UNSIGNED_INT||s.gpuType===v;if(s.isInterleavedBufferAttribute){const t=s.data,l=t.stride,_=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let o=void 0!==n.precision?n.precision:"highp";const s=a(o);s!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",s,"instead."),o=s);const l=!0===n.logarithmicDepthBuffer,c=!0===n.reverseDepthBuffer&&t.has("EXT_clip_control"),d=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),u=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:a,textureFormatReadable:function(t){return t===M||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const i=n===E&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==S&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==T&&!i)},precision:o,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:d,maxVertexTextures:u,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function Hn(t){const n=this;let r=null,i=0,a=!1,o=!1;const s=new x,l=new e,c={value:null,needsUpdate:!1};function d(e,t,r,i){const a=null!==e?e.length:0;let o=null;if(0!==a){if(o=c.value,!0!==i||null===o){const n=r+4*a,i=t.matrixWorldInverse;l.getNormalMatrix(i),(null===o||o.length0);n.numPlanes=i,n.numIntersection=0}();else{const e=o?0:i,t=4*e;let n=m.clippingState||null;c.value=n,n=d(u,s,t,l);for(let e=0;e!==t;++e)n[e]=r[e];m.clippingState=n,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}}}function Gn(e){let t=new WeakMap;function n(e,t){return t===R?e.mapping=C:t===A&&(e.mapping=L),e}function r(e){const n=e.target;n.removeEventListener("dispose",r);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){const a=i.mapping;if(a===R||a===A){if(t.has(i)){return n(t.get(i).texture,i.mapping)}{const a=i.image;if(a&&a.height>0){const o=new b(a.height);return o.fromEquirectangularTexture(e,i),t.set(i,o),i.addEventListener("dispose",r),n(o.texture,i.mapping)}return null}}}return i},dispose:function(){t=new WeakMap}}}const Vn=[.125,.215,.35,.446,.526,.582],zn=20,kn=new P,Wn=new n;let Xn=null,Yn=0,Kn=0,jn=!1;const qn=(1+Math.sqrt(5))/2,Zn=1/qn,$n=[new i(-qn,Zn,0),new i(qn,Zn,0),new i(-Zn,0,qn),new i(Zn,0,qn),new i(0,qn,-Zn),new i(0,qn,Zn),new i(-1,1,-1),new i(1,1,-1),new i(-1,1,1),new i(1,1,1)],Qn=new i;class Jn{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,i={}){const{size:a=256,position:o=Qn}=i;Xn=this._renderer.getRenderTarget(),Yn=this._renderer.getActiveCubeFace(),Kn=this._renderer.getActiveMipmapLevel(),jn=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=rr(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=nr(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?s=Vn[o-e+4-1]:0===o&&(s=0),r.push(s);const l=1/(a-2),c=-l,d=1+l,u=[c,c,d,c,d,d,c,c,d,d,c,d],f=6,p=6,m=3,h=2,_=1,g=new Float32Array(m*p*f),v=new Float32Array(h*p*f),E=new Float32Array(_*p*f);for(let e=0;e2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];g.set(r,m*p*e),v.set(u,h*p*e);const i=[e,e,e,e,e,e];E.set(i,_*p*e)}const S=new N;S.setAttribute("position",new O(g,m)),S.setAttribute("uv",new O(v,h)),S.setAttribute("faceIndex",new O(E,_)),t.push(S),i>4&&i--}return{lodPlanes:t,sizeLods:n,sigmas:r}}(r)),this._blurMaterial=function(e,t,n){const r=new Float32Array(zn),a=new i(0,1,0),o=new l({name:"SphericalGaussianBlur",defines:{n:zn,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:ir(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:y,depthTest:!1,depthWrite:!1});return o}(r,e,t)}return r}_compileMaterial(e){const t=new o(this._lodPlanes[0],e);this._renderer.compile(t,kn)}_sceneToCubeUV(e,t,n,r,i){const a=new U(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,f=u.autoClear,p=u.toneMapping;u.getClearColor(Wn),u.toneMapping=D,u.autoClear=!1;const m=new w({name:"PMREM.Background",side:c,depthWrite:!1,depthTest:!1}),h=new o(new s,m);let _=!1;const g=e.background;g?g.isColor&&(m.color.copy(g),e.background=null,_=!0):(m.color.copy(Wn),_=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(a.up.set(0,l[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+d[t],i.y,i.z)):1===n?(a.up.set(0,0,l[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+d[t],i.z)):(a.up.set(0,l[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+d[t]));const o=this._cubeSize;tr(r,n*o,t>2?o:0,o,o),u.setRenderTarget(r),_&&u.render(h,a),u.render(e,a)}h.geometry.dispose(),h.material.dispose(),u.toneMapping=p,u.autoClear=f,e.background=g}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===C||e.mapping===L;r?(null===this._cubemapMaterial&&(this._cubemapMaterial=rr()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=nr());const i=r?this._cubemapMaterial:this._equirectMaterial,a=new o(this._lodPlanes[0],i);i.uniforms.envMap.value=e;const s=this._cubeSize;tr(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,kn)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let t=1;tzn&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${h} samples when the maximum is set to 20`);const _=[];let g=0;for(let e=0;ev-4?r-v+4:0),4*(this._cubeSize-E),3*E,2*E),l.setRenderTarget(t),l.render(d,kn)}}function er(e,t,n){const r=new I(e,t,n);return r.texture.mapping=a,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function tr(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function nr(){return new l({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ir(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:y,depthTest:!1,depthWrite:!1})}function rr(){return new l({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ir(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:y,depthTest:!1,depthWrite:!1})}function ir(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function ar(e){let t=new WeakMap,n=null;function r(e){const n=e.target;n.removeEventListener("dispose",r);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){const a=i.mapping,o=a===R||a===A,s=a===C||a===L;if(o||s){let a=t.get(i);const l=void 0!==a?a.texture.pmremVersion:0;if(i.isRenderTargetTexture&&i.pmremVersion!==l)return null===n&&(n=new Jn(e)),a=o?n.fromEquirectangular(i,a):n.fromCubemap(i,a),a.texture.pmremVersion=i.pmremVersion,t.set(i,a),a.texture;if(void 0!==a)return a.texture;{const l=i.image;return o&&l&&l.height>0||s&&l&&function(e){let t=0;const n=6;for(let r=0;rn.maxTextureSize&&(M=Math.ceil(S/n.maxTextureSize),S=n.maxTextureSize);const x=new Float32Array(S*M*4*u),R=new W(x,S,M,u);R.type=T,R.needsUpdate=!0;const A=4*E;for(let C=0;C0)return e;const i=t*n;let a=gr[i];if(void 0===a&&(a=new Float32Array(i),gr[i]=a),0!==t){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function xr(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n":" "} ${i}: ${n[e]}`)}return r.join("\n")}(e.getShaderSource(t),r)}return i}function Ti(e,t){const n=function(e){p._getMatrix(Ei,p.workingColorSpace,e);const t=`mat3( ${Ei.elements.map((e=>e.toFixed(4)))} )`;switch(p.getTransfer(e)){case se:return[t,"LinearTransferOETF"];case m:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}function Mi(e,t){let n;switch(t){case oe:n="Linear";break;case ae:n="Reinhard";break;case ie:n="Cineon";break;case re:n="ACESFilmic";break;case ne:n="AgX";break;case te:n="Neutral";break;case ee:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const xi=new i;function Ri(){p.getLuminanceCoefficients(xi);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${xi.x.toFixed(4)}, ${xi.y.toFixed(4)}, ${xi.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function Ai(e){return""!==e}function bi(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Ci(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Li=/^[ \t]*#include +<([\w\d./]+)>/gm;function Pi(e){return e.replace(Li,Di)}const Ui=new Map;function Di(e,t){let n=Pn[t];if(void 0===n){const e=Ui.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Pn[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Pi(n)}const wi=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function yi(e){return e.replace(wi,Ii)}function Ii(e,t,n,r){let i="";for(let e=parseInt(t);e0&&(g+="\n"),v=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,h].filter(Ai).join("\n"),v.length>0&&(v+="\n")):(g=[Ni(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,h,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Ai).join("\n"),v=[Ni(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,h,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.envMap?"#define "+u:"",n.envMap?"#define "+f:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==D?"#define TONE_MAPPING":"",n.toneMapping!==D?Pn.tonemapping_pars_fragment:"",n.toneMapping!==D?Mi("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Pn.colorspace_pars_fragment,Ti("linearToOutputTexel",n.outputColorSpace),Ri(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(Ai).join("\n")),s=Pi(s),s=bi(s,n),s=Ci(s,n),l=Pi(l),l=bi(l,n),l=Ci(l,n),s=yi(s),l=yi(l),!0!==n.isRawShaderMaterial&&(E="#version 300 es\n",g=[m,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,v=["#define varying in",n.glslVersion===Z?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Z?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+v);const S=E+g+s,T=E+v+l,M=gi(i,i.VERTEX_SHADER,S),x=gi(i,i.FRAGMENT_SHADER,T);function R(t){if(e.debug.checkShaderErrors){const n=i.getProgramInfoLog(_).trim(),r=i.getShaderInfoLog(M).trim(),a=i.getShaderInfoLog(x).trim();let o=!0,s=!0;if(!1===i.getProgramParameter(_,i.LINK_STATUS))if(o=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(i,_,M,x);else{const e=Si(i,M,"vertex"),r=Si(i,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(_,i.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+r)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==r&&""!==a||(s=!1);s&&(t.diagnostics={runnable:o,programLog:n,vertexShader:{log:r,prefix:g},fragmentShader:{log:a,prefix:v}})}i.deleteShader(M),i.deleteShader(x),A=new _i(i,_),b=function(e,t){const n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i0,J=o.clearcoat>0,ee=o.dispersion>0,te=o.iridescence>0,ne=o.sheen>0,re=o.transmission>0,ie=Q&&!!o.anisotropyMap,ae=J&&!!o.clearcoatMap,oe=J&&!!o.clearcoatNormalMap,se=J&&!!o.clearcoatRoughnessMap,le=te&&!!o.iridescenceMap,ce=te&&!!o.iridescenceThicknessMap,de=ne&&!!o.sheenColorMap,ue=ne&&!!o.sheenRoughnessMap,_e=!!o.specularMap,ge=!!o.specularColorMap,ve=!!o.specularIntensityMap,Ee=re&&!!o.transmissionMap,Se=re&&!!o.thicknessMap,Te=!!o.gradientMap,Me=!!o.alphaMap,xe=o.alphaTest>0,Re=!!o.alphaHash,Ae=!!o.extensions;let be=D;o.toneMapped&&(null!==O&&!0!==O.isXRRenderTarget||(be=e.toneMapping));const Ce={shaderID:C,shaderType:o.type,shaderName:o.name,vertexShader:U,fragmentShader:w,defines:o.defines,customVertexShaderID:y,customFragmentShaderID:I,isRawShaderMaterial:!0===o.isRawShaderMaterial,glslVersion:o.glslVersion,precision:g,batching:G,batchingColor:G&&null!==T._colorsTexture,instancing:H,instancingColor:H&&null!==T.instanceColor,instancingMorph:H&&null!==T.morphTexture,supportsVertexTextures:_,outputColorSpace:null===O?e.outputColorSpace:!0===O.isXRRenderTarget?O.texture.colorSpace:F,alphaToCoverage:!!o.alphaToCoverage,map:V,matcap:z,envMap:k,envMapMode:k&&A.mapping,envMapCubeUVHeight:b,aoMap:W,lightMap:X,bumpMap:Y,normalMap:K,displacementMap:_&&j,emissiveMap:q,normalMapObjectSpace:K&&o.normalMapType===he,normalMapTangentSpace:K&&o.normalMapType===me,metalnessMap:Z,roughnessMap:$,anisotropy:Q,anisotropyMap:ie,clearcoat:J,clearcoatMap:ae,clearcoatNormalMap:oe,clearcoatRoughnessMap:se,dispersion:ee,iridescence:te,iridescenceMap:le,iridescenceThicknessMap:ce,sheen:ne,sheenColorMap:de,sheenRoughnessMap:ue,specularMap:_e,specularColorMap:ge,specularIntensityMap:ve,transmission:re,transmissionMap:Ee,thicknessMap:Se,gradientMap:Te,opaque:!1===o.transparent&&o.blending===pe&&!1===o.alphaToCoverage,alphaMap:Me,alphaTest:xe,alphaHash:Re,combine:o.combine,mapUv:V&&E(o.map.channel),aoMapUv:W&&E(o.aoMap.channel),lightMapUv:X&&E(o.lightMap.channel),bumpMapUv:Y&&E(o.bumpMap.channel),normalMapUv:K&&E(o.normalMap.channel),displacementMapUv:j&&E(o.displacementMap.channel),emissiveMapUv:q&&E(o.emissiveMap.channel),metalnessMapUv:Z&&E(o.metalnessMap.channel),roughnessMapUv:$&&E(o.roughnessMap.channel),anisotropyMapUv:ie&&E(o.anisotropyMap.channel),clearcoatMapUv:ae&&E(o.clearcoatMap.channel),clearcoatNormalMapUv:oe&&E(o.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:se&&E(o.clearcoatRoughnessMap.channel),iridescenceMapUv:le&&E(o.iridescenceMap.channel),iridescenceThicknessMapUv:ce&&E(o.iridescenceThicknessMap.channel),sheenColorMapUv:de&&E(o.sheenColorMap.channel),sheenRoughnessMapUv:ue&&E(o.sheenRoughnessMap.channel),specularMapUv:_e&&E(o.specularMap.channel),specularColorMapUv:ge&&E(o.specularColorMap.channel),specularIntensityMapUv:ve&&E(o.specularIntensityMap.channel),transmissionMapUv:Ee&&E(o.transmissionMap.channel),thicknessMapUv:Se&&E(o.thicknessMap.channel),alphaMapUv:Me&&E(o.alphaMap.channel),vertexTangents:!!x.attributes.tangent&&(K||Q),vertexColors:o.vertexColors,vertexAlphas:!0===o.vertexColors&&!!x.attributes.color&&4===x.attributes.color.itemSize,pointsUvs:!0===T.isPoints&&!!x.attributes.uv&&(V||Me),fog:!!M,useFog:!0===o.fog,fogExp2:!!M&&M.isFogExp2,flatShading:!0===o.flatShading&&!1===o.wireframe,sizeAttenuation:!0===o.sizeAttenuation,logarithmicDepthBuffer:h,reverseDepthBuffer:B,skinning:!0===T.isSkinnedMesh,morphTargets:void 0!==x.morphAttributes.position,morphNormals:void 0!==x.morphAttributes.normal,morphColors:void 0!==x.morphAttributes.color,morphTargetsCount:P,morphTextureStride:N,numDirLights:l.directional.length,numPointLights:l.point.length,numSpotLights:l.spot.length,numSpotLightMaps:l.spotLightMap.length,numRectAreaLights:l.rectArea.length,numHemiLights:l.hemi.length,numDirLightShadows:l.directionalShadowMap.length,numPointLightShadows:l.pointShadowMap.length,numSpotLightShadows:l.spotShadowMap.length,numSpotLightShadowsWithMaps:l.numSpotLightShadowsWithMaps,numLightProbes:l.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:o.dithering,shadowMapEnabled:e.shadowMap.enabled&&f.length>0,shadowMapType:e.shadowMap.type,toneMapping:be,decodeVideoTexture:V&&!0===o.map.isVideoTexture&&p.getTransfer(o.map.colorSpace)===m,decodeVideoTextureEmissive:q&&!0===o.emissiveMap.isVideoTexture&&p.getTransfer(o.emissiveMap.colorSpace)===m,premultipliedAlpha:o.premultipliedAlpha,doubleSided:o.side===fe,flipSided:o.side===c,useDepthPacking:o.depthPacking>=0,depthPacking:o.depthPacking||0,index0AttributeName:o.index0AttributeName,extensionClipCullDistance:Ae&&!0===o.extensions.clipCullDistance&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ae&&!0===o.extensions.multiDraw||G)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:o.customProgramCacheKey()};return Ce.vertexUv1s=u.has(1),Ce.vertexUv2s=u.has(2),Ce.vertexUv3s=u.has(3),u.clear(),Ce},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){l.disableAll(),t.supportsVertexTextures&&l.enable(0);t.instancing&&l.enable(1);t.instancingColor&&l.enable(2);t.instancingMorph&&l.enable(3);t.matcap&&l.enable(4);t.envMap&&l.enable(5);t.normalMapObjectSpace&&l.enable(6);t.normalMapTangentSpace&&l.enable(7);t.clearcoat&&l.enable(8);t.iridescence&&l.enable(9);t.alphaTest&&l.enable(10);t.vertexColors&&l.enable(11);t.vertexAlphas&&l.enable(12);t.vertexUv1s&&l.enable(13);t.vertexUv2s&&l.enable(14);t.vertexUv3s&&l.enable(15);t.vertexTangents&&l.enable(16);t.anisotropy&&l.enable(17);t.alphaHash&&l.enable(18);t.batching&&l.enable(19);t.dispersion&&l.enable(20);t.batchingColor&&l.enable(21);e.push(l.mask),l.disableAll(),t.fog&&l.enable(0);t.useFog&&l.enable(1);t.flatShading&&l.enable(2);t.logarithmicDepthBuffer&&l.enable(3);t.reverseDepthBuffer&&l.enable(4);t.skinning&&l.enable(5);t.morphTargets&&l.enable(6);t.morphNormals&&l.enable(7);t.morphColors&&l.enable(8);t.premultipliedAlpha&&l.enable(9);t.shadowMapEnabled&&l.enable(10);t.doubleSided&&l.enable(11);t.flipSided&&l.enable(12);t.useDepthPacking&&l.enable(13);t.dithering&&l.enable(14);t.transmission&&l.enable(15);t.sheen&&l.enable(16);t.opaque&&l.enable(17);t.pointsUvs&&l.enable(18);t.decodeVideoTexture&&l.enable(19);t.decodeVideoTextureEmissive&&l.enable(20);t.alphaToCoverage&&l.enable(21);e.push(l.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=v[e.type];let n;if(t){const e=Dn[t];n=ue.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let r;for(let e=0,t=f.length;e0?r.push(d):!0===o.transparent?i.push(d):n.push(d)},unshift:function(e,t,o,s,l,c){const d=a(e,t,o,s,l,c);o.transmission>0?r.unshift(d):!0===o.transparent?i.unshift(d):n.unshift(d)},finish:function(){for(let n=t,r=e.length;n1&&n.sort(e||zi),r.length>1&&r.sort(t||ki),i.length>1&&i.sort(t||ki)}}}function Xi(){let e=new WeakMap;return{get:function(t,n){const r=e.get(t);let i;return void 0===r?(i=new Wi,e.set(t,[i])):n>=r.length?(i=new Wi,r.push(i)):i=r[n],i},dispose:function(){e=new WeakMap}}}function Yi(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let r;switch(t.type){case"DirectionalLight":r={direction:new i,color:new n};break;case"SpotLight":r={position:new i,direction:new i,color:new n,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":r={position:new i,color:new n,distance:0,decay:0};break;case"HemisphereLight":r={direction:new i,skyColor:new n,groundColor:new n};break;case"RectAreaLight":r={color:new n,position:new i,halfWidth:new i,halfHeight:new i}}return e[t.id]=r,r}}}let Ki=0;function ji(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function qi(e){const n=new Yi,r=function(){const e={};return{get:function(n){if(void 0!==e[n.id])return e[n.id];let r;switch(n.type){case"DirectionalLight":case"SpotLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new t};break;case"PointLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new t,shadowCameraNear:1,shadowCameraFar:1e3}}return e[n.id]=r,r}}}(),a={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)a.probe.push(new i);const o=new i,s=new f,l=new f;return{setup:function(t){let i=0,o=0,s=0;for(let e=0;e<9;e++)a.probe[e].set(0,0,0);let l=0,c=0,d=0,u=0,f=0,p=0,m=0,h=0,_=0,g=0,v=0;t.sort(ji);for(let e=0,E=t.length;e0&&(!0===e.has("OES_texture_float_linear")?(a.rectAreaLTC1=Un.LTC_FLOAT_1,a.rectAreaLTC2=Un.LTC_FLOAT_2):(a.rectAreaLTC1=Un.LTC_HALF_1,a.rectAreaLTC2=Un.LTC_HALF_2)),a.ambient[0]=i,a.ambient[1]=o,a.ambient[2]=s;const E=a.hash;E.directionalLength===l&&E.pointLength===c&&E.spotLength===d&&E.rectAreaLength===u&&E.hemiLength===f&&E.numDirectionalShadows===p&&E.numPointShadows===m&&E.numSpotShadows===h&&E.numSpotMaps===_&&E.numLightProbes===v||(a.directional.length=l,a.spot.length=d,a.rectArea.length=u,a.point.length=c,a.hemi.length=f,a.directionalShadow.length=p,a.directionalShadowMap.length=p,a.pointShadow.length=m,a.pointShadowMap.length=m,a.spotShadow.length=h,a.spotShadowMap.length=h,a.directionalShadowMatrix.length=p,a.pointShadowMatrix.length=m,a.spotLightMatrix.length=h+_-g,a.spotLightMap.length=_,a.numSpotLightShadowsWithMaps=g,a.numLightProbes=v,E.directionalLength=l,E.pointLength=c,E.spotLength=d,E.rectAreaLength=u,E.hemiLength=f,E.numDirectionalShadows=p,E.numPointShadows=m,E.numSpotShadows=h,E.numSpotMaps=_,E.numLightProbes=v,a.version=Ki++)},setupView:function(e,t){let n=0,r=0,i=0,c=0,d=0;const u=t.matrixWorldInverse;for(let t=0,f=e.length;t=i.length?(a=new Zi(e),i.push(a)):a=i[r],a},dispose:function(){t=new WeakMap}}}function Qi(e,n,r){let i=new ge;const a=new t,s=new t,d=new k,u=new ve({depthPacking:Ee}),f=new Se,p={},m=r.maxTextureSize,h={[_]:c,[c]:_,[fe]:fe},g=new l({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new t},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),v=g.clone();v.defines.HORIZONTAL_PASS=1;const E=new N;E.setAttribute("position",new O(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const S=new o(E,g),T=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=$;let M=this.type;function x(t,r){const i=n.update(S);g.defines.VSM_SAMPLES!==t.blurSamples&&(g.defines.VSM_SAMPLES=t.blurSamples,v.defines.VSM_SAMPLES=t.blurSamples,g.needsUpdate=!0,v.needsUpdate=!0),null===t.mapPass&&(t.mapPass=new I(a.x,a.y)),g.uniforms.shadow_pass.value=t.map.texture,g.uniforms.resolution.value=t.mapSize,g.uniforms.radius.value=t.radius,e.setRenderTarget(t.mapPass),e.clear(),e.renderBufferDirect(r,null,i,g,S,null),v.uniforms.shadow_pass.value=t.mapPass.texture,v.uniforms.resolution.value=t.mapSize,v.uniforms.radius.value=t.radius,e.setRenderTarget(t.map),e.clear(),e.renderBufferDirect(r,null,i,v,S,null)}function R(t,n,r,i){let a=null;const o=!0===r.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==o)a=o;else if(a=!0===r.isPointLight?f:u,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=a.uuid,t=n.uuid;let r=p[e];void 0===r&&(r={},p[e]=r);let i=r[t];void 0===i&&(i=a.clone(),r[t]=i,n.addEventListener("dispose",b)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,a.side=i===J?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],a.alphaMap=n.alphaMap,a.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,!0===r.isPointLight&&!0===a.isMeshDistanceMaterial){e.properties.get(a).light=r}return a}function A(t,r,a,o,s){if(!1===t.visible)return;if(t.layers.test(r.layers)&&(t.isMesh||t.isLine||t.isPoints)&&(t.castShadow||t.receiveShadow&&s===J)&&(!t.frustumCulled||i.intersectsObject(t))){t.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,t.matrixWorld);const i=n.update(t),l=t.material;if(Array.isArray(l)){const n=i.groups;for(let c=0,d=n.length;cm||a.y>m)&&(a.x>m&&(s.x=Math.floor(m/h.x),a.x=s.x*h.x,c.mapSize.x=s.x),a.y>m&&(s.y=Math.floor(m/h.y),a.y=s.y*h.y,c.mapSize.y=s.y)),null===c.map||!0===f||!0===p){const e=this.type!==J?{minFilter:Te,magFilter:Te}:{};null!==c.map&&c.map.dispose(),c.map=new I(a.x,a.y,e),c.map.texture.name=l.name+".shadowMap",c.camera.updateProjectionMatrix()}e.setRenderTarget(c.map),e.clear();const _=c.getViewportCount();for(let e=0;e<_;e++){const t=c.getViewport(e);d.set(s.x*t.x,s.y*t.y,s.x*t.z,s.y*t.w),u.viewport(d),c.updateMatrices(l,e),i=c.getFrustum(),A(n,r,c.camera,l,this.type)}!0!==c.isPointLightShadow&&this.type===J&&x(c,r),c.needsUpdate=!1}M=this.type,T.needsUpdate=!1,e.setRenderTarget(o,l,c)}}const Ji={[Ke]:Ye,[Xe]:ze,[We]:Ve,[Me]:ke,[Ye]:Ke,[ze]:Xe,[Ve]:We,[ke]:Me};function ea(e,t){const r=new function(){let t=!1;const n=new k;let r=null;const i=new k(0,0,0,0);return{setMask:function(n){r===n||t||(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){!0===s&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),!1===i.equals(n)&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}},i=new function(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){const n=t.get("EXT_clip_control");e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;const i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?W(e.DEPTH_TEST):X(e.DEPTH_TEST)},setMask:function(t){i===t||n||(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Ji[t]),a!==t){switch(t){case Ke:e.depthFunc(e.NEVER);break;case Ye:e.depthFunc(e.ALWAYS);break;case Xe:e.depthFunc(e.LESS);break;case Me:e.depthFunc(e.LEQUAL);break;case We:e.depthFunc(e.EQUAL);break;case ke:e.depthFunc(e.GEQUAL);break;case ze:e.depthFunc(e.GREATER);break;case Ve:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(r&&(t=1-t),e.clearDepth(t),o=t)},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}},a=new function(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,l=null,c=null;return{setTest:function(n){t||(n?W(e.STENCIL_TEST):X(e.STENCIL_TEST))},setMask:function(r){n===r||t||(e.stencilMask(r),n=r)},setFunc:function(t,n,o){r===t&&i===n&&a===o||(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){o===t&&s===n&&l===r||(e.stencilOp(t,n,r),o=t,s=n,l=r)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,l=null,c=null}}},o=new WeakMap,s=new WeakMap;let l={},d={},u=new WeakMap,f=[],p=null,m=!1,h=null,_=null,g=null,v=null,E=null,S=null,T=null,M=new n(0,0,0),x=0,R=!1,A=null,b=null,C=null,L=null,P=null;const U=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let D=!1,w=0;const I=e.getParameter(e.VERSION);-1!==I.indexOf("WebGL")?(w=parseFloat(/^WebGL (\d)/.exec(I)[1]),D=w>=1):-1!==I.indexOf("OpenGL ES")&&(w=parseFloat(/^OpenGL ES (\d)/.exec(I)[1]),D=w>=2);let N=null,O={};const F=e.getParameter(e.SCISSOR_BOX),B=e.getParameter(e.VIEWPORT),H=(new k).fromArray(F),G=(new k).fromArray(B);function V(t,n,r,i){const a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;on||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(r*i.width),a=Math.floor(r*i.height);void 0===f&&(f=g(n,a));const o=t?g(n,a):f;o.width=n,o.height=a;return o.getContext("2d").drawImage(e,0,0,n,a),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+i.width+"x"+i.height+") to ("+n+"x"+a+")."),o}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+i.width+"x"+i.height+")."),e}return e}function E(e){return e.generateMipmaps}function x(t){e.generateMipmap(t)}function R(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function A(t,r,i,a,o=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+t+"'")}let s=r;if(r===e.RED&&(i===e.FLOAT&&(s=e.R32F),i===e.HALF_FLOAT&&(s=e.R16F),i===e.UNSIGNED_BYTE&&(s=e.R8)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.R8UI),i===e.UNSIGNED_SHORT&&(s=e.R16UI),i===e.UNSIGNED_INT&&(s=e.R32UI),i===e.BYTE&&(s=e.R8I),i===e.SHORT&&(s=e.R16I),i===e.INT&&(s=e.R32I)),r===e.RG&&(i===e.FLOAT&&(s=e.RG32F),i===e.HALF_FLOAT&&(s=e.RG16F),i===e.UNSIGNED_BYTE&&(s=e.RG8)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RG8UI),i===e.UNSIGNED_SHORT&&(s=e.RG16UI),i===e.UNSIGNED_INT&&(s=e.RG32UI),i===e.BYTE&&(s=e.RG8I),i===e.SHORT&&(s=e.RG16I),i===e.INT&&(s=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGB8UI),i===e.UNSIGNED_SHORT&&(s=e.RGB16UI),i===e.UNSIGNED_INT&&(s=e.RGB32UI),i===e.BYTE&&(s=e.RGB8I),i===e.SHORT&&(s=e.RGB16I),i===e.INT&&(s=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(s=e.RGBA16UI),i===e.UNSIGNED_INT&&(s=e.RGBA32UI),i===e.BYTE&&(s=e.RGBA8I),i===e.SHORT&&(s=e.RGBA16I),i===e.INT&&(s=e.RGBA32I)),r===e.RGB&&i===e.UNSIGNED_INT_5_9_9_9_REV&&(s=e.RGB9_E5),r===e.RGBA){const t=o?se:p.getTransfer(a);i===e.FLOAT&&(s=e.RGBA32F),i===e.HALF_FLOAT&&(s=e.RGBA16F),i===e.UNSIGNED_BYTE&&(s=t===m?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT_4_4_4_4&&(s=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(s=e.RGB5_A1)}return s!==e.R16F&&s!==e.R32F&&s!==e.RG16F&&s!==e.RG32F&&s!==e.RGBA16F&&s!==e.RGBA32F||n.get("EXT_color_buffer_float"),s}function b(t,n){let r;return t?null===n||n===Tt||n===Mt?r=e.DEPTH24_STENCIL8:n===T?r=e.DEPTH32F_STENCIL8:n===xt&&(r=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===Tt||n===Mt?r=e.DEPTH_COMPONENT24:n===T?r=e.DEPTH_COMPONENT32F:n===xt&&(r=e.DEPTH_COMPONENT16),r}function C(e,t){return!0===E(e)||e.isFramebufferTexture&&e.minFilter!==Te&&e.minFilter!==B?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function L(e){const t=e.target;t.removeEventListener("dispose",L),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=h.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&U(e),0===Object.keys(r).length&&h.delete(n)}i.remove(e)}(t),t.isVideoTexture&&u.delete(t)}function P(t){const n=t.target;n.removeEventListener("dispose",P),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r0&&a.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void V(a,t,n);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}r.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+n)}const y={[at]:e.REPEAT,[it]:e.CLAMP_TO_EDGE,[rt]:e.MIRRORED_REPEAT},I={[Te]:e.NEAREST,[ct]:e.NEAREST_MIPMAP_NEAREST,[lt]:e.NEAREST_MIPMAP_LINEAR,[B]:e.LINEAR,[st]:e.LINEAR_MIPMAP_NEAREST,[ot]:e.LINEAR_MIPMAP_LINEAR},N={[_t]:e.NEVER,[ht]:e.ALWAYS,[mt]:e.LESS,[K]:e.LEQUAL,[pt]:e.EQUAL,[ft]:e.GEQUAL,[ut]:e.GREATER,[dt]:e.NOTEQUAL};function O(t,r){if(r.type!==T||!1!==n.has("OES_texture_float_linear")||r.magFilter!==B&&r.magFilter!==st&&r.magFilter!==lt&&r.magFilter!==ot&&r.minFilter!==B&&r.minFilter!==st&&r.minFilter!==lt&&r.minFilter!==ot||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(t,e.TEXTURE_WRAP_S,y[r.wrapS]),e.texParameteri(t,e.TEXTURE_WRAP_T,y[r.wrapT]),t!==e.TEXTURE_3D&&t!==e.TEXTURE_2D_ARRAY||e.texParameteri(t,e.TEXTURE_WRAP_R,y[r.wrapR]),e.texParameteri(t,e.TEXTURE_MAG_FILTER,I[r.magFilter]),e.texParameteri(t,e.TEXTURE_MIN_FILTER,I[r.minFilter]),r.compareFunction&&(e.texParameteri(t,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(t,e.TEXTURE_COMPARE_FUNC,N[r.compareFunction])),!0===n.has("EXT_texture_filter_anisotropic")){if(r.magFilter===Te)return;if(r.minFilter!==lt&&r.minFilter!==ot)return;if(r.type===T&&!1===n.has("OES_texture_float_linear"))return;if(r.anisotropy>1||i.get(r).__currentAnisotropy){const o=n.get("EXT_texture_filter_anisotropic");e.texParameterf(t,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r.anisotropy,a.getMaxAnisotropy())),i.get(r).__currentAnisotropy=r.anisotropy}}}function H(t,n){let r=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",L));const i=n.source;let a=h.get(i);void 0===a&&(a={},h.set(i,a));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===a[o]&&(a[o]={texture:e.createTexture(),usedTimes:0},s.memory.textures++,r=!0),a[o].usedTimes++;const i=a[t.__cacheKey];void 0!==i&&(a[t.__cacheKey].usedTimes--,0===i.usedTimes&&U(n)),t.__cacheKey=o,t.__webglTexture=a[o].texture}return r}function G(e,t,n){return Math.floor(Math.floor(e/n)/t)}function V(t,n,s){let l=e.TEXTURE_2D;(n.isDataArrayTexture||n.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),n.isData3DTexture&&(l=e.TEXTURE_3D);const c=H(t,n),d=n.source;r.bindTexture(l,t.__webglTexture,e.TEXTURE0+s);const u=i.get(d);if(d.version!==u.__version||!0===c){r.activeTexture(e.TEXTURE0+s);const t=p.getPrimaries(p.workingColorSpace),i=n.colorSpace===gt?null:p.getPrimaries(n.colorSpace),f=n.colorSpace===gt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,n.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,f);let m=v(n.image,!1,a.maxTextureSize);m=$(n,m);const h=o.convert(n.format,n.colorSpace),_=o.convert(n.type);let g,S=A(n.internalFormat,h,_,n.colorSpace,n.isVideoTexture);O(l,n);const T=n.mipmaps,R=!0!==n.isVideoTexture,L=void 0===u.__version||!0===c,P=d.dataReady,U=C(n,m);if(n.isDepthTexture)S=b(n.format===vt,n.type),L&&(R?r.texStorage2D(e.TEXTURE_2D,1,S,m.width,m.height):r.texImage2D(e.TEXTURE_2D,0,S,m.width,m.height,0,h,_,null));else if(n.isDataTexture)if(T.length>0){R&&L&&r.texStorage2D(e.TEXTURE_2D,U,S,T[0].width,T[0].height);for(let t=0,n=T.length;te.start-t.start));let s=0;for(let e=1;e0){const i=Et(g.width,g.height,n.format,n.type);for(const a of n.layerUpdates){const n=g.data.subarray(a*i/g.data.BYTES_PER_ELEMENT,(a+1)*i/g.data.BYTES_PER_ELEMENT);r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,a,g.width,g.height,1,h,n)}n.clearLayerUpdates()}else r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,g.width,g.height,m.depth,h,g.data)}else r.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,S,g.width,g.height,m.depth,0,g.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else R?P&&r.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,g.width,g.height,m.depth,h,_,g.data):r.texImage3D(e.TEXTURE_2D_ARRAY,t,S,g.width,g.height,m.depth,0,h,_,g.data)}else{R&&L&&r.texStorage2D(e.TEXTURE_2D,U,S,T[0].width,T[0].height);for(let t=0,i=T.length;t0){const t=Et(m.width,m.height,n.format,n.type);for(const i of n.layerUpdates){const n=m.data.subarray(i*t/m.data.BYTES_PER_ELEMENT,(i+1)*t/m.data.BYTES_PER_ELEMENT);r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,m.width,m.height,1,h,_,n)}n.clearLayerUpdates()}else r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,m.width,m.height,m.depth,h,_,m.data)}else r.texImage3D(e.TEXTURE_2D_ARRAY,0,S,m.width,m.height,m.depth,0,h,_,m.data);else if(n.isData3DTexture)R?(L&&r.texStorage3D(e.TEXTURE_3D,U,S,m.width,m.height,m.depth),P&&r.texSubImage3D(e.TEXTURE_3D,0,0,0,0,m.width,m.height,m.depth,h,_,m.data)):r.texImage3D(e.TEXTURE_3D,0,S,m.width,m.height,m.depth,0,h,_,m.data);else if(n.isFramebufferTexture){if(L)if(R)r.texStorage2D(e.TEXTURE_2D,U,S,m.width,m.height);else{let t=m.width,n=m.height;for(let i=0;i>=1,n>>=1}}else if(T.length>0){if(R&&L){const t=Q(T[0]);r.texStorage2D(e.TEXTURE_2D,U,S,t.width,t.height)}for(let t=0,n=T.length;t>d),i=Math.max(1,n.height>>d);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?r.texImage3D(c,d,p,t,i,n.depth,0,u,f,null):r.texImage2D(c,d,p,t,i,0,u,f,null)}r.bindFramebuffer(e.FRAMEBUFFER,t),Z(n)?l.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,s,c,h.__webglTexture,0,q(n)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,s,c,h.__webglTexture,d),r.bindFramebuffer(e.FRAMEBUFFER,null)}function k(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=b(n.stencilBuffer,a),s=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=q(n);Z(n)?l.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,c,o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,c,o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,s,e.RENDERBUFFER,t)}else{const t=n.textures;for(let i=0;i{delete n.__boundDepthTexture,delete n.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),n.__depthDisposeCallback=t}n.__boundDepthTexture=e}if(t.depthTexture&&!n.__autoAllocateDepthBuffer){if(a)throw new Error("target.depthTexture not supported in Cube render targets");const e=t.texture.mipmaps;e&&e.length>0?W(n.__webglFramebuffer[0],t):W(n.__webglFramebuffer,t)}else if(a){n.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(r.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[i]),void 0===n.__webglDepthbuffer[i])n.__webglDepthbuffer[i]=e.createRenderbuffer(),k(n.__webglDepthbuffer[i],t,!1);else{const r=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=n.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,r,e.RENDERBUFFER,a)}}else{const i=t.texture.mipmaps;if(i&&i.length>0?r.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[0]):r.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer),void 0===n.__webglDepthbuffer)n.__webglDepthbuffer=e.createRenderbuffer(),k(n.__webglDepthbuffer,t,!1);else{const r=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=n.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,r,e.RENDERBUFFER,i)}}r.bindFramebuffer(e.FRAMEBUFFER,null)}const Y=[],j=[];function q(e){return Math.min(a.maxSamples,e.samples)}function Z(e){const t=i.get(e);return e.samples>0&&!0===n.has("WEBGL_multisampled_render_to_texture")&&!1!==t.__useRenderToTexture}function $(e,t){const n=e.colorSpace,r=e.format,i=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==F&&n!==gt&&(p.getTransfer(n)===m?r===M&&i===S||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),t}function Q(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(d.width=e.naturalWidth||e.width,d.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(d.width=e.displayWidth,d.height=e.displayHeight):(d.width=e.width,d.height=e.height),d}this.allocateTextureUnit=function(){const e=D;return e>=a.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+a.maxTextures),D+=1,e},this.resetTextureUnits=function(){D=0},this.setTexture2D=w,this.setTexture2DArray=function(t,n){const a=i.get(t);t.version>0&&a.__version!==t.version?V(a,t,n):r.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+n)},this.setTexture3D=function(t,n){const a=i.get(t);t.version>0&&a.__version!==t.version?V(a,t,n):r.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+n)},this.setTextureCube=function(t,n){const s=i.get(t);t.version>0&&s.__version!==t.version?function(t,n,s){if(6!==n.image.length)return;const l=H(t,n),c=n.source;r.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);const d=i.get(c);if(c.version!==d.__version||!0===l){r.activeTexture(e.TEXTURE0+s);const t=p.getPrimaries(p.workingColorSpace),i=n.colorSpace===gt?null:p.getPrimaries(n.colorSpace),u=n.colorSpace===gt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,n.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const f=n.isCompressedTexture||n.image[0].isCompressedTexture,m=n.image[0]&&n.image[0].isDataTexture,h=[];for(let e=0;e<6;e++)h[e]=f||m?m?n.image[e].image:n.image[e]:v(n.image[e],!0,a.maxCubemapSize),h[e]=$(n,h[e]);const _=h[0],g=o.convert(n.format,n.colorSpace),S=o.convert(n.type),T=A(n.internalFormat,g,S,n.colorSpace),R=!0!==n.isVideoTexture,b=void 0===d.__version||!0===l,L=c.dataReady;let P,U=C(n,_);if(O(e.TEXTURE_CUBE_MAP,n),f){R&&b&&r.texStorage2D(e.TEXTURE_CUBE_MAP,U,T,_.width,_.height);for(let t=0;t<6;t++){P=h[t].mipmaps;for(let i=0;i0&&U++;const t=Q(h[0]);r.texStorage2D(e.TEXTURE_CUBE_MAP,U,T,t.width,t.height)}for(let t=0;t<6;t++)if(m){R?L&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,h[t].width,h[t].height,g,S,h[t].data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,T,h[t].width,h[t].height,0,g,S,h[t].data);for(let n=0;n1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=n.version,s.memory.textures++),d){a.__webglFramebuffer=[];for(let t=0;t<6;t++)if(n.mipmaps&&n.mipmaps.length>0){a.__webglFramebuffer[t]=[];for(let r=0;r0){a.__webglFramebuffer=[];for(let t=0;t0&&!1===Z(t)){a.__webglMultisampledFramebuffer=e.createFramebuffer(),a.__webglColorRenderbuffer=[],r.bindFramebuffer(e.FRAMEBUFFER,a.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let r=0;r0)if(!1===Z(t)){const n=t.textures,a=t.width,o=t.height;let s=e.COLOR_BUFFER_BIT;const l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,d=i.get(t),u=n.length>1;if(u)for(let t=0;t0?r.bindFramebuffer(e.DRAW_FRAMEBUFFER,d.__webglFramebuffer[0]):r.bindFramebuffer(e.DRAW_FRAMEBUFFER,d.__webglFramebuffer);for(let r=0;r= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new o(new h(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class ia extends _n{constructor(e,n){super();const r=this;let a=null,o=1,s=null,l="local-floor",c=1,d=null,u=null,f=null,p=null,m=null,h=null;const _=new ra,g=n.getContextAttributes();let v=null,E=null;const T=[],x=[],R=new t;let A=null;const b=new U;b.viewport=new k;const C=new U;C.viewport=new k;const L=[b,C],P=new gn;let D=null,w=null;function y(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=T[t];void 0!==n&&(n.update(e.inputSource,e.frame,d||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function N(){a.removeEventListener("select",y),a.removeEventListener("selectstart",y),a.removeEventListener("selectend",y),a.removeEventListener("squeeze",y),a.removeEventListener("squeezestart",y),a.removeEventListener("squeezeend",y),a.removeEventListener("end",N),a.removeEventListener("inputsourceschange",O);for(let e=0;e=0&&(x[r]=null,T[r].disconnect(n))}for(let t=0;t=x.length){x.push(n),r=e;break}if(null===x[e]){x[e]=n,r=e;break}}if(-1===r)break}const i=T[r];i&&i.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=T[e];return void 0===t&&(t=new vn,T[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=T[e];return void 0===t&&(t=new vn,T[e]=t),t.getGripSpace()},this.getHand=function(e){let t=T[e];return void 0===t&&(t=new vn,T[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){o=e,!0===r.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){l=e,!0===r.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||s},this.setReferenceSpace=function(e){d=e},this.getBaseLayer=function(){return null!==p?p:m},this.getBinding=function(){return f},this.getFrame=function(){return h},this.getSession=function(){return a},this.setSession=async function(t){if(a=t,null!==a){v=e.getRenderTarget(),a.addEventListener("select",y),a.addEventListener("selectstart",y),a.addEventListener("selectend",y),a.addEventListener("squeeze",y),a.addEventListener("squeezestart",y),a.addEventListener("squeezeend",y),a.addEventListener("end",N),a.addEventListener("inputsourceschange",O),!0!==g.xrCompatible&&await n.makeXRCompatible(),A=e.getPixelRatio(),e.getSize(R);if("undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype){let t=null,r=null,i=null;g.depth&&(i=g.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,t=g.stencil?vt:St,r=g.stencil?Mt:Tt);const s={colorFormat:n.RGBA8,depthFormat:i,scaleFactor:o};f=new XRWebGLBinding(a,n),p=f.createProjectionLayer(s),a.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),E=new I(p.textureWidth,p.textureHeight,{format:M,type:S,depthTexture:new j(p.textureWidth,p.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,t),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:!1===p.ignoreDepthValues,resolveStencilBuffer:!1===p.ignoreDepthValues})}else{const t={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:o};m=new XRWebGLLayer(a,n,t),a.updateRenderState({baseLayer:m}),e.setPixelRatio(1),e.setSize(m.framebufferWidth,m.framebufferHeight,!1),E=new I(m.framebufferWidth,m.framebufferHeight,{format:M,type:S,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil,resolveDepthBuffer:!1===m.ignoreDepthValues,resolveStencilBuffer:!1===m.ignoreDepthValues})}E.isXRRenderTarget=!0,this.setFoveation(c),d=null,s=await a.requestReferenceSpace(l),V.setContext(a),V.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==a)return a.environmentBlendMode},this.getDepthTexture=function(){return _.getDepthTexture()};const F=new i,B=new i;function H(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===a)return;let t=e.near,n=e.far;null!==_.texture&&(_.depthNear>0&&(t=_.depthNear),_.depthFar>0&&(n=_.depthFar)),P.near=C.near=b.near=t,P.far=C.far=b.far=n,D===P.near&&w===P.far||(a.updateRenderState({depthNear:P.near,depthFar:P.far}),D=P.near,w=P.far),b.layers.mask=2|e.layers.mask,C.layers.mask=4|e.layers.mask,P.layers.mask=b.layers.mask|C.layers.mask;const r=e.parent,i=P.cameras;H(P,r);for(let e=0;e0&&(e.alphaTest.value=r.alphaTest);const i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,aa.copy(o),aa.x*=-1,aa.y*=-1,aa.z*=-1,a.isCubeTexture&&!1===a.isRenderTargetTexture&&(aa.y*=-1,aa.z*=-1),e.envMapRotation.value.setFromMatrix4(oa.makeRotationFromEuler(aa)),e.flipEnvMap.value=a.isCubeTexture&&!1===a.isRenderTargetTexture?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,g(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,i,a,o,s){i.isMeshBasicMaterial||i.isMeshLambertMaterial?r(e,i):i.isMeshToonMaterial?(r(e,i),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,i)):i.isMeshPhongMaterial?(r(e,i),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,i)):i.isMeshStandardMaterial?(r(e,i),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,i),i.isMeshPhysicalMaterial&&function(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===c&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,i,s)):i.isMeshMatcapMaterial?(r(e,i),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,i)):i.isMeshDepthMaterial?r(e,i):i.isMeshDistanceMaterial?(r(e,i),function(e,n){const r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}(e,i)):i.isMeshNormalMaterial?r(e,i):i.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,i),i.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,i)):i.isPointsMaterial?function(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=.5*i,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i,a,o):i.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i):i.isShadowMaterial?(e.color.value.copy(i.color),e.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1)}}}function la(e,t,n,r){let i={},a={},o=[];const s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,r){const i=e.value,a=t+"_"+n;if(void 0===r[a])return r[a]="number"==typeof i||"boolean"==typeof i?i:i.clone(),!0;{const e=r[a];if("number"==typeof i||"boolean"==typeof i){if(e!==i)return r[a]=i,!0}else if(!1===e.equals(i))return e.copy(i),!0}return!1}function c(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",e),t}function d(t){const n=t.target;n.removeEventListener("dispose",d);const r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}return{bind:function(e,t){const n=t.program;r.uniformBlockBinding(e,n)},update:function(n,u){let f=i[n.id];void 0===f&&(!function(e){const t=e.uniforms;let n=0;const r=16;for(let e=0,i=t.length;e0&&(n+=r-i);e.__size=n,e.__cache={}}(n),f=function(t){const n=function(){for(let e=0;e0),u=!!n.morphAttributes.position,f=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=D;r.toneMapped&&(null!==w&&!0!==w.isXRRenderTarget||(m=C.toneMapping));const h=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=void 0!==h?h.length:0,g=pe.get(r),v=R.state.lights;if(!0===J&&(!0===ee||e!==N)){const t=e===N&&r.id===y;Ae.setState(r,e,t)}let E=!1;r.version===g.__version?g.needsLights&&g.lightsStateVersion!==v.state.version||g.outputColorSpace!==s||i.isBatchedMesh&&!1===g.batching?E=!0:i.isBatchedMesh||!0!==g.batching?i.isBatchedMesh&&!0===g.batchingColor&&null===i.colorTexture||i.isBatchedMesh&&!1===g.batchingColor&&null!==i.colorTexture||i.isInstancedMesh&&!1===g.instancing?E=!0:i.isInstancedMesh||!0!==g.instancing?i.isSkinnedMesh&&!1===g.skinning?E=!0:i.isSkinnedMesh||!0!==g.skinning?i.isInstancedMesh&&!0===g.instancingColor&&null===i.instanceColor||i.isInstancedMesh&&!1===g.instancingColor&&null!==i.instanceColor||i.isInstancedMesh&&!0===g.instancingMorph&&null===i.morphTexture||i.isInstancedMesh&&!1===g.instancingMorph&&null!==i.morphTexture||g.envMap!==l||!0===r.fog&&g.fog!==a?E=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===Ae.numPlanes&&g.numIntersection===Ae.numIntersection?(g.vertexAlphas!==c||g.vertexTangents!==d||g.morphTargets!==u||g.morphNormals!==f||g.morphColors!==p||g.toneMapping!==m||g.morphTargetsCount!==_)&&(E=!0):E=!0:E=!0:E=!0:E=!0:(E=!0,g.__version=r.version);let S=g.currentProgram;!0===E&&(S=Qe(r,t,i));let T=!1,M=!1,x=!1;const A=S.getUniforms(),b=g.uniforms;de.useProgram(S.program)&&(T=!0,M=!0,x=!0);r.id!==y&&(y=r.id,M=!0);if(T||N!==e){de.buffers.depth.getReversed()?(te.copy(e.projectionMatrix),xn(te),Rn(te),A.setValue(Ie,"projectionMatrix",te)):A.setValue(Ie,"projectionMatrix",e.projectionMatrix),A.setValue(Ie,"viewMatrix",e.matrixWorldInverse);const t=A.map.cameraPosition;void 0!==t&&t.setValue(Ie,re.setFromMatrixPosition(e.matrixWorld)),ce.logarithmicDepthBuffer&&A.setValue(Ie,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&A.setValue(Ie,"isOrthographic",!0===e.isOrthographicCamera),N!==e&&(N=e,M=!0,x=!0)}if(i.isSkinnedMesh){A.setOptional(Ie,i,"bindMatrix"),A.setOptional(Ie,i,"bindMatrixInverse");const e=i.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),A.setValue(Ie,"boneTexture",e.boneTexture,me))}i.isBatchedMesh&&(A.setOptional(Ie,i,"batchingTexture"),A.setValue(Ie,"batchingTexture",i._matricesTexture,me),A.setOptional(Ie,i,"batchingIdTexture"),A.setValue(Ie,"batchingIdTexture",i._indirectTexture,me),A.setOptional(Ie,i,"batchingColorTexture"),null!==i._colorsTexture&&A.setValue(Ie,"batchingColorTexture",i._colorsTexture,me));const L=n.morphAttributes;void 0===L.position&&void 0===L.normal&&void 0===L.color||Le.update(i,n,S);(M||g.receiveShadow!==i.receiveShadow)&&(g.receiveShadow=i.receiveShadow,A.setValue(Ie,"receiveShadow",i.receiveShadow));r.isMeshGouraudMaterial&&null!==r.envMap&&(b.envMap.value=l,b.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);r.isMeshStandardMaterial&&null===r.envMap&&null!==t.environment&&(b.envMapIntensity.value=t.environmentIntensity);M&&(A.setValue(Ie,"toneMappingExposure",C.toneMappingExposure),g.needsLights&&(U=x,(P=b).ambientLightColor.needsUpdate=U,P.lightProbe.needsUpdate=U,P.directionalLights.needsUpdate=U,P.directionalLightShadows.needsUpdate=U,P.pointLights.needsUpdate=U,P.pointLightShadows.needsUpdate=U,P.spotLights.needsUpdate=U,P.spotLightShadows.needsUpdate=U,P.rectAreaLights.needsUpdate=U,P.hemisphereLights.needsUpdate=U),a&&!0===r.fog&&Me.refreshFogUniforms(b,a),Me.refreshMaterialUniforms(b,r,Y,X,R.state.transmissionRenderTarget[e.id]),_i.upload(Ie,Je(g),b,me));var P,U;r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(_i.upload(Ie,Je(g),b,me),r.uniformsNeedUpdate=!1);r.isSpriteMaterial&&A.setValue(Ie,"center",i.center);if(A.setValue(Ie,"modelViewMatrix",i.modelViewMatrix),A.setValue(Ie,"normalMatrix",i.normalMatrix),A.setValue(Ie,"modelMatrix",i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){const e=r.uniformsGroups;for(let t=0,n=e.length;t{function n(){r.forEach((function(e){pe.get(e).currentProgram.isReady()&&r.delete(e)})),0!==r.size?setTimeout(n,10):t(e)}null!==le.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let ke=null;function We(){Ye.stop()}function Xe(){Ye.start()}const Ye=new Cn;function Ke(e,t,n,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)R.pushLight(e),e.castShadow&&R.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||Q.intersectsSprite(e)){r&&ie.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ne);const t=Se.update(e),i=e.material;i.visible&&x.push(e,t,i,n,ie.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||Q.intersectsObject(e))){const t=Se.update(e),i=e.material;if(r&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),ie.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),ie.copy(t.boundingSphere.center)),ie.applyMatrix4(e.matrixWorld).applyMatrix4(ne)),Array.isArray(i)){const r=t.groups;for(let a=0,o=r.length;a0&&Ze(i,t,n),a.length>0&&Ze(a,t,n),o.length>0&&Ze(o,t,n),de.buffers.depth.setTest(!0),de.buffers.depth.setMask(!0),de.buffers.color.setMask(!0),de.setPolygonOffset(!1)}function qe(e,t,n,r){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===R.state.transmissionRenderTarget[r.id]&&(R.state.transmissionRenderTarget[r.id]=new I(1,1,{generateMipmaps:!0,type:le.has("EXT_color_buffer_half_float")||le.has("EXT_color_buffer_float")?E:S,minFilter:ot,samples:4,stencilBuffer:o,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:p.workingColorSpace}));const i=R.state.transmissionRenderTarget[r.id],a=r.viewport||O;i.setSize(a.z*C.transmissionResolutionScale,a.w*C.transmissionResolutionScale);const s=C.getRenderTarget();C.setRenderTarget(i),C.getClearColor(V),z=C.getClearAlpha(),z<1&&C.setClearColor(16777215,.5),C.clear(),oe&&Ce.render(n);const l=C.toneMapping;C.toneMapping=D;const d=r.viewport;if(void 0!==r.viewport&&(r.viewport=void 0),R.setupLightsView(r),!0===J&&Ae.setGlobalState(C.clippingPlanes,r),Ze(e,n,r),me.updateMultisampleRenderTarget(i),me.updateRenderTargetMipmap(i),!1===le.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let i=0,a=t.length;i0)for(let t=0,a=n.length;t0&&qe(r,i,e,t),oe&&Ce.render(e),je(x,e,t);null!==w&&0===U&&(me.updateMultisampleRenderTarget(w),me.updateRenderTargetMipmap(w)),!0===e.isScene&&e.onAfterRender(C,e,t),we.resetDefaultState(),y=-1,N=null,b.pop(),b.length>0?(R=b[b.length-1],!0===J&&Ae.setGlobalState(C.clippingPlanes,R.state.camera)):R=null,A.pop(),x=A.length>0?A[A.length-1]:null},this.getActiveCubeFace=function(){return P},this.getActiveMipmapLevel=function(){return U},this.getRenderTarget=function(){return w},this.setRenderTargetTextures=function(e,t,n){const r=pe.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),pe.get(e.texture).__webglTexture=t,pe.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=pe.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const tt=Ie.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){w=e,P=t,U=n;let r=!0,i=null,a=!1,o=!1;if(e){const s=pe.get(e);if(void 0!==s.__useDefaultFramebuffer)de.bindFramebuffer(Ie.FRAMEBUFFER,null),r=!1;else if(void 0===s.__webglFramebuffer)me.setupRenderTarget(e);else if(s.__hasExternalTextures)me.rebindTextures(e,pe.get(e.texture).__webglTexture,pe.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(s.__boundDepthTexture!==t){if(null!==t&&pe.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");me.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(o=!0);const c=pe.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(c[t])?c[t][n]:c[t],a=!0):i=e.samples>0&&!1===me.useMultisampledRTT(e)?pe.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,O.copy(e.viewport),B.copy(e.scissor),G=e.scissorTest}else O.copy(q).multiplyScalar(Y).floor(),B.copy(Z).multiplyScalar(Y).floor(),G=$;0!==n&&(i=tt);if(de.bindFramebuffer(Ie.FRAMEBUFFER,i)&&r&&de.drawBuffers(e,i),de.viewport(O),de.scissor(B),de.setScissorTest(G),a){const r=pe.get(e.texture);Ie.framebufferTexture2D(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,Ie.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(o){const r=pe.get(e.texture),i=t;Ie.framebufferTextureLayer(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,r.__webglTexture,n,i)}else if(null!==e&&0!==n){const t=pe.get(e.texture);Ie.framebufferTexture2D(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,Ie.TEXTURE_2D,t.__webglTexture,n)}y=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=pe.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==o&&(l=l[o]),l){de.bindFramebuffer(Ie.FRAMEBUFFER,l);try{const o=e.textures[s],l=o.format,c=o.type;if(!ce.textureFormatReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!ce.textureTypeReadable(c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&Ie.readBuffer(Ie.COLOR_ATTACHMENT0+s),Ie.readPixels(t,n,r,i,De.convert(l),De.convert(c),a))}finally{const e=null!==w?pe.get(w).__webglFramebuffer:null;de.bindFramebuffer(Ie.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=pe.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==o&&(l=l[o]),l){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){de.bindFramebuffer(Ie.FRAMEBUFFER,l);const o=e.textures[s],c=o.format,d=o.type;if(!ce.textureFormatReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ce.textureTypeReadable(d))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const u=Ie.createBuffer();Ie.bindBuffer(Ie.PIXEL_PACK_BUFFER,u),Ie.bufferData(Ie.PIXEL_PACK_BUFFER,a.byteLength,Ie.STREAM_READ),e.textures.length>1&&Ie.readBuffer(Ie.COLOR_ATTACHMENT0+s),Ie.readPixels(t,n,r,i,De.convert(c),De.convert(d),0);const f=null!==w?pe.get(w).__webglFramebuffer:null;de.bindFramebuffer(Ie.FRAMEBUFFER,f);const p=Ie.fenceSync(Ie.SYNC_GPU_COMMANDS_COMPLETE,0);return Ie.flush(),await An(Ie,p,4),Ie.bindBuffer(Ie.PIXEL_PACK_BUFFER,u),Ie.getBufferSubData(Ie.PIXEL_PACK_BUFFER,0,a),Ie.deleteBuffer(u),Ie.deleteSync(p),a}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const r=Math.pow(2,-n),i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=null!==t?t.x:0,s=null!==t?t.y:0;me.setTexture2D(e,0),Ie.copyTexSubImage2D(Ie.TEXTURE_2D,n,0,0,o,s,i,a),de.unbindTexture()};const nt=Ie.createFramebuffer(),rt=Ie.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=null){let o,s,l,c,d,u,f,p,m;null===a&&(0!==i?(H("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),a=i,i=0):a=0);const h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(null!==n)o=n.max.x-n.min.x,s=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,c=n.min.x,d=n.min.y,u=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-i);o=Math.floor(h.width*t),s=Math.floor(h.height*t),l=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,c=0,d=0,u=0}null!==r?(f=r.x,p=r.y,m=r.z):(f=0,p=0,m=0);const _=De.convert(t.format),g=De.convert(t.type);let v;t.isData3DTexture?(me.setTexture3D(t,0),v=Ie.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(me.setTexture2DArray(t,0),v=Ie.TEXTURE_2D_ARRAY):(me.setTexture2D(t,0),v=Ie.TEXTURE_2D),Ie.pixelStorei(Ie.UNPACK_FLIP_Y_WEBGL,t.flipY),Ie.pixelStorei(Ie.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Ie.pixelStorei(Ie.UNPACK_ALIGNMENT,t.unpackAlignment);const E=Ie.getParameter(Ie.UNPACK_ROW_LENGTH),S=Ie.getParameter(Ie.UNPACK_IMAGE_HEIGHT),T=Ie.getParameter(Ie.UNPACK_SKIP_PIXELS),M=Ie.getParameter(Ie.UNPACK_SKIP_ROWS),x=Ie.getParameter(Ie.UNPACK_SKIP_IMAGES);Ie.pixelStorei(Ie.UNPACK_ROW_LENGTH,h.width),Ie.pixelStorei(Ie.UNPACK_IMAGE_HEIGHT,h.height),Ie.pixelStorei(Ie.UNPACK_SKIP_PIXELS,c),Ie.pixelStorei(Ie.UNPACK_SKIP_ROWS,d),Ie.pixelStorei(Ie.UNPACK_SKIP_IMAGES,u);const R=e.isDataArrayTexture||e.isData3DTexture,A=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=pe.get(e),r=pe.get(t),h=pe.get(n.__renderTarget),_=pe.get(r.__renderTarget);de.bindFramebuffer(Ie.READ_FRAMEBUFFER,h.__webglFramebuffer),de.bindFramebuffer(Ie.DRAW_FRAMEBUFFER,_.__webglFramebuffer);for(let n=0;ne.start-t.start));let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},Un={common:{diffuse:{value:new n(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new e},alphaMap:{value:null},alphaMapTransform:{value:new e},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new e}},envmap:{envMap:{value:null},envMapRotation:{value:new e},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new e}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new e}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new e},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new e},normalScale:{value:new t(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new e},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new e}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new e}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new e}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new n(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new n(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new e},alphaTest:{value:0},uvTransform:{value:new e}},sprite:{diffuse:{value:new n(16777215)},opacity:{value:1},center:{value:new t(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new e},alphaMap:{value:null},alphaMapTransform:{value:new e},alphaTest:{value:0}}},Dn={basic:{uniforms:r([Un.common,Un.specularmap,Un.envmap,Un.aomap,Un.lightmap,Un.fog]),vertexShader:Pn.meshbasic_vert,fragmentShader:Pn.meshbasic_frag},lambert:{uniforms:r([Un.common,Un.specularmap,Un.envmap,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.fog,Un.lights,{emissive:{value:new n(0)}}]),vertexShader:Pn.meshlambert_vert,fragmentShader:Pn.meshlambert_frag},phong:{uniforms:r([Un.common,Un.specularmap,Un.envmap,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.fog,Un.lights,{emissive:{value:new n(0)},specular:{value:new n(1118481)},shininess:{value:30}}]),vertexShader:Pn.meshphong_vert,fragmentShader:Pn.meshphong_frag},standard:{uniforms:r([Un.common,Un.envmap,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.roughnessmap,Un.metalnessmap,Un.fog,Un.lights,{emissive:{value:new n(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Pn.meshphysical_vert,fragmentShader:Pn.meshphysical_frag},toon:{uniforms:r([Un.common,Un.aomap,Un.lightmap,Un.emissivemap,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.gradientmap,Un.fog,Un.lights,{emissive:{value:new n(0)}}]),vertexShader:Pn.meshtoon_vert,fragmentShader:Pn.meshtoon_frag},matcap:{uniforms:r([Un.common,Un.bumpmap,Un.normalmap,Un.displacementmap,Un.fog,{matcap:{value:null}}]),vertexShader:Pn.meshmatcap_vert,fragmentShader:Pn.meshmatcap_frag},points:{uniforms:r([Un.points,Un.fog]),vertexShader:Pn.points_vert,fragmentShader:Pn.points_frag},dashed:{uniforms:r([Un.common,Un.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Pn.linedashed_vert,fragmentShader:Pn.linedashed_frag},depth:{uniforms:r([Un.common,Un.displacementmap]),vertexShader:Pn.depth_vert,fragmentShader:Pn.depth_frag},normal:{uniforms:r([Un.common,Un.bumpmap,Un.normalmap,Un.displacementmap,{opacity:{value:1}}]),vertexShader:Pn.meshnormal_vert,fragmentShader:Pn.meshnormal_frag},sprite:{uniforms:r([Un.sprite,Un.fog]),vertexShader:Pn.sprite_vert,fragmentShader:Pn.sprite_frag},background:{uniforms:{uvTransform:{value:new e},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Pn.background_vert,fragmentShader:Pn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new e}},vertexShader:Pn.backgroundCube_vert,fragmentShader:Pn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Pn.cube_vert,fragmentShader:Pn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Pn.equirect_vert,fragmentShader:Pn.equirect_frag},distanceRGBA:{uniforms:r([Un.common,Un.displacementmap,{referencePosition:{value:new i},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Pn.distanceRGBA_vert,fragmentShader:Pn.distanceRGBA_frag},shadow:{uniforms:r([Un.lights,Un.fog,{color:{value:new n(0)},opacity:{value:1}}]),vertexShader:Pn.shadow_vert,fragmentShader:Pn.shadow_frag}};Dn.physical={uniforms:r([Dn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new e},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new e},clearcoatNormalScale:{value:new t(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new e},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new e},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new e},sheen:{value:0},sheenColor:{value:new n(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new e},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new e},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new e},transmissionSamplerSize:{value:new t},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new e},attenuationDistance:{value:0},attenuationColor:{value:new n(0)},specularColor:{value:new n(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new e},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new e},anisotropyVector:{value:new t},anisotropyMap:{value:null},anisotropyMapTransform:{value:new e}}]),vertexShader:Pn.meshphysical_vert,fragmentShader:Pn.meshphysical_frag};const wn={r:0,b:0,g:0},yn=new u,In=new f;function Nn(e,t,r,i,u,f,v){const E=new n(0);let S,T,M=!0===f?0:1,x=null,R=0,A=null;function b(e){let n=!0===e.isScene?e.background:null;if(n&&n.isTexture){n=(e.backgroundBlurriness>0?r:t).get(n)}return n}function C(t,n){t.getRGB(wn,g(e)),i.buffers.color.setClear(wn.r,wn.g,wn.b,n,v)}return{getClearColor:function(){return E},setClearColor:function(e,t=1){E.set(e),M=t,C(E,M)},getClearAlpha:function(){return M},setClearAlpha:function(e){M=e,C(E,M)},render:function(t){let n=!1;const r=b(t);null===r?C(E,M):r&&r.isColor&&(C(r,1),n=!0);const a=e.xr.getEnvironmentBlendMode();"additive"===a?i.buffers.color.setClear(0,0,0,1,v):"alpha-blend"===a&&i.buffers.color.setClear(0,0,0,0,v),(e.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const r=b(n);r&&(r.isCubeTexture||r.mapping===a)?(void 0===T&&(T=new o(new s(1,1,1),new l({name:"BackgroundCubeMaterial",uniforms:d(Dn.backgroundCube.uniforms),vertexShader:Dn.backgroundCube.vertexShader,fragmentShader:Dn.backgroundCube.fragmentShader,side:c,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),T.geometry.deleteAttribute("normal"),T.geometry.deleteAttribute("uv"),T.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(T.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),u.update(T)),yn.copy(n.backgroundRotation),yn.x*=-1,yn.y*=-1,yn.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(yn.y*=-1,yn.z*=-1),T.material.uniforms.envMap.value=r,T.material.uniforms.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,T.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,T.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,T.material.uniforms.backgroundRotation.value.setFromMatrix4(In.makeRotationFromEuler(yn)),T.material.toneMapped=p.getTransfer(r.colorSpace)!==m,x===r&&R===r.version&&A===e.toneMapping||(T.material.needsUpdate=!0,x=r,R=r.version,A=e.toneMapping),T.layers.enableAll(),t.unshift(T,T.geometry,T.material,0,0,null)):r&&r.isTexture&&(void 0===S&&(S=new o(new h(2,2),new l({name:"BackgroundMaterial",uniforms:d(Dn.background.uniforms),vertexShader:Dn.background.vertexShader,fragmentShader:Dn.background.fragmentShader,side:_,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),S.geometry.deleteAttribute("normal"),Object.defineProperty(S.material,"map",{get:function(){return this.uniforms.t2D.value}}),u.update(S)),S.material.uniforms.t2D.value=r,S.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,S.material.toneMapped=p.getTransfer(r.colorSpace)!==m,!0===r.matrixAutoUpdate&&r.updateMatrix(),S.material.uniforms.uvTransform.value.copy(r.matrix),x===r&&R===r.version&&A===e.toneMapping||(S.material.needsUpdate=!0,x=r,R=r.version,A=e.toneMapping),S.layers.enableAll(),t.unshift(S,S.geometry,S.material,0,0,null))},dispose:function(){void 0!==T&&(T.geometry.dispose(),T.material.dispose(),T=void 0),void 0!==S&&(S.geometry.dispose(),S.material.dispose(),S=void 0)}}}function On(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=c(null);let a=i,o=!1;function s(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function c(e){const t=[],r=[],i=[];for(let e=0;e=0){const n=i[t];let r=o[t];if(void 0===r&&("instanceMatrix"===t&&e.instanceMatrix&&(r=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(r=e.instanceColor)),void 0===n)return!0;if(n.attribute!==r)return!0;if(r&&n.data!==r.data)return!0;s++}}return a.attributesNum!==s||a.index!==r}(n,h,l,_),g&&function(e,t,n,r){const i={},o=t.attributes;let s=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=o[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}}a.attributes=i,a.attributesNum=s,a.index=r}(n,h,l,_),null!==_&&t.update(_,e.ELEMENT_ARRAY_BUFFER),(g||o)&&(o=!1,function(n,r,i,a){d();const o=a.attributes,s=i.getAttributes(),l=r.defaultAttributeValues;for(const r in s){const i=s[r];if(i.location>=0){let s=o[r];if(void 0===s&&("instanceMatrix"===r&&n.instanceMatrix&&(s=n.instanceMatrix),"instanceColor"===r&&n.instanceColor&&(s=n.instanceColor)),void 0!==s){const r=s.normalized,o=s.itemSize,l=t.get(s);if(void 0===l)continue;const c=l.buffer,d=l.type,p=l.bytesPerElement,h=d===e.INT||d===e.UNSIGNED_INT||s.gpuType===v;if(s.isInterleavedBufferAttribute){const t=s.data,l=t.stride,_=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let o=void 0!==n.precision?n.precision:"highp";const s=a(o);s!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",s,"instead."),o=s);const l=!0===n.logarithmicDepthBuffer,c=!0===n.reverseDepthBuffer&&t.has("EXT_clip_control"),d=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),u=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:a,textureFormatReadable:function(t){return t===M||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const i=n===E&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==S&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==T&&!i)},precision:o,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:d,maxVertexTextures:u,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function Hn(t){const n=this;let r=null,i=0,a=!1,o=!1;const s=new x,l=new e,c={value:null,needsUpdate:!1};function d(e,t,r,i){const a=null!==e?e.length:0;let o=null;if(0!==a){if(o=c.value,!0!==i||null===o){const n=r+4*a,i=t.matrixWorldInverse;l.getNormalMatrix(i),(null===o||o.length0);n.numPlanes=i,n.numIntersection=0}();else{const e=o?0:i,t=4*e;let n=m.clippingState||null;c.value=n,n=d(u,s,t,l);for(let e=0;e!==t;++e)n[e]=r[e];m.clippingState=n,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}}}function Gn(e){let t=new WeakMap;function n(e,t){return t===R?e.mapping=C:t===A&&(e.mapping=L),e}function r(e){const n=e.target;n.removeEventListener("dispose",r);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){const a=i.mapping;if(a===R||a===A){if(t.has(i)){return n(t.get(i).texture,i.mapping)}{const a=i.image;if(a&&a.height>0){const o=new b(a.height);return o.fromEquirectangularTexture(e,i),t.set(i,o),i.addEventListener("dispose",r),n(o.texture,i.mapping)}return null}}}return i},dispose:function(){t=new WeakMap}}}const Vn=[.125,.215,.35,.446,.526,.582],zn=20,kn=new P,Wn=new n;let Xn=null,Yn=0,Kn=0,jn=!1;const qn=(1+Math.sqrt(5))/2,Zn=1/qn,$n=[new i(-qn,Zn,0),new i(qn,Zn,0),new i(-Zn,0,qn),new i(Zn,0,qn),new i(0,qn,-Zn),new i(0,qn,Zn),new i(-1,1,-1),new i(1,1,-1),new i(-1,1,1),new i(1,1,1)],Qn=new i;class Jn{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,i={}){const{size:a=256,position:o=Qn}=i;Xn=this._renderer.getRenderTarget(),Yn=this._renderer.getActiveCubeFace(),Kn=this._renderer.getActiveMipmapLevel(),jn=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=rr(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=nr(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?s=Vn[o-e+4-1]:0===o&&(s=0),r.push(s);const l=1/(a-2),c=-l,d=1+l,u=[c,c,d,c,d,d,c,c,d,d,c,d],f=6,p=6,m=3,h=2,_=1,g=new Float32Array(m*p*f),v=new Float32Array(h*p*f),E=new Float32Array(_*p*f);for(let e=0;e2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];g.set(r,m*p*e),v.set(u,h*p*e);const i=[e,e,e,e,e,e];E.set(i,_*p*e)}const S=new N;S.setAttribute("position",new O(g,m)),S.setAttribute("uv",new O(v,h)),S.setAttribute("faceIndex",new O(E,_)),t.push(S),i>4&&i--}return{lodPlanes:t,sizeLods:n,sigmas:r}}(r)),this._blurMaterial=function(e,t,n){const r=new Float32Array(zn),a=new i(0,1,0),o=new l({name:"SphericalGaussianBlur",defines:{n:zn,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:ir(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:y,depthTest:!1,depthWrite:!1});return o}(r,e,t)}return r}_compileMaterial(e){const t=new o(this._lodPlanes[0],e);this._renderer.compile(t,kn)}_sceneToCubeUV(e,t,n,r,i){const a=new U(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,f=u.autoClear,p=u.toneMapping;u.getClearColor(Wn),u.toneMapping=D,u.autoClear=!1;const m=new w({name:"PMREM.Background",side:c,depthWrite:!1,depthTest:!1}),h=new o(new s,m);let _=!1;const g=e.background;g?g.isColor&&(m.color.copy(g),e.background=null,_=!0):(m.color.copy(Wn),_=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(a.up.set(0,l[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+d[t],i.y,i.z)):1===n?(a.up.set(0,0,l[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+d[t],i.z)):(a.up.set(0,l[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+d[t]));const o=this._cubeSize;tr(r,n*o,t>2?o:0,o,o),u.setRenderTarget(r),_&&u.render(h,a),u.render(e,a)}h.geometry.dispose(),h.material.dispose(),u.toneMapping=p,u.autoClear=f,e.background=g}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===C||e.mapping===L;r?(null===this._cubemapMaterial&&(this._cubemapMaterial=rr()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=nr());const i=r?this._cubemapMaterial:this._equirectMaterial,a=new o(this._lodPlanes[0],i);i.uniforms.envMap.value=e;const s=this._cubeSize;tr(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,kn)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let t=1;tzn&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${h} samples when the maximum is set to 20`);const _=[];let g=0;for(let e=0;ev-4?r-v+4:0),4*(this._cubeSize-E),3*E,2*E),l.setRenderTarget(t),l.render(d,kn)}}function er(e,t,n){const r=new I(e,t,n);return r.texture.mapping=a,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function tr(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function nr(){return new l({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ir(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:y,depthTest:!1,depthWrite:!1})}function rr(){return new l({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ir(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:y,depthTest:!1,depthWrite:!1})}function ir(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function ar(e){let t=new WeakMap,n=null;function r(e){const n=e.target;n.removeEventListener("dispose",r);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){const a=i.mapping,o=a===R||a===A,s=a===C||a===L;if(o||s){let a=t.get(i);const l=void 0!==a?a.texture.pmremVersion:0;if(i.isRenderTargetTexture&&i.pmremVersion!==l)return null===n&&(n=new Jn(e)),a=o?n.fromEquirectangular(i,a):n.fromCubemap(i,a),a.texture.pmremVersion=i.pmremVersion,t.set(i,a),a.texture;if(void 0!==a)return a.texture;{const l=i.image;return o&&l&&l.height>0||s&&l&&function(e){let t=0;const n=6;for(let r=0;rn.maxTextureSize&&(M=Math.ceil(S/n.maxTextureSize),S=n.maxTextureSize);const x=new Float32Array(S*M*4*u),R=new W(x,S,M,u);R.type=T,R.needsUpdate=!0;const A=4*E;for(let C=0;C0)return e;const i=t*n;let a=gr[i];if(void 0===a&&(a=new Float32Array(i),gr[i]=a),0!==t){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function xr(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n":" "} ${i}: ${n[e]}`)}return r.join("\n")}(e.getShaderSource(t),r)}return i}function Ti(e,t){const n=function(e){p._getMatrix(Ei,p.workingColorSpace,e);const t=`mat3( ${Ei.elements.map((e=>e.toFixed(4)))} )`;switch(p.getTransfer(e)){case se:return[t,"LinearTransferOETF"];case m:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}function Mi(e,t){let n;switch(t){case oe:n="Linear";break;case ae:n="Reinhard";break;case ie:n="Cineon";break;case re:n="ACESFilmic";break;case ne:n="AgX";break;case te:n="Neutral";break;case ee:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const xi=new i;function Ri(){p.getLuminanceCoefficients(xi);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${xi.x.toFixed(4)}, ${xi.y.toFixed(4)}, ${xi.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function Ai(e){return""!==e}function bi(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Ci(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Li=/^[ \t]*#include +<([\w\d./]+)>/gm;function Pi(e){return e.replace(Li,Di)}const Ui=new Map;function Di(e,t){let n=Pn[t];if(void 0===n){const e=Ui.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Pn[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Pi(n)}const wi=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function yi(e){return e.replace(wi,Ii)}function Ii(e,t,n,r){let i="";for(let e=parseInt(t);e0&&(g+="\n"),v=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,h].filter(Ai).join("\n"),v.length>0&&(v+="\n")):(g=[Ni(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,h,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Ai).join("\n"),v=[Ni(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,h,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.envMap?"#define "+u:"",n.envMap?"#define "+f:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==D?"#define TONE_MAPPING":"",n.toneMapping!==D?Pn.tonemapping_pars_fragment:"",n.toneMapping!==D?Mi("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Pn.colorspace_pars_fragment,Ti("linearToOutputTexel",n.outputColorSpace),Ri(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(Ai).join("\n")),s=Pi(s),s=bi(s,n),s=Ci(s,n),l=Pi(l),l=bi(l,n),l=Ci(l,n),s=yi(s),l=yi(l),!0!==n.isRawShaderMaterial&&(E="#version 300 es\n",g=[m,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,v=["#define varying in",n.glslVersion===Z?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Z?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+v);const S=E+g+s,T=E+v+l,M=gi(i,i.VERTEX_SHADER,S),x=gi(i,i.FRAGMENT_SHADER,T);function R(t){if(e.debug.checkShaderErrors){const n=i.getProgramInfoLog(_).trim(),r=i.getShaderInfoLog(M).trim(),a=i.getShaderInfoLog(x).trim();let o=!0,s=!0;if(!1===i.getProgramParameter(_,i.LINK_STATUS))if(o=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(i,_,M,x);else{const e=Si(i,M,"vertex"),r=Si(i,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(_,i.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+r)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==r&&""!==a||(s=!1);s&&(t.diagnostics={runnable:o,programLog:n,vertexShader:{log:r,prefix:g},fragmentShader:{log:a,prefix:v}})}i.deleteShader(M),i.deleteShader(x),A=new _i(i,_),b=function(e,t){const n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i0,J=o.clearcoat>0,ee=o.dispersion>0,te=o.iridescence>0,ne=o.sheen>0,re=o.transmission>0,ie=Q&&!!o.anisotropyMap,ae=J&&!!o.clearcoatMap,oe=J&&!!o.clearcoatNormalMap,se=J&&!!o.clearcoatRoughnessMap,le=te&&!!o.iridescenceMap,ce=te&&!!o.iridescenceThicknessMap,de=ne&&!!o.sheenColorMap,ue=ne&&!!o.sheenRoughnessMap,_e=!!o.specularMap,ge=!!o.specularColorMap,ve=!!o.specularIntensityMap,Ee=re&&!!o.transmissionMap,Se=re&&!!o.thicknessMap,Te=!!o.gradientMap,Me=!!o.alphaMap,xe=o.alphaTest>0,Re=!!o.alphaHash,Ae=!!o.extensions;let be=D;o.toneMapped&&(null!==O&&!0!==O.isXRRenderTarget||(be=e.toneMapping));const Ce={shaderID:C,shaderType:o.type,shaderName:o.name,vertexShader:U,fragmentShader:w,defines:o.defines,customVertexShaderID:y,customFragmentShaderID:I,isRawShaderMaterial:!0===o.isRawShaderMaterial,glslVersion:o.glslVersion,precision:g,batching:G,batchingColor:G&&null!==T._colorsTexture,instancing:H,instancingColor:H&&null!==T.instanceColor,instancingMorph:H&&null!==T.morphTexture,supportsVertexTextures:_,outputColorSpace:null===O?e.outputColorSpace:!0===O.isXRRenderTarget?O.texture.colorSpace:F,alphaToCoverage:!!o.alphaToCoverage,map:V,matcap:z,envMap:k,envMapMode:k&&A.mapping,envMapCubeUVHeight:b,aoMap:W,lightMap:X,bumpMap:Y,normalMap:K,displacementMap:_&&j,emissiveMap:q,normalMapObjectSpace:K&&o.normalMapType===he,normalMapTangentSpace:K&&o.normalMapType===me,metalnessMap:Z,roughnessMap:$,anisotropy:Q,anisotropyMap:ie,clearcoat:J,clearcoatMap:ae,clearcoatNormalMap:oe,clearcoatRoughnessMap:se,dispersion:ee,iridescence:te,iridescenceMap:le,iridescenceThicknessMap:ce,sheen:ne,sheenColorMap:de,sheenRoughnessMap:ue,specularMap:_e,specularColorMap:ge,specularIntensityMap:ve,transmission:re,transmissionMap:Ee,thicknessMap:Se,gradientMap:Te,opaque:!1===o.transparent&&o.blending===pe&&!1===o.alphaToCoverage,alphaMap:Me,alphaTest:xe,alphaHash:Re,combine:o.combine,mapUv:V&&E(o.map.channel),aoMapUv:W&&E(o.aoMap.channel),lightMapUv:X&&E(o.lightMap.channel),bumpMapUv:Y&&E(o.bumpMap.channel),normalMapUv:K&&E(o.normalMap.channel),displacementMapUv:j&&E(o.displacementMap.channel),emissiveMapUv:q&&E(o.emissiveMap.channel),metalnessMapUv:Z&&E(o.metalnessMap.channel),roughnessMapUv:$&&E(o.roughnessMap.channel),anisotropyMapUv:ie&&E(o.anisotropyMap.channel),clearcoatMapUv:ae&&E(o.clearcoatMap.channel),clearcoatNormalMapUv:oe&&E(o.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:se&&E(o.clearcoatRoughnessMap.channel),iridescenceMapUv:le&&E(o.iridescenceMap.channel),iridescenceThicknessMapUv:ce&&E(o.iridescenceThicknessMap.channel),sheenColorMapUv:de&&E(o.sheenColorMap.channel),sheenRoughnessMapUv:ue&&E(o.sheenRoughnessMap.channel),specularMapUv:_e&&E(o.specularMap.channel),specularColorMapUv:ge&&E(o.specularColorMap.channel),specularIntensityMapUv:ve&&E(o.specularIntensityMap.channel),transmissionMapUv:Ee&&E(o.transmissionMap.channel),thicknessMapUv:Se&&E(o.thicknessMap.channel),alphaMapUv:Me&&E(o.alphaMap.channel),vertexTangents:!!x.attributes.tangent&&(K||Q),vertexColors:o.vertexColors,vertexAlphas:!0===o.vertexColors&&!!x.attributes.color&&4===x.attributes.color.itemSize,pointsUvs:!0===T.isPoints&&!!x.attributes.uv&&(V||Me),fog:!!M,useFog:!0===o.fog,fogExp2:!!M&&M.isFogExp2,flatShading:!0===o.flatShading&&!1===o.wireframe,sizeAttenuation:!0===o.sizeAttenuation,logarithmicDepthBuffer:h,reverseDepthBuffer:B,skinning:!0===T.isSkinnedMesh,morphTargets:void 0!==x.morphAttributes.position,morphNormals:void 0!==x.morphAttributes.normal,morphColors:void 0!==x.morphAttributes.color,morphTargetsCount:P,morphTextureStride:N,numDirLights:l.directional.length,numPointLights:l.point.length,numSpotLights:l.spot.length,numSpotLightMaps:l.spotLightMap.length,numRectAreaLights:l.rectArea.length,numHemiLights:l.hemi.length,numDirLightShadows:l.directionalShadowMap.length,numPointLightShadows:l.pointShadowMap.length,numSpotLightShadows:l.spotShadowMap.length,numSpotLightShadowsWithMaps:l.numSpotLightShadowsWithMaps,numLightProbes:l.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:o.dithering,shadowMapEnabled:e.shadowMap.enabled&&f.length>0,shadowMapType:e.shadowMap.type,toneMapping:be,decodeVideoTexture:V&&!0===o.map.isVideoTexture&&p.getTransfer(o.map.colorSpace)===m,decodeVideoTextureEmissive:q&&!0===o.emissiveMap.isVideoTexture&&p.getTransfer(o.emissiveMap.colorSpace)===m,premultipliedAlpha:o.premultipliedAlpha,doubleSided:o.side===fe,flipSided:o.side===c,useDepthPacking:o.depthPacking>=0,depthPacking:o.depthPacking||0,index0AttributeName:o.index0AttributeName,extensionClipCullDistance:Ae&&!0===o.extensions.clipCullDistance&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ae&&!0===o.extensions.multiDraw||G)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:o.customProgramCacheKey()};return Ce.vertexUv1s=u.has(1),Ce.vertexUv2s=u.has(2),Ce.vertexUv3s=u.has(3),u.clear(),Ce},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){l.disableAll(),t.supportsVertexTextures&&l.enable(0);t.instancing&&l.enable(1);t.instancingColor&&l.enable(2);t.instancingMorph&&l.enable(3);t.matcap&&l.enable(4);t.envMap&&l.enable(5);t.normalMapObjectSpace&&l.enable(6);t.normalMapTangentSpace&&l.enable(7);t.clearcoat&&l.enable(8);t.iridescence&&l.enable(9);t.alphaTest&&l.enable(10);t.vertexColors&&l.enable(11);t.vertexAlphas&&l.enable(12);t.vertexUv1s&&l.enable(13);t.vertexUv2s&&l.enable(14);t.vertexUv3s&&l.enable(15);t.vertexTangents&&l.enable(16);t.anisotropy&&l.enable(17);t.alphaHash&&l.enable(18);t.batching&&l.enable(19);t.dispersion&&l.enable(20);t.batchingColor&&l.enable(21);t.gradientMap&&l.enable(22);e.push(l.mask),l.disableAll(),t.fog&&l.enable(0);t.useFog&&l.enable(1);t.flatShading&&l.enable(2);t.logarithmicDepthBuffer&&l.enable(3);t.reverseDepthBuffer&&l.enable(4);t.skinning&&l.enable(5);t.morphTargets&&l.enable(6);t.morphNormals&&l.enable(7);t.morphColors&&l.enable(8);t.premultipliedAlpha&&l.enable(9);t.shadowMapEnabled&&l.enable(10);t.doubleSided&&l.enable(11);t.flipSided&&l.enable(12);t.useDepthPacking&&l.enable(13);t.dithering&&l.enable(14);t.transmission&&l.enable(15);t.sheen&&l.enable(16);t.opaque&&l.enable(17);t.pointsUvs&&l.enable(18);t.decodeVideoTexture&&l.enable(19);t.decodeVideoTextureEmissive&&l.enable(20);t.alphaToCoverage&&l.enable(21);e.push(l.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=v[e.type];let n;if(t){const e=Dn[t];n=ue.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let r;for(let e=0,t=f.length;e0?r.push(d):!0===o.transparent?i.push(d):n.push(d)},unshift:function(e,t,o,s,l,c){const d=a(e,t,o,s,l,c);o.transmission>0?r.unshift(d):!0===o.transparent?i.unshift(d):n.unshift(d)},finish:function(){for(let n=t,r=e.length;n1&&n.sort(e||zi),r.length>1&&r.sort(t||ki),i.length>1&&i.sort(t||ki)}}}function Xi(){let e=new WeakMap;return{get:function(t,n){const r=e.get(t);let i;return void 0===r?(i=new Wi,e.set(t,[i])):n>=r.length?(i=new Wi,r.push(i)):i=r[n],i},dispose:function(){e=new WeakMap}}}function Yi(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let r;switch(t.type){case"DirectionalLight":r={direction:new i,color:new n};break;case"SpotLight":r={position:new i,direction:new i,color:new n,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":r={position:new i,color:new n,distance:0,decay:0};break;case"HemisphereLight":r={direction:new i,skyColor:new n,groundColor:new n};break;case"RectAreaLight":r={color:new n,position:new i,halfWidth:new i,halfHeight:new i}}return e[t.id]=r,r}}}let Ki=0;function ji(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function qi(e){const n=new Yi,r=function(){const e={};return{get:function(n){if(void 0!==e[n.id])return e[n.id];let r;switch(n.type){case"DirectionalLight":case"SpotLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new t};break;case"PointLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new t,shadowCameraNear:1,shadowCameraFar:1e3}}return e[n.id]=r,r}}}(),a={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)a.probe.push(new i);const o=new i,s=new f,l=new f;return{setup:function(t){let i=0,o=0,s=0;for(let e=0;e<9;e++)a.probe[e].set(0,0,0);let l=0,c=0,d=0,u=0,f=0,p=0,m=0,h=0,_=0,g=0,v=0;t.sort(ji);for(let e=0,E=t.length;e0&&(!0===e.has("OES_texture_float_linear")?(a.rectAreaLTC1=Un.LTC_FLOAT_1,a.rectAreaLTC2=Un.LTC_FLOAT_2):(a.rectAreaLTC1=Un.LTC_HALF_1,a.rectAreaLTC2=Un.LTC_HALF_2)),a.ambient[0]=i,a.ambient[1]=o,a.ambient[2]=s;const E=a.hash;E.directionalLength===l&&E.pointLength===c&&E.spotLength===d&&E.rectAreaLength===u&&E.hemiLength===f&&E.numDirectionalShadows===p&&E.numPointShadows===m&&E.numSpotShadows===h&&E.numSpotMaps===_&&E.numLightProbes===v||(a.directional.length=l,a.spot.length=d,a.rectArea.length=u,a.point.length=c,a.hemi.length=f,a.directionalShadow.length=p,a.directionalShadowMap.length=p,a.pointShadow.length=m,a.pointShadowMap.length=m,a.spotShadow.length=h,a.spotShadowMap.length=h,a.directionalShadowMatrix.length=p,a.pointShadowMatrix.length=m,a.spotLightMatrix.length=h+_-g,a.spotLightMap.length=_,a.numSpotLightShadowsWithMaps=g,a.numLightProbes=v,E.directionalLength=l,E.pointLength=c,E.spotLength=d,E.rectAreaLength=u,E.hemiLength=f,E.numDirectionalShadows=p,E.numPointShadows=m,E.numSpotShadows=h,E.numSpotMaps=_,E.numLightProbes=v,a.version=Ki++)},setupView:function(e,t){let n=0,r=0,i=0,c=0,d=0;const u=t.matrixWorldInverse;for(let t=0,f=e.length;t=i.length?(a=new Zi(e),i.push(a)):a=i[r],a},dispose:function(){t=new WeakMap}}}function Qi(e,n,r){let i=new ge;const a=new t,s=new t,d=new k,u=new ve({depthPacking:Ee}),f=new Se,p={},m=r.maxTextureSize,h={[_]:c,[c]:_,[fe]:fe},g=new l({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new t},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),v=g.clone();v.defines.HORIZONTAL_PASS=1;const E=new N;E.setAttribute("position",new O(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const S=new o(E,g),T=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=$;let M=this.type;function x(t,r){const i=n.update(S);g.defines.VSM_SAMPLES!==t.blurSamples&&(g.defines.VSM_SAMPLES=t.blurSamples,v.defines.VSM_SAMPLES=t.blurSamples,g.needsUpdate=!0,v.needsUpdate=!0),null===t.mapPass&&(t.mapPass=new I(a.x,a.y)),g.uniforms.shadow_pass.value=t.map.texture,g.uniforms.resolution.value=t.mapSize,g.uniforms.radius.value=t.radius,e.setRenderTarget(t.mapPass),e.clear(),e.renderBufferDirect(r,null,i,g,S,null),v.uniforms.shadow_pass.value=t.mapPass.texture,v.uniforms.resolution.value=t.mapSize,v.uniforms.radius.value=t.radius,e.setRenderTarget(t.map),e.clear(),e.renderBufferDirect(r,null,i,v,S,null)}function R(t,n,r,i){let a=null;const o=!0===r.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==o)a=o;else if(a=!0===r.isPointLight?f:u,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=a.uuid,t=n.uuid;let r=p[e];void 0===r&&(r={},p[e]=r);let i=r[t];void 0===i&&(i=a.clone(),r[t]=i,n.addEventListener("dispose",b)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,a.side=i===J?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],a.alphaMap=n.alphaMap,a.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,!0===r.isPointLight&&!0===a.isMeshDistanceMaterial){e.properties.get(a).light=r}return a}function A(t,r,a,o,s){if(!1===t.visible)return;if(t.layers.test(r.layers)&&(t.isMesh||t.isLine||t.isPoints)&&(t.castShadow||t.receiveShadow&&s===J)&&(!t.frustumCulled||i.intersectsObject(t))){t.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,t.matrixWorld);const i=n.update(t),l=t.material;if(Array.isArray(l)){const n=i.groups;for(let c=0,d=n.length;cm||a.y>m)&&(a.x>m&&(s.x=Math.floor(m/h.x),a.x=s.x*h.x,c.mapSize.x=s.x),a.y>m&&(s.y=Math.floor(m/h.y),a.y=s.y*h.y,c.mapSize.y=s.y)),null===c.map||!0===f||!0===p){const e=this.type!==J?{minFilter:Te,magFilter:Te}:{};null!==c.map&&c.map.dispose(),c.map=new I(a.x,a.y,e),c.map.texture.name=l.name+".shadowMap",c.camera.updateProjectionMatrix()}e.setRenderTarget(c.map),e.clear();const _=c.getViewportCount();for(let e=0;e<_;e++){const t=c.getViewport(e);d.set(s.x*t.x,s.y*t.y,s.x*t.z,s.y*t.w),u.viewport(d),c.updateMatrices(l,e),i=c.getFrustum(),A(n,r,c.camera,l,this.type)}!0!==c.isPointLightShadow&&this.type===J&&x(c,r),c.needsUpdate=!1}M=this.type,T.needsUpdate=!1,e.setRenderTarget(o,l,c)}}const Ji={[Ke]:Ye,[Xe]:ze,[We]:Ve,[Me]:ke,[Ye]:Ke,[ze]:Xe,[Ve]:We,[ke]:Me};function ea(e,t){const r=new function(){let t=!1;const n=new k;let r=null;const i=new k(0,0,0,0);return{setMask:function(n){r===n||t||(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){!0===s&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),!1===i.equals(n)&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}},i=new function(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){const n=t.get("EXT_clip_control");e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;const i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?W(e.DEPTH_TEST):X(e.DEPTH_TEST)},setMask:function(t){i===t||n||(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Ji[t]),a!==t){switch(t){case Ke:e.depthFunc(e.NEVER);break;case Ye:e.depthFunc(e.ALWAYS);break;case Xe:e.depthFunc(e.LESS);break;case Me:e.depthFunc(e.LEQUAL);break;case We:e.depthFunc(e.EQUAL);break;case ke:e.depthFunc(e.GEQUAL);break;case ze:e.depthFunc(e.GREATER);break;case Ve:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(r&&(t=1-t),e.clearDepth(t),o=t)},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}},a=new function(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,l=null,c=null;return{setTest:function(n){t||(n?W(e.STENCIL_TEST):X(e.STENCIL_TEST))},setMask:function(r){n===r||t||(e.stencilMask(r),n=r)},setFunc:function(t,n,o){r===t&&i===n&&a===o||(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){o===t&&s===n&&l===r||(e.stencilOp(t,n,r),o=t,s=n,l=r)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,l=null,c=null}}},o=new WeakMap,s=new WeakMap;let l={},d={},u=new WeakMap,f=[],p=null,m=!1,h=null,_=null,g=null,v=null,E=null,S=null,T=null,M=new n(0,0,0),x=0,R=!1,A=null,b=null,C=null,L=null,P=null;const U=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let D=!1,w=0;const I=e.getParameter(e.VERSION);-1!==I.indexOf("WebGL")?(w=parseFloat(/^WebGL (\d)/.exec(I)[1]),D=w>=1):-1!==I.indexOf("OpenGL ES")&&(w=parseFloat(/^OpenGL ES (\d)/.exec(I)[1]),D=w>=2);let N=null,O={};const F=e.getParameter(e.SCISSOR_BOX),B=e.getParameter(e.VIEWPORT),H=(new k).fromArray(F),G=(new k).fromArray(B);function V(t,n,r,i){const a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;on||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(r*i.width),a=Math.floor(r*i.height);void 0===f&&(f=g(n,a));const o=t?g(n,a):f;o.width=n,o.height=a;return o.getContext("2d").drawImage(e,0,0,n,a),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+i.width+"x"+i.height+") to ("+n+"x"+a+")."),o}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+i.width+"x"+i.height+")."),e}return e}function E(e){return e.generateMipmaps}function x(t){e.generateMipmap(t)}function R(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function A(t,r,i,a,o=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+t+"'")}let s=r;if(r===e.RED&&(i===e.FLOAT&&(s=e.R32F),i===e.HALF_FLOAT&&(s=e.R16F),i===e.UNSIGNED_BYTE&&(s=e.R8)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.R8UI),i===e.UNSIGNED_SHORT&&(s=e.R16UI),i===e.UNSIGNED_INT&&(s=e.R32UI),i===e.BYTE&&(s=e.R8I),i===e.SHORT&&(s=e.R16I),i===e.INT&&(s=e.R32I)),r===e.RG&&(i===e.FLOAT&&(s=e.RG32F),i===e.HALF_FLOAT&&(s=e.RG16F),i===e.UNSIGNED_BYTE&&(s=e.RG8)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RG8UI),i===e.UNSIGNED_SHORT&&(s=e.RG16UI),i===e.UNSIGNED_INT&&(s=e.RG32UI),i===e.BYTE&&(s=e.RG8I),i===e.SHORT&&(s=e.RG16I),i===e.INT&&(s=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGB8UI),i===e.UNSIGNED_SHORT&&(s=e.RGB16UI),i===e.UNSIGNED_INT&&(s=e.RGB32UI),i===e.BYTE&&(s=e.RGB8I),i===e.SHORT&&(s=e.RGB16I),i===e.INT&&(s=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(s=e.RGBA16UI),i===e.UNSIGNED_INT&&(s=e.RGBA32UI),i===e.BYTE&&(s=e.RGBA8I),i===e.SHORT&&(s=e.RGBA16I),i===e.INT&&(s=e.RGBA32I)),r===e.RGB&&i===e.UNSIGNED_INT_5_9_9_9_REV&&(s=e.RGB9_E5),r===e.RGBA){const t=o?se:p.getTransfer(a);i===e.FLOAT&&(s=e.RGBA32F),i===e.HALF_FLOAT&&(s=e.RGBA16F),i===e.UNSIGNED_BYTE&&(s=t===m?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT_4_4_4_4&&(s=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(s=e.RGB5_A1)}return s!==e.R16F&&s!==e.R32F&&s!==e.RG16F&&s!==e.RG32F&&s!==e.RGBA16F&&s!==e.RGBA32F||n.get("EXT_color_buffer_float"),s}function b(t,n){let r;return t?null===n||n===Tt||n===Mt?r=e.DEPTH24_STENCIL8:n===T?r=e.DEPTH32F_STENCIL8:n===xt&&(r=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===Tt||n===Mt?r=e.DEPTH_COMPONENT24:n===T?r=e.DEPTH_COMPONENT32F:n===xt&&(r=e.DEPTH_COMPONENT16),r}function C(e,t){return!0===E(e)||e.isFramebufferTexture&&e.minFilter!==Te&&e.minFilter!==B?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function L(e){const t=e.target;t.removeEventListener("dispose",L),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=h.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&U(e),0===Object.keys(r).length&&h.delete(n)}i.remove(e)}(t),t.isVideoTexture&&u.delete(t)}function P(t){const n=t.target;n.removeEventListener("dispose",P),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r0&&a.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void V(a,t,n);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}r.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+n)}const y={[at]:e.REPEAT,[it]:e.CLAMP_TO_EDGE,[rt]:e.MIRRORED_REPEAT},I={[Te]:e.NEAREST,[ct]:e.NEAREST_MIPMAP_NEAREST,[lt]:e.NEAREST_MIPMAP_LINEAR,[B]:e.LINEAR,[st]:e.LINEAR_MIPMAP_NEAREST,[ot]:e.LINEAR_MIPMAP_LINEAR},N={[_t]:e.NEVER,[ht]:e.ALWAYS,[mt]:e.LESS,[K]:e.LEQUAL,[pt]:e.EQUAL,[ft]:e.GEQUAL,[ut]:e.GREATER,[dt]:e.NOTEQUAL};function O(t,r){if(r.type!==T||!1!==n.has("OES_texture_float_linear")||r.magFilter!==B&&r.magFilter!==st&&r.magFilter!==lt&&r.magFilter!==ot&&r.minFilter!==B&&r.minFilter!==st&&r.minFilter!==lt&&r.minFilter!==ot||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(t,e.TEXTURE_WRAP_S,y[r.wrapS]),e.texParameteri(t,e.TEXTURE_WRAP_T,y[r.wrapT]),t!==e.TEXTURE_3D&&t!==e.TEXTURE_2D_ARRAY||e.texParameteri(t,e.TEXTURE_WRAP_R,y[r.wrapR]),e.texParameteri(t,e.TEXTURE_MAG_FILTER,I[r.magFilter]),e.texParameteri(t,e.TEXTURE_MIN_FILTER,I[r.minFilter]),r.compareFunction&&(e.texParameteri(t,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(t,e.TEXTURE_COMPARE_FUNC,N[r.compareFunction])),!0===n.has("EXT_texture_filter_anisotropic")){if(r.magFilter===Te)return;if(r.minFilter!==lt&&r.minFilter!==ot)return;if(r.type===T&&!1===n.has("OES_texture_float_linear"))return;if(r.anisotropy>1||i.get(r).__currentAnisotropy){const o=n.get("EXT_texture_filter_anisotropic");e.texParameterf(t,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r.anisotropy,a.getMaxAnisotropy())),i.get(r).__currentAnisotropy=r.anisotropy}}}function H(t,n){let r=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",L));const i=n.source;let a=h.get(i);void 0===a&&(a={},h.set(i,a));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===a[o]&&(a[o]={texture:e.createTexture(),usedTimes:0},s.memory.textures++,r=!0),a[o].usedTimes++;const i=a[t.__cacheKey];void 0!==i&&(a[t.__cacheKey].usedTimes--,0===i.usedTimes&&U(n)),t.__cacheKey=o,t.__webglTexture=a[o].texture}return r}function G(e,t,n){return Math.floor(Math.floor(e/n)/t)}function V(t,n,s){let l=e.TEXTURE_2D;(n.isDataArrayTexture||n.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),n.isData3DTexture&&(l=e.TEXTURE_3D);const c=H(t,n),d=n.source;r.bindTexture(l,t.__webglTexture,e.TEXTURE0+s);const u=i.get(d);if(d.version!==u.__version||!0===c){r.activeTexture(e.TEXTURE0+s);const t=p.getPrimaries(p.workingColorSpace),i=n.colorSpace===gt?null:p.getPrimaries(n.colorSpace),f=n.colorSpace===gt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,n.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,f);let m=v(n.image,!1,a.maxTextureSize);m=$(n,m);const h=o.convert(n.format,n.colorSpace),_=o.convert(n.type);let g,S=A(n.internalFormat,h,_,n.colorSpace,n.isVideoTexture);O(l,n);const T=n.mipmaps,R=!0!==n.isVideoTexture,L=void 0===u.__version||!0===c,P=d.dataReady,U=C(n,m);if(n.isDepthTexture)S=b(n.format===vt,n.type),L&&(R?r.texStorage2D(e.TEXTURE_2D,1,S,m.width,m.height):r.texImage2D(e.TEXTURE_2D,0,S,m.width,m.height,0,h,_,null));else if(n.isDataTexture)if(T.length>0){R&&L&&r.texStorage2D(e.TEXTURE_2D,U,S,T[0].width,T[0].height);for(let t=0,n=T.length;te.start-t.start));let s=0;for(let e=1;e0){const i=Et(g.width,g.height,n.format,n.type);for(const a of n.layerUpdates){const n=g.data.subarray(a*i/g.data.BYTES_PER_ELEMENT,(a+1)*i/g.data.BYTES_PER_ELEMENT);r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,a,g.width,g.height,1,h,n)}n.clearLayerUpdates()}else r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,g.width,g.height,m.depth,h,g.data)}else r.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,S,g.width,g.height,m.depth,0,g.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else R?P&&r.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,g.width,g.height,m.depth,h,_,g.data):r.texImage3D(e.TEXTURE_2D_ARRAY,t,S,g.width,g.height,m.depth,0,h,_,g.data)}else{R&&L&&r.texStorage2D(e.TEXTURE_2D,U,S,T[0].width,T[0].height);for(let t=0,i=T.length;t0){const t=Et(m.width,m.height,n.format,n.type);for(const i of n.layerUpdates){const n=m.data.subarray(i*t/m.data.BYTES_PER_ELEMENT,(i+1)*t/m.data.BYTES_PER_ELEMENT);r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,m.width,m.height,1,h,_,n)}n.clearLayerUpdates()}else r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,m.width,m.height,m.depth,h,_,m.data)}else r.texImage3D(e.TEXTURE_2D_ARRAY,0,S,m.width,m.height,m.depth,0,h,_,m.data);else if(n.isData3DTexture)R?(L&&r.texStorage3D(e.TEXTURE_3D,U,S,m.width,m.height,m.depth),P&&r.texSubImage3D(e.TEXTURE_3D,0,0,0,0,m.width,m.height,m.depth,h,_,m.data)):r.texImage3D(e.TEXTURE_3D,0,S,m.width,m.height,m.depth,0,h,_,m.data);else if(n.isFramebufferTexture){if(L)if(R)r.texStorage2D(e.TEXTURE_2D,U,S,m.width,m.height);else{let t=m.width,n=m.height;for(let i=0;i>=1,n>>=1}}else if(T.length>0){if(R&&L){const t=Q(T[0]);r.texStorage2D(e.TEXTURE_2D,U,S,t.width,t.height)}for(let t=0,n=T.length;t>d),i=Math.max(1,n.height>>d);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?r.texImage3D(c,d,p,t,i,n.depth,0,u,f,null):r.texImage2D(c,d,p,t,i,0,u,f,null)}r.bindFramebuffer(e.FRAMEBUFFER,t),Z(n)?l.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,s,c,h.__webglTexture,0,q(n)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,s,c,h.__webglTexture,d),r.bindFramebuffer(e.FRAMEBUFFER,null)}function k(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=b(n.stencilBuffer,a),s=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=q(n);Z(n)?l.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,c,o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,c,o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,s,e.RENDERBUFFER,t)}else{const t=n.textures;for(let i=0;i{delete n.__boundDepthTexture,delete n.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),n.__depthDisposeCallback=t}n.__boundDepthTexture=e}if(t.depthTexture&&!n.__autoAllocateDepthBuffer){if(a)throw new Error("target.depthTexture not supported in Cube render targets");const e=t.texture.mipmaps;e&&e.length>0?W(n.__webglFramebuffer[0],t):W(n.__webglFramebuffer,t)}else if(a){n.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(r.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[i]),void 0===n.__webglDepthbuffer[i])n.__webglDepthbuffer[i]=e.createRenderbuffer(),k(n.__webglDepthbuffer[i],t,!1);else{const r=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=n.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,r,e.RENDERBUFFER,a)}}else{const i=t.texture.mipmaps;if(i&&i.length>0?r.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer[0]):r.bindFramebuffer(e.FRAMEBUFFER,n.__webglFramebuffer),void 0===n.__webglDepthbuffer)n.__webglDepthbuffer=e.createRenderbuffer(),k(n.__webglDepthbuffer,t,!1);else{const r=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=n.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,r,e.RENDERBUFFER,i)}}r.bindFramebuffer(e.FRAMEBUFFER,null)}const Y=[],j=[];function q(e){return Math.min(a.maxSamples,e.samples)}function Z(e){const t=i.get(e);return e.samples>0&&!0===n.has("WEBGL_multisampled_render_to_texture")&&!1!==t.__useRenderToTexture}function $(e,t){const n=e.colorSpace,r=e.format,i=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==F&&n!==gt&&(p.getTransfer(n)===m?r===M&&i===S||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),t}function Q(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(d.width=e.naturalWidth||e.width,d.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(d.width=e.displayWidth,d.height=e.displayHeight):(d.width=e.width,d.height=e.height),d}this.allocateTextureUnit=function(){const e=D;return e>=a.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+a.maxTextures),D+=1,e},this.resetTextureUnits=function(){D=0},this.setTexture2D=w,this.setTexture2DArray=function(t,n){const a=i.get(t);t.version>0&&a.__version!==t.version?V(a,t,n):r.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+n)},this.setTexture3D=function(t,n){const a=i.get(t);t.version>0&&a.__version!==t.version?V(a,t,n):r.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+n)},this.setTextureCube=function(t,n){const s=i.get(t);t.version>0&&s.__version!==t.version?function(t,n,s){if(6!==n.image.length)return;const l=H(t,n),c=n.source;r.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);const d=i.get(c);if(c.version!==d.__version||!0===l){r.activeTexture(e.TEXTURE0+s);const t=p.getPrimaries(p.workingColorSpace),i=n.colorSpace===gt?null:p.getPrimaries(n.colorSpace),u=n.colorSpace===gt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,n.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const f=n.isCompressedTexture||n.image[0].isCompressedTexture,m=n.image[0]&&n.image[0].isDataTexture,h=[];for(let e=0;e<6;e++)h[e]=f||m?m?n.image[e].image:n.image[e]:v(n.image[e],!0,a.maxCubemapSize),h[e]=$(n,h[e]);const _=h[0],g=o.convert(n.format,n.colorSpace),S=o.convert(n.type),T=A(n.internalFormat,g,S,n.colorSpace),R=!0!==n.isVideoTexture,b=void 0===d.__version||!0===l,L=c.dataReady;let P,U=C(n,_);if(O(e.TEXTURE_CUBE_MAP,n),f){R&&b&&r.texStorage2D(e.TEXTURE_CUBE_MAP,U,T,_.width,_.height);for(let t=0;t<6;t++){P=h[t].mipmaps;for(let i=0;i0&&U++;const t=Q(h[0]);r.texStorage2D(e.TEXTURE_CUBE_MAP,U,T,t.width,t.height)}for(let t=0;t<6;t++)if(m){R?L&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,h[t].width,h[t].height,g,S,h[t].data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,T,h[t].width,h[t].height,0,g,S,h[t].data);for(let n=0;n1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=n.version,s.memory.textures++),d){a.__webglFramebuffer=[];for(let t=0;t<6;t++)if(n.mipmaps&&n.mipmaps.length>0){a.__webglFramebuffer[t]=[];for(let r=0;r0){a.__webglFramebuffer=[];for(let t=0;t0&&!1===Z(t)){a.__webglMultisampledFramebuffer=e.createFramebuffer(),a.__webglColorRenderbuffer=[],r.bindFramebuffer(e.FRAMEBUFFER,a.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let r=0;r0)if(!1===Z(t)){const n=t.textures,a=t.width,o=t.height;let s=e.COLOR_BUFFER_BIT;const l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,d=i.get(t),u=n.length>1;if(u)for(let t=0;t0?r.bindFramebuffer(e.DRAW_FRAMEBUFFER,d.__webglFramebuffer[0]):r.bindFramebuffer(e.DRAW_FRAMEBUFFER,d.__webglFramebuffer);for(let r=0;r= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new o(new h(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class ia extends _n{constructor(e,n){super();const r=this;let a=null,o=1,s=null,l="local-floor",c=1,d=null,u=null,f=null,p=null,m=null,h=null;const _=new ra,g=n.getContextAttributes();let v=null,E=null;const T=[],x=[],R=new t;let A=null;const b=new U;b.viewport=new k;const C=new U;C.viewport=new k;const L=[b,C],P=new gn;let D=null,w=null;function y(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=T[t];void 0!==n&&(n.update(e.inputSource,e.frame,d||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function N(){a.removeEventListener("select",y),a.removeEventListener("selectstart",y),a.removeEventListener("selectend",y),a.removeEventListener("squeeze",y),a.removeEventListener("squeezestart",y),a.removeEventListener("squeezeend",y),a.removeEventListener("end",N),a.removeEventListener("inputsourceschange",O);for(let e=0;e=0&&(x[r]=null,T[r].disconnect(n))}for(let t=0;t=x.length){x.push(n),r=e;break}if(null===x[e]){x[e]=n,r=e;break}}if(-1===r)break}const i=T[r];i&&i.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=T[e];return void 0===t&&(t=new vn,T[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=T[e];return void 0===t&&(t=new vn,T[e]=t),t.getGripSpace()},this.getHand=function(e){let t=T[e];return void 0===t&&(t=new vn,T[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){o=e,!0===r.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){l=e,!0===r.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||s},this.setReferenceSpace=function(e){d=e},this.getBaseLayer=function(){return null!==p?p:m},this.getBinding=function(){return f},this.getFrame=function(){return h},this.getSession=function(){return a},this.setSession=async function(t){if(a=t,null!==a){v=e.getRenderTarget(),a.addEventListener("select",y),a.addEventListener("selectstart",y),a.addEventListener("selectend",y),a.addEventListener("squeeze",y),a.addEventListener("squeezestart",y),a.addEventListener("squeezeend",y),a.addEventListener("end",N),a.addEventListener("inputsourceschange",O),!0!==g.xrCompatible&&await n.makeXRCompatible(),A=e.getPixelRatio(),e.getSize(R);if("undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype){let t=null,r=null,i=null;g.depth&&(i=g.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,t=g.stencil?vt:St,r=g.stencil?Mt:Tt);const s={colorFormat:n.RGBA8,depthFormat:i,scaleFactor:o};f=new XRWebGLBinding(a,n),p=f.createProjectionLayer(s),a.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),E=new I(p.textureWidth,p.textureHeight,{format:M,type:S,depthTexture:new j(p.textureWidth,p.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,t),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:!1===p.ignoreDepthValues,resolveStencilBuffer:!1===p.ignoreDepthValues})}else{const t={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:o};m=new XRWebGLLayer(a,n,t),a.updateRenderState({baseLayer:m}),e.setPixelRatio(1),e.setSize(m.framebufferWidth,m.framebufferHeight,!1),E=new I(m.framebufferWidth,m.framebufferHeight,{format:M,type:S,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil,resolveDepthBuffer:!1===m.ignoreDepthValues,resolveStencilBuffer:!1===m.ignoreDepthValues})}E.isXRRenderTarget=!0,this.setFoveation(c),d=null,s=await a.requestReferenceSpace(l),V.setContext(a),V.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==a)return a.environmentBlendMode},this.getDepthTexture=function(){return _.getDepthTexture()};const F=new i,B=new i;function H(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===a)return;let t=e.near,n=e.far;null!==_.texture&&(_.depthNear>0&&(t=_.depthNear),_.depthFar>0&&(n=_.depthFar)),P.near=C.near=b.near=t,P.far=C.far=b.far=n,D===P.near&&w===P.far||(a.updateRenderState({depthNear:P.near,depthFar:P.far}),D=P.near,w=P.far),b.layers.mask=2|e.layers.mask,C.layers.mask=4|e.layers.mask,P.layers.mask=b.layers.mask|C.layers.mask;const r=e.parent,i=P.cameras;H(P,r);for(let e=0;e0&&(e.alphaTest.value=r.alphaTest);const i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,aa.copy(o),aa.x*=-1,aa.y*=-1,aa.z*=-1,a.isCubeTexture&&!1===a.isRenderTargetTexture&&(aa.y*=-1,aa.z*=-1),e.envMapRotation.value.setFromMatrix4(oa.makeRotationFromEuler(aa)),e.flipEnvMap.value=a.isCubeTexture&&!1===a.isRenderTargetTexture?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,g(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,i,a,o,s){i.isMeshBasicMaterial||i.isMeshLambertMaterial?r(e,i):i.isMeshToonMaterial?(r(e,i),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,i)):i.isMeshPhongMaterial?(r(e,i),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,i)):i.isMeshStandardMaterial?(r(e,i),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,i),i.isMeshPhysicalMaterial&&function(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===c&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,i,s)):i.isMeshMatcapMaterial?(r(e,i),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,i)):i.isMeshDepthMaterial?r(e,i):i.isMeshDistanceMaterial?(r(e,i),function(e,n){const r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}(e,i)):i.isMeshNormalMaterial?r(e,i):i.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,i),i.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,i)):i.isPointsMaterial?function(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=.5*i,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i,a,o):i.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i):i.isShadowMaterial?(e.color.value.copy(i.color),e.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1)}}}function la(e,t,n,r){let i={},a={},o=[];const s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,r){const i=e.value,a=t+"_"+n;if(void 0===r[a])return r[a]="number"==typeof i||"boolean"==typeof i?i:i.clone(),!0;{const e=r[a];if("number"==typeof i||"boolean"==typeof i){if(e!==i)return r[a]=i,!0}else if(!1===e.equals(i))return e.copy(i),!0}return!1}function c(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",e),t}function d(t){const n=t.target;n.removeEventListener("dispose",d);const r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}return{bind:function(e,t){const n=t.program;r.uniformBlockBinding(e,n)},update:function(n,u){let f=i[n.id];void 0===f&&(!function(e){const t=e.uniforms;let n=0;const r=16;for(let e=0,i=t.length;e0&&(n+=r-i);e.__size=n,e.__cache={}}(n),f=function(t){const n=function(){for(let e=0;e0),u=!!n.morphAttributes.position,f=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=D;r.toneMapped&&(null!==w&&!0!==w.isXRRenderTarget||(m=C.toneMapping));const h=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=void 0!==h?h.length:0,g=pe.get(r),v=R.state.lights;if(!0===J&&(!0===ee||e!==N)){const t=e===N&&r.id===y;Ae.setState(r,e,t)}let E=!1;r.version===g.__version?g.needsLights&&g.lightsStateVersion!==v.state.version||g.outputColorSpace!==s||i.isBatchedMesh&&!1===g.batching?E=!0:i.isBatchedMesh||!0!==g.batching?i.isBatchedMesh&&!0===g.batchingColor&&null===i.colorTexture||i.isBatchedMesh&&!1===g.batchingColor&&null!==i.colorTexture||i.isInstancedMesh&&!1===g.instancing?E=!0:i.isInstancedMesh||!0!==g.instancing?i.isSkinnedMesh&&!1===g.skinning?E=!0:i.isSkinnedMesh||!0!==g.skinning?i.isInstancedMesh&&!0===g.instancingColor&&null===i.instanceColor||i.isInstancedMesh&&!1===g.instancingColor&&null!==i.instanceColor||i.isInstancedMesh&&!0===g.instancingMorph&&null===i.morphTexture||i.isInstancedMesh&&!1===g.instancingMorph&&null!==i.morphTexture||g.envMap!==l||!0===r.fog&&g.fog!==a?E=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===Ae.numPlanes&&g.numIntersection===Ae.numIntersection?(g.vertexAlphas!==c||g.vertexTangents!==d||g.morphTargets!==u||g.morphNormals!==f||g.morphColors!==p||g.toneMapping!==m||g.morphTargetsCount!==_)&&(E=!0):E=!0:E=!0:E=!0:E=!0:(E=!0,g.__version=r.version);let S=g.currentProgram;!0===E&&(S=Qe(r,t,i));let T=!1,M=!1,x=!1;const A=S.getUniforms(),b=g.uniforms;de.useProgram(S.program)&&(T=!0,M=!0,x=!0);r.id!==y&&(y=r.id,M=!0);if(T||N!==e){de.buffers.depth.getReversed()?(te.copy(e.projectionMatrix),xn(te),Rn(te),A.setValue(Ie,"projectionMatrix",te)):A.setValue(Ie,"projectionMatrix",e.projectionMatrix),A.setValue(Ie,"viewMatrix",e.matrixWorldInverse);const t=A.map.cameraPosition;void 0!==t&&t.setValue(Ie,re.setFromMatrixPosition(e.matrixWorld)),ce.logarithmicDepthBuffer&&A.setValue(Ie,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&A.setValue(Ie,"isOrthographic",!0===e.isOrthographicCamera),N!==e&&(N=e,M=!0,x=!0)}if(i.isSkinnedMesh){A.setOptional(Ie,i,"bindMatrix"),A.setOptional(Ie,i,"bindMatrixInverse");const e=i.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),A.setValue(Ie,"boneTexture",e.boneTexture,me))}i.isBatchedMesh&&(A.setOptional(Ie,i,"batchingTexture"),A.setValue(Ie,"batchingTexture",i._matricesTexture,me),A.setOptional(Ie,i,"batchingIdTexture"),A.setValue(Ie,"batchingIdTexture",i._indirectTexture,me),A.setOptional(Ie,i,"batchingColorTexture"),null!==i._colorsTexture&&A.setValue(Ie,"batchingColorTexture",i._colorsTexture,me));const L=n.morphAttributes;void 0===L.position&&void 0===L.normal&&void 0===L.color||Le.update(i,n,S);(M||g.receiveShadow!==i.receiveShadow)&&(g.receiveShadow=i.receiveShadow,A.setValue(Ie,"receiveShadow",i.receiveShadow));r.isMeshGouraudMaterial&&null!==r.envMap&&(b.envMap.value=l,b.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);r.isMeshStandardMaterial&&null===r.envMap&&null!==t.environment&&(b.envMapIntensity.value=t.environmentIntensity);M&&(A.setValue(Ie,"toneMappingExposure",C.toneMappingExposure),g.needsLights&&(U=x,(P=b).ambientLightColor.needsUpdate=U,P.lightProbe.needsUpdate=U,P.directionalLights.needsUpdate=U,P.directionalLightShadows.needsUpdate=U,P.pointLights.needsUpdate=U,P.pointLightShadows.needsUpdate=U,P.spotLights.needsUpdate=U,P.spotLightShadows.needsUpdate=U,P.rectAreaLights.needsUpdate=U,P.hemisphereLights.needsUpdate=U),a&&!0===r.fog&&Me.refreshFogUniforms(b,a),Me.refreshMaterialUniforms(b,r,Y,X,R.state.transmissionRenderTarget[e.id]),_i.upload(Ie,Je(g),b,me));var P,U;r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(_i.upload(Ie,Je(g),b,me),r.uniformsNeedUpdate=!1);r.isSpriteMaterial&&A.setValue(Ie,"center",i.center);if(A.setValue(Ie,"modelViewMatrix",i.modelViewMatrix),A.setValue(Ie,"normalMatrix",i.normalMatrix),A.setValue(Ie,"modelMatrix",i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){const e=r.uniformsGroups;for(let t=0,n=e.length;t{function n(){r.forEach((function(e){pe.get(e).currentProgram.isReady()&&r.delete(e)})),0!==r.size?setTimeout(n,10):t(e)}null!==le.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let ke=null;function We(){Ye.stop()}function Xe(){Ye.start()}const Ye=new Cn;function Ke(e,t,n,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)R.pushLight(e),e.castShadow&&R.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||Q.intersectsSprite(e)){r&&ie.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ne);const t=Se.update(e),i=e.material;i.visible&&x.push(e,t,i,n,ie.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||Q.intersectsObject(e))){const t=Se.update(e),i=e.material;if(r&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),ie.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),ie.copy(t.boundingSphere.center)),ie.applyMatrix4(e.matrixWorld).applyMatrix4(ne)),Array.isArray(i)){const r=t.groups;for(let a=0,o=r.length;a0&&Ze(i,t,n),a.length>0&&Ze(a,t,n),o.length>0&&Ze(o,t,n),de.buffers.depth.setTest(!0),de.buffers.depth.setMask(!0),de.buffers.color.setMask(!0),de.setPolygonOffset(!1)}function qe(e,t,n,r){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===R.state.transmissionRenderTarget[r.id]&&(R.state.transmissionRenderTarget[r.id]=new I(1,1,{generateMipmaps:!0,type:le.has("EXT_color_buffer_half_float")||le.has("EXT_color_buffer_float")?E:S,minFilter:ot,samples:4,stencilBuffer:o,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:p.workingColorSpace}));const i=R.state.transmissionRenderTarget[r.id],a=r.viewport||O;i.setSize(a.z*C.transmissionResolutionScale,a.w*C.transmissionResolutionScale);const s=C.getRenderTarget();C.setRenderTarget(i),C.getClearColor(V),z=C.getClearAlpha(),z<1&&C.setClearColor(16777215,.5),C.clear(),oe&&Ce.render(n);const l=C.toneMapping;C.toneMapping=D;const d=r.viewport;if(void 0!==r.viewport&&(r.viewport=void 0),R.setupLightsView(r),!0===J&&Ae.setGlobalState(C.clippingPlanes,r),Ze(e,n,r),me.updateMultisampleRenderTarget(i),me.updateRenderTargetMipmap(i),!1===le.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let i=0,a=t.length;i0)for(let t=0,a=n.length;t0&&qe(r,i,e,t),oe&&Ce.render(e),je(x,e,t);null!==w&&0===U&&(me.updateMultisampleRenderTarget(w),me.updateRenderTargetMipmap(w)),!0===e.isScene&&e.onAfterRender(C,e,t),we.resetDefaultState(),y=-1,N=null,b.pop(),b.length>0?(R=b[b.length-1],!0===J&&Ae.setGlobalState(C.clippingPlanes,R.state.camera)):R=null,A.pop(),x=A.length>0?A[A.length-1]:null},this.getActiveCubeFace=function(){return P},this.getActiveMipmapLevel=function(){return U},this.getRenderTarget=function(){return w},this.setRenderTargetTextures=function(e,t,n){const r=pe.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),pe.get(e.texture).__webglTexture=t,pe.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=pe.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const tt=Ie.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){w=e,P=t,U=n;let r=!0,i=null,a=!1,o=!1;if(e){const s=pe.get(e);if(void 0!==s.__useDefaultFramebuffer)de.bindFramebuffer(Ie.FRAMEBUFFER,null),r=!1;else if(void 0===s.__webglFramebuffer)me.setupRenderTarget(e);else if(s.__hasExternalTextures)me.rebindTextures(e,pe.get(e.texture).__webglTexture,pe.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(s.__boundDepthTexture!==t){if(null!==t&&pe.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");me.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(o=!0);const c=pe.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(c[t])?c[t][n]:c[t],a=!0):i=e.samples>0&&!1===me.useMultisampledRTT(e)?pe.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,O.copy(e.viewport),B.copy(e.scissor),G=e.scissorTest}else O.copy(q).multiplyScalar(Y).floor(),B.copy(Z).multiplyScalar(Y).floor(),G=$;0!==n&&(i=tt);if(de.bindFramebuffer(Ie.FRAMEBUFFER,i)&&r&&de.drawBuffers(e,i),de.viewport(O),de.scissor(B),de.setScissorTest(G),a){const r=pe.get(e.texture);Ie.framebufferTexture2D(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,Ie.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(o){const r=pe.get(e.texture),i=t;Ie.framebufferTextureLayer(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,r.__webglTexture,n,i)}else if(null!==e&&0!==n){const t=pe.get(e.texture);Ie.framebufferTexture2D(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,Ie.TEXTURE_2D,t.__webglTexture,n)}y=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=pe.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==o&&(l=l[o]),l){de.bindFramebuffer(Ie.FRAMEBUFFER,l);try{const o=e.textures[s],l=o.format,c=o.type;if(!ce.textureFormatReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!ce.textureTypeReadable(c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&Ie.readBuffer(Ie.COLOR_ATTACHMENT0+s),Ie.readPixels(t,n,r,i,De.convert(l),De.convert(c),a))}finally{const e=null!==w?pe.get(w).__webglFramebuffer:null;de.bindFramebuffer(Ie.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=pe.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==o&&(l=l[o]),l){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){de.bindFramebuffer(Ie.FRAMEBUFFER,l);const o=e.textures[s],c=o.format,d=o.type;if(!ce.textureFormatReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ce.textureTypeReadable(d))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const u=Ie.createBuffer();Ie.bindBuffer(Ie.PIXEL_PACK_BUFFER,u),Ie.bufferData(Ie.PIXEL_PACK_BUFFER,a.byteLength,Ie.STREAM_READ),e.textures.length>1&&Ie.readBuffer(Ie.COLOR_ATTACHMENT0+s),Ie.readPixels(t,n,r,i,De.convert(c),De.convert(d),0);const f=null!==w?pe.get(w).__webglFramebuffer:null;de.bindFramebuffer(Ie.FRAMEBUFFER,f);const p=Ie.fenceSync(Ie.SYNC_GPU_COMMANDS_COMPLETE,0);return Ie.flush(),await An(Ie,p,4),Ie.bindBuffer(Ie.PIXEL_PACK_BUFFER,u),Ie.getBufferSubData(Ie.PIXEL_PACK_BUFFER,0,a),Ie.deleteBuffer(u),Ie.deleteSync(p),a}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const r=Math.pow(2,-n),i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=null!==t?t.x:0,s=null!==t?t.y:0;me.setTexture2D(e,0),Ie.copyTexSubImage2D(Ie.TEXTURE_2D,n,0,0,o,s,i,a),de.unbindTexture()};const nt=Ie.createFramebuffer(),rt=Ie.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=null){let o,s,l,c,d,u,f,p,m;null===a&&(0!==i?(H("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),a=i,i=0):a=0);const h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(null!==n)o=n.max.x-n.min.x,s=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,c=n.min.x,d=n.min.y,u=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-i);o=Math.floor(h.width*t),s=Math.floor(h.height*t),l=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,c=0,d=0,u=0}null!==r?(f=r.x,p=r.y,m=r.z):(f=0,p=0,m=0);const _=De.convert(t.format),g=De.convert(t.type);let v;t.isData3DTexture?(me.setTexture3D(t,0),v=Ie.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(me.setTexture2DArray(t,0),v=Ie.TEXTURE_2D_ARRAY):(me.setTexture2D(t,0),v=Ie.TEXTURE_2D),Ie.pixelStorei(Ie.UNPACK_FLIP_Y_WEBGL,t.flipY),Ie.pixelStorei(Ie.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Ie.pixelStorei(Ie.UNPACK_ALIGNMENT,t.unpackAlignment);const E=Ie.getParameter(Ie.UNPACK_ROW_LENGTH),S=Ie.getParameter(Ie.UNPACK_IMAGE_HEIGHT),T=Ie.getParameter(Ie.UNPACK_SKIP_PIXELS),M=Ie.getParameter(Ie.UNPACK_SKIP_ROWS),x=Ie.getParameter(Ie.UNPACK_SKIP_IMAGES);Ie.pixelStorei(Ie.UNPACK_ROW_LENGTH,h.width),Ie.pixelStorei(Ie.UNPACK_IMAGE_HEIGHT,h.height),Ie.pixelStorei(Ie.UNPACK_SKIP_PIXELS,c),Ie.pixelStorei(Ie.UNPACK_SKIP_ROWS,d),Ie.pixelStorei(Ie.UNPACK_SKIP_IMAGES,u);const R=e.isDataArrayTexture||e.isData3DTexture,A=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=pe.get(e),r=pe.get(t),h=pe.get(n.__renderTarget),_=pe.get(r.__renderTarget);de.bindFramebuffer(Ie.READ_FRAMEBUFFER,h.__webglFramebuffer),de.bindFramebuffer(Ie.DRAW_FRAMEBUFFER,_.__webglFramebuffer);for(let n=0;n nodeObject( new AttributeNode( na * @param {number} [index=0] - The uv index. * @return {AttributeNode} The uv attribute node. */ -const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' ); +const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' ); /** * A node that represents the dimensions of a texture. The texture size is @@ -10235,7 +10235,7 @@ class TextureNode extends UniformNode { */ getDefaultUV() { - return uv( this.value.channel ); + return uv$1( this.value.channel ); } @@ -13064,6 +13064,49 @@ class MaterialReferenceNode extends ReferenceNode { */ const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); +// Normal Mapping Without Precomputed Tangents +// http://www.thetenthplanet.de/archives/1180 + +const uv = uv$1(); + +const q0 = positionView.dFdx(); +const q1 = positionView.dFdy(); +const st0 = uv.dFdx(); +const st1 = uv.dFdy(); + +const N = normalView; + +const q1perp = q1.cross( N ); +const q0perp = N.cross( q0 ); + +const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) ); +const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) ); + +const det = T.dot( T ).max( B.dot( B ) ); +const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() ); + +/** + * Tangent vector in view space, computed dynamically from geometry and UV derivatives. + * Useful for normal mapping without precomputed tangents. + * + * Reference: http://www.thetenthplanet.de/archives/1180 + * + * @tsl + * @type {Node} + */ +const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' ); + +/** + * Bitangent vector in view space, computed dynamically from geometry and UV derivatives. + * Complements the tangentViewFrame for constructing the tangent space basis. + * + * Reference: http://www.thetenthplanet.de/archives/1180 + * + * @tsl + * @type {Node} + */ +const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' ); + /** * TSL object that represents the tangent attribute of the current rendered object. * @@ -13096,7 +13139,29 @@ const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' ); * @tsl * @type {Node} */ -const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' ); +const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => { + + let node; + + if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) { + + node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize(); + + } else { + + node = tangentViewFrame; + + } + + if ( material.flatShading !== true ) { + + node = directionToFaceDirection( node ); + + } + + return node; + +}, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' ); /** * TSL object that represents the vertex tangent in world space of the current rendered object. @@ -13151,7 +13216,29 @@ const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLoc * @tsl * @type {Node} */ -const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' ); +const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => { + + let node; + + if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) { + + node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize(); + + } else { + + node = bitangentViewFrame; + + } + + if ( material.flatShading !== true ) { + + node = directionToFaceDirection( node ); + + } + + return node; + +}, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' ); /** * TSL object that represents the vertex bitangent in world space of the current rendered object. @@ -13207,33 +13294,6 @@ const bentNormalView = /*@__PURE__*/ ( Fn( () => { } ).once() )(); -// Normal Mapping Without Precomputed Tangents -// http://www.thetenthplanet.de/archives/1180 - -const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => { - - const { eye_pos, surf_norm, mapN, uv } = inputs; - - const q0 = eye_pos.dFdx(); - const q1 = eye_pos.dFdy(); - const st0 = uv.dFdx(); - const st1 = uv.dFdy(); - - const N = surf_norm; // normalized - - const q1perp = q1.cross( N ); - const q0perp = N.cross( q0 ); - - const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) ); - const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) ); - - const det = T.dot( T ).max( B.dot( B ) ); - const scale = faceDirection.mul( det.inverseSqrt() ); - - return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize(); - -} ); - /** * This class can be used for applying normals maps to materials. * @@ -13286,7 +13346,7 @@ class NormalMapNode extends TempNode { } - setup( builder ) { + setup( { material } ) { const { normalMapType, scaleNode } = this; @@ -13294,44 +13354,37 @@ class NormalMapNode extends TempNode { if ( scaleNode !== null ) { - normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z ); + let scale = scaleNode; - } + if ( material.flatShading === true ) { - let outputNode = null; + scale = directionToFaceDirection( scale ); - if ( normalMapType === ObjectSpaceNormalMap ) { + } - outputNode = transformNormalToView( normalMap ); + normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z ); - } else if ( normalMapType === TangentSpaceNormalMap ) { + } - const tangent = builder.hasGeometryAttribute( 'tangent' ); + let output = null; - if ( tangent === true ) { + if ( normalMapType === ObjectSpaceNormalMap ) { - outputNode = TBNViewMatrix.mul( normalMap ).normalize(); + output = transformNormalToView( normalMap ); - } else { + } else if ( normalMapType === TangentSpaceNormalMap ) { - outputNode = perturbNormal2Arb( { - eye_pos: positionView, - surf_norm: normalView, - mapN: normalMap, - uv: uv() - } ); - - } + output = TBNViewMatrix.mul( normalMap ).normalize(); } else { console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` ); - outputNode = normalView; // Fallback to default normal view + output = normalView; // Fallback to default normal view } - return outputNode; + return output; } @@ -13354,7 +13407,7 @@ const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1 const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => { // It's used to preserve the same TextureNode instance - const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } ); + const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } ); const Hll = float( sampleTexture( ( uvNode ) => uvNode ) ); @@ -19676,7 +19729,7 @@ class Line2NodeMaterial extends NodeMaterial { this.colorNode = Fn( () => { - const vUv = uv(); + const vUv = uv$1(); if ( useDash ) { @@ -19950,6 +20003,8 @@ class MeshNormalNodeMaterial extends NodeMaterial { } /** + * TSL function for creating an equirect uv node. + * * Can be used to compute texture coordinates for projecting an * equirectangular texture onto a mesh for using it as the scene's * background. @@ -19958,56 +20013,19 @@ class MeshNormalNodeMaterial extends NodeMaterial { * scene.backgroundNode = texture( equirectTexture, equirectUV() ); * ``` * - * @augments TempNode - */ -class EquirectUVNode extends TempNode { - - static get type() { - - return 'EquirectUVNode'; - - } - - /** - * Constructs a new equirect uv node. - * - * @param {Node} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`. - */ - constructor( dirNode = positionWorldDirection ) { - - super( 'vec2' ); - - /** - * A direction vector for sampling why is by default `positionWorldDirection`. - * - * @type {Node} - */ - this.dirNode = dirNode; - - } - - setup() { - - const dir = this.dirNode; - - const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 ); - const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 ); - - return vec2( u, v ); - - } - -} - -/** - * TSL function for creating an equirect uv node. - * * @tsl * @function * @param {?Node} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`. - * @returns {EquirectUVNode} + * @returns {Node} */ -const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 ); +const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => { + + const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 ); + const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 ); + + return vec2( u, v ); + +} ); // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget @@ -21515,10 +21533,10 @@ const bicubic = ( textureNode, texelSize, lod ) => { * @tsl * @function * @param {TextureNode} textureNode - The texture node that should be filtered. - * @param {Node} [lodNode=float(3)] - Defines the LOD to sample from. + * @param {Node} lodNode - Defines the LOD to sample from. * @return {Node} The filtered texture sample. */ -const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => { +const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => { const fLodSize = vec2( textureNode.size( int( lodNode ) ) ); const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) ); @@ -21531,6 +21549,23 @@ const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] } ); +/** + * Applies mipped bicubic texture filtering to the given texture node. + * + * @tsl + * @function + * @param {TextureNode} textureNode - The texture node that should be filtered. + * @param {Node} [strength] - Defines the strength of the bicubic filtering. + * @return {Node} The filtered texture sample. + */ +const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => { + + const lod = strength.mul( maxMipLevel( textureNode ) ); + + return textureBicubicLevel( textureNode, lod ); + +} ); + // // Transmission // @@ -21589,7 +21624,7 @@ const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) ); - return textureBicubic( transmissionSample, lod ); + return textureBicubicLevel( transmissionSample, lod ); } ); @@ -22635,7 +22670,7 @@ const _faceLib = [ 0, 4, 2 ]; -const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize(); +const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize(); const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z ); /** @@ -24991,47 +25026,23 @@ class MeshToonNodeMaterial extends NodeMaterial { } /** + * TSL function for creating a matcap uv node. + * * Can be used to compute texture coordinates for projecting a * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}. * - * @augments TempNode + * @tsl + * @function + * @returns {Node} The matcap UV coordinates. */ -class MatcapUVNode extends TempNode { - - static get type() { - - return 'MatcapUVNode'; - - } +const matcapUV = /*@__PURE__*/ Fn( () => { - /** - * Constructs a new matcap uv node. - */ - constructor() { - - super( 'vec2' ); - - } - - setup() { + const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize(); + const y = positionViewDirection.cross( x ); - const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize(); - const y = positionViewDirection.cross( x ); + return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks - return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks - - } - -} - -/** - * TSL function for creating a matcap uv node. - * - * @tsl - * @function - * @returns {MatcapUVNode} - */ -const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode ); +} ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' ); const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial(); @@ -31682,7 +31693,7 @@ class SpriteSheetUVNode extends Node { * @param {Node} [uvNode=uv()] - The uv node. * @param {Node} [frameNode=float()] - The node that defines the current frame/sprite. */ - constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { + constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) { super( 'vec2' ); @@ -31742,118 +31753,14 @@ class SpriteSheetUVNode extends Node { const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 ); /** + * TSL function for creating a triplanar textures node. + * * Can be used for triplanar texture mapping. * * ```js * material.colorNode = triplanarTexture( texture( diffuseMap ) ); * ``` * - * @augments Node - */ -class TriplanarTexturesNode extends Node { - - static get type() { - - return 'TriplanarTexturesNode'; - - } - - /** - * Constructs a new triplanar textures node. - * - * @param {Node} textureXNode - First texture node. - * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead. - * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead. - * @param {?Node} [scaleNode=float(1)] - The scale node. - * @param {?Node} [positionNode=positionLocal] - Vertex positions in local space. - * @param {?Node} [normalNode=normalLocal] - Normals in local space. - */ - constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { - - super( 'vec4' ); - - /** - * First texture node. - * - * @type {Node} - */ - this.textureXNode = textureXNode; - - /** - * Second texture node. When not set, the shader will sample from `textureXNode` instead. - * - * @type {?Node} - * @default null - */ - this.textureYNode = textureYNode; - - /** - * Third texture node. When not set, the shader will sample from `textureXNode` instead. - * - * @type {?Node} - * @default null - */ - this.textureZNode = textureZNode; - - /** - * The scale node. - * - * @type {Node} - * @default float(1) - */ - this.scaleNode = scaleNode; - - /** - * Vertex positions in local space. - * - * @type {Node} - * @default positionLocal - */ - this.positionNode = positionNode; - - /** - * Normals in local space. - * - * @type {Node} - * @default normalLocal - */ - this.normalNode = normalNode; - - } - - setup() { - - const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; - - // Ref: https://github.com/keijiro/StandardTriplanar - - // Blending factor of triplanar mapping - let bf = normalNode.abs().normalize(); - bf = bf.div( bf.dot( vec3( 1.0 ) ) ); - - // Triplanar mapping - const tx = positionNode.yz.mul( scaleNode ); - const ty = positionNode.zx.mul( scaleNode ); - const tz = positionNode.xy.mul( scaleNode ); - - // Base color - const textureX = textureXNode.value; - const textureY = textureYNode !== null ? textureYNode.value : textureX; - const textureZ = textureZNode !== null ? textureZNode.value : textureX; - - const cx = texture( textureX, tx ).mul( bf.x ); - const cy = texture( textureY, ty ).mul( bf.y ); - const cz = texture( textureZ, tz ).mul( bf.z ); - - return add( cx, cy, cz ); - - } - -} - -/** - * TSL function for creating a triplanar textures node. - * * @tsl * @function * @param {Node} textureXNode - First texture node. @@ -31862,9 +31769,33 @@ class TriplanarTexturesNode extends Node { * @param {?Node} [scaleNode=float(1)] - The scale node. * @param {?Node} [positionNode=positionLocal] - Vertex positions in local space. * @param {?Node} [normalNode=normalLocal] - Normals in local space. - * @returns {TriplanarTexturesNode} + * @returns {Node} */ -const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 ); +const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => { + + // Reference: https://github.com/keijiro/StandardTriplanar + + // Blending factor of triplanar mapping + let bf = normalNode.abs().normalize(); + bf = bf.div( bf.dot( vec3( 1.0 ) ) ); + + // Triplanar mapping + const tx = positionNode.yz.mul( scaleNode ); + const ty = positionNode.zx.mul( scaleNode ); + const tz = positionNode.xy.mul( scaleNode ); + + // Base color + const textureX = textureXNode.value; + const textureY = textureYNode !== null ? textureYNode.value : textureX; + const textureZ = textureZNode !== null ? textureZNode.value : textureX; + + const cx = texture( textureX, tx ).mul( bf.x ); + const cy = texture( textureY, ty ).mul( bf.y ); + const cz = texture( textureZ, tz ).mul( bf.z ); + + return add( cx, cy, cz ); + +} ); /** * TSL function for creating a triplanar textures node. @@ -31877,7 +31808,7 @@ const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setPa * @param {?Node} [scaleNode=float(1)] - The scale node. * @param {?Node} [positionNode=positionLocal] - Vertex positions in local space. * @param {?Node} [normalNode=normalLocal] - Normals in local space. - * @returns {TriplanarTexturesNode} + * @returns {Node} */ const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); @@ -32021,10 +31952,17 @@ class ReflectorNode extends TextureNode { clone() { - const texture = new this.constructor( this.reflectorNode ); - texture._reflectorBaseNode = this._reflectorBaseNode; + const newNode = new this.constructor( this.reflectorNode ); + newNode.uvNode = this.uvNode; + newNode.levelNode = this.levelNode; + newNode.biasNode = this.biasNode; + newNode.sampler = this.sampler; + newNode.depthNode = this.depthNode; + newNode.compareNode = this.compareNode; + newNode.gradNode = this.gradNode; + newNode._reflectorBaseNode = this._reflectorBaseNode; - return texture; + return newNode; } @@ -32566,7 +32504,7 @@ class RTTNode extends TextureNode { const renderTarget = new RenderTarget( width, height, options ); - super( renderTarget.texture, uv() ); + super( renderTarget.texture, uv$1() ); /** * The node to render a texture with. @@ -32885,6 +32823,82 @@ const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMat } ); +/** + * Class representing a node that samples a value using a provided callback function. + * + * @extends Node + */ +class SampleNode extends Node { + + /** + * Returns the type of the node. + * + * @type {string} + * @readonly + * @static + */ + static get type() { + + return 'SampleNode'; + + } + + /** + * Creates an instance of SampleNode. + * + * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value. + */ + constructor( callback ) { + + super(); + + this.callback = callback; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSampleNode = true; + + } + + /** + * Sets up the node by sampling with the default UV accessor. + * + * @returns {Node} The result of the callback function when called with the UV node. + */ + setup() { + + return this.sample( uv$1() ); + + } + + /** + * Calls the callback function with the provided UV node. + * + * @param {Node} uv - The UV node or value to be passed to the callback. + * @returns {Node} The result of the callback function. + */ + sample( uv ) { + + return this.callback( uv ); + + } + +} + +/** + * Helper function to create a SampleNode wrapped as a node object. + * + * @function + * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value. + * @returns {SampleNode} The created SampleNode instance wrapped as a node object. + */ +const sample = ( callback ) => nodeObject( new SampleNode( 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 @@ -34236,7 +34250,16 @@ class PassMultipleTextureNode extends PassTextureNode { clone() { - return new this.constructor( this.passNode, this.textureName, this.previousTexture ); + const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture ); + newNode.uvNode = this.uvNode; + newNode.levelNode = this.levelNode; + newNode.biasNode = this.biasNode; + newNode.sampler = this.sampler; + newNode.depthNode = this.depthNode; + newNode.compareNode = this.compareNode; + newNode.gradNode = this.gradNode; + + return newNode; } @@ -40114,7 +40137,7 @@ class PointLightNode extends AnalyticLightNode { * @param {Node} coord - The uv coordinates. * @return {Node} The result data. */ -const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { +const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => { const uv = coord.mul( 2.0 ); @@ -40134,7 +40157,7 @@ const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { * @param {Node} coord - The uv to generate the circle. * @return {Node} The circle shape. */ -const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => { +const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => { const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) ); @@ -41636,14 +41659,14 @@ const mx_aastep = ( threshold, value ) => { }; const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() ); -const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' ); -const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' ); +const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' ); +const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' ); const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) ); -const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' ); -const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' ); +const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' ); +const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' ); -const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset ); +const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset ); const mx_safepower = ( in1, in2 = 1 ) => { @@ -41655,10 +41678,10 @@ const mx_safepower = ( in1, in2 = 1 ) => { const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot ); -const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { +const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => { texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type @@ -41668,16 +41691,16 @@ const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { }; -const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); +const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); -const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); /** * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM). @@ -42170,6 +42193,7 @@ var TSL = /*#__PURE__*/Object.freeze({ rtt: rtt, sRGBTransferEOTF: sRGBTransferEOTF, sRGBTransferOETF: sRGBTransferOETF, + sample: sample, sampler: sampler, samplerComparison: samplerComparison, saturate: saturate, @@ -42227,6 +42251,7 @@ var TSL = /*#__PURE__*/Object.freeze({ texture3D: texture3D, textureBarrier: textureBarrier, textureBicubic: textureBicubic, + textureBicubicLevel: textureBicubicLevel, textureCubeUV: textureCubeUV, textureLoad: textureLoad, textureSize: textureSize, @@ -42259,7 +42284,7 @@ var TSL = /*#__PURE__*/Object.freeze({ uniformTexture: uniformTexture, unpremultiplyAlpha: unpremultiplyAlpha, userData: userData, - uv: uv, + uv: uv$1, uvec2: uvec2, uvec3: uvec3, uvec4: uvec4, @@ -73841,4 +73866,4 @@ class ClippingGroup extends Group { } -export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents }; +export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents }; diff --git a/build/three.webgpu.min.js b/build/three.webgpu.min.js index be153d6659f821..547653fff79a3f 100644 --- a/build/three.webgpu.min.js +++ b/build/three.webgpu.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2025 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,EventDispatcher as o,MathUtils as u,WebGLCoordinateSystem as l,WebGPUCoordinateSystem as d,ColorManagement as c,SRGBTransfer as h,NoToneMapping as p,StaticDrawUsage as g,InterleavedBuffer as m,InterleavedBufferAttribute as f,DynamicDrawUsage as y,NoColorSpace as b,Texture as x,UnsignedIntType as T,IntType as _,NearestFilter as v,Sphere as N,BackSide as S,DoubleSide as E,Euler as w,CubeTexture as A,CubeReflectionMapping as R,CubeRefractionMapping as C,TangentSpaceNormalMap as M,ObjectSpaceNormalMap as P,InstancedInterleavedBuffer as B,InstancedBufferAttribute as L,DataArrayTexture as F,FloatType as I,FramebufferTexture as D,LinearMipmapLinearFilter as V,DepthTexture as U,Material as O,NormalBlending as k,LineBasicMaterial as G,LineDashedMaterial as z,NoBlending as H,MeshNormalMaterial as $,SRGBColorSpace as W,WebGLCubeRenderTarget as j,BoxGeometry as q,Mesh as X,Scene as K,LinearFilter as Y,CubeCamera as Q,EquirectangularReflectionMapping as Z,EquirectangularRefractionMapping as J,AddOperation as ee,MixOperation as te,MultiplyOperation as re,MeshBasicMaterial as se,MeshLambertMaterial as ie,MeshPhongMaterial as ne,OrthographicCamera as ae,PerspectiveCamera as oe,RenderTarget as ue,LinearSRGBColorSpace as le,RGBAFormat as de,HalfFloatType as ce,CubeUVReflectionMapping as he,BufferGeometry as pe,BufferAttribute as ge,MeshStandardMaterial as me,MeshPhysicalMaterial as fe,MeshToonMaterial as ye,MeshMatcapMaterial as be,SpriteMaterial as xe,PointsMaterial as Te,ShadowMaterial as _e,Uint32BufferAttribute as ve,Uint16BufferAttribute as Ne,arrayNeedsUint32 as Se,Camera as Ee,DepthStencilFormat as we,DepthFormat as Ae,UnsignedInt248Type as Re,UnsignedByteType as Ce,Plane as Me,Object3D as Pe,LinearMipMapLinearFilter as Be,Float32BufferAttribute as Le,UVMapping as Fe,VSMShadowMap as Ie,LessCompare as De,RGFormat as Ve,BasicShadowMap as Ue,SphereGeometry as Oe,LinearMipmapNearestFilter as ke,NearestMipmapLinearFilter as Ge,Float16BufferAttribute as ze,REVISION as He,ArrayCamera as $e,PlaneGeometry as We,FrontSide as je,CustomBlending as qe,AddEquation as Xe,ZeroFactor as Ke,CylinderGeometry as Ye,Quaternion as Qe,WebXRController as Ze,RAD2DEG as Je,PCFShadowMap as et,FrustumArray as tt,Frustum as rt,DataTexture as st,RedIntegerFormat as it,RedFormat as nt,ShortType as at,ByteType as ot,UnsignedShortType as ut,RGIntegerFormat as lt,RGBIntegerFormat as dt,RGBFormat as ct,RGBAIntegerFormat as ht,warnOnce as pt,createCanvasElement as gt,ReverseSubtractEquation as mt,SubtractEquation as ft,OneMinusDstAlphaFactor as yt,OneMinusDstColorFactor as bt,OneMinusSrcAlphaFactor as xt,OneMinusSrcColorFactor as Tt,DstAlphaFactor as _t,DstColorFactor as vt,SrcAlphaSaturateFactor as Nt,SrcAlphaFactor as St,SrcColorFactor as Et,OneFactor as wt,CullFaceNone as At,CullFaceBack as Rt,CullFaceFront as Ct,MultiplyBlending as Mt,SubtractiveBlending as Pt,AdditiveBlending as Bt,NotEqualDepth as Lt,GreaterDepth as Ft,GreaterEqualDepth as It,EqualDepth as Dt,LessEqualDepth as Vt,LessDepth as Ut,AlwaysDepth as Ot,NeverDepth as kt,UnsignedShort4444Type as Gt,UnsignedShort5551Type as zt,UnsignedInt5999Type as Ht,AlphaFormat as $t,RGB_S3TC_DXT1_Format as Wt,RGBA_S3TC_DXT1_Format as jt,RGBA_S3TC_DXT3_Format as qt,RGBA_S3TC_DXT5_Format as Xt,RGB_PVRTC_4BPPV1_Format as Kt,RGB_PVRTC_2BPPV1_Format as Yt,RGBA_PVRTC_4BPPV1_Format as Qt,RGBA_PVRTC_2BPPV1_Format as Zt,RGB_ETC1_Format as Jt,RGB_ETC2_Format as er,RGBA_ETC2_EAC_Format as tr,RGBA_ASTC_4x4_Format as rr,RGBA_ASTC_5x4_Format as sr,RGBA_ASTC_5x5_Format as ir,RGBA_ASTC_6x5_Format as nr,RGBA_ASTC_6x6_Format as ar,RGBA_ASTC_8x5_Format as or,RGBA_ASTC_8x6_Format as ur,RGBA_ASTC_8x8_Format as lr,RGBA_ASTC_10x5_Format as dr,RGBA_ASTC_10x6_Format as cr,RGBA_ASTC_10x8_Format as hr,RGBA_ASTC_10x10_Format as pr,RGBA_ASTC_12x10_Format as gr,RGBA_ASTC_12x12_Format as mr,RGBA_BPTC_Format as fr,RED_RGTC1_Format as yr,SIGNED_RED_RGTC1_Format as br,RED_GREEN_RGTC2_Format as xr,SIGNED_RED_GREEN_RGTC2_Format as Tr,MirroredRepeatWrapping as _r,ClampToEdgeWrapping as vr,RepeatWrapping as Nr,NearestMipmapNearestFilter as Sr,NotEqualCompare as Er,GreaterCompare as wr,GreaterEqualCompare as Ar,EqualCompare as Rr,LessEqualCompare as Cr,AlwaysCompare as Mr,NeverCompare as Pr,LinearTransfer as Br,NotEqualStencilFunc as Lr,GreaterStencilFunc as Fr,GreaterEqualStencilFunc as Ir,EqualStencilFunc as Dr,LessEqualStencilFunc as Vr,LessStencilFunc as Ur,AlwaysStencilFunc as Or,NeverStencilFunc as kr,DecrementWrapStencilOp as Gr,IncrementWrapStencilOp as zr,DecrementStencilOp as Hr,IncrementStencilOp as $r,InvertStencilOp as Wr,ReplaceStencilOp as jr,ZeroStencilOp as qr,KeepStencilOp as Xr,MaxEquation as Kr,MinEquation as Yr,SpotLight as Qr,PointLight as Zr,DirectionalLight as Jr,RectAreaLight as es,AmbientLight as ts,HemisphereLight as rs,LightProbe as ss,LinearToneMapping as is,ReinhardToneMapping as ns,CineonToneMapping as as,ACESFilmicToneMapping as os,AgXToneMapping as us,NeutralToneMapping as ls,Group as ds,Loader as cs,FileLoader as hs,MaterialLoader as ps,ObjectLoader as gs}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,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,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,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,PCFSoftShadowMap,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,TimestampQuery,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding}from"./three.core.min.js";const ms=["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"];class fs{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=ms,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,material:s,object:i}=e;if(t={material:this.getMaterialData(s),geometry:{id:r.id,attributes:this.getAttributesData(r.attributes),indexVersion:r.index?r.index.version:null,drawRange:{start:r.drawRange.start,count:r.drawRange.count}},worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={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 null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};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)}return t}equals(e){const{object:t,material:r,geometry:s}=e,i=this.getRenderObjectData(e);if(!0!==i.worldMatrix.equals(t.matrixWorld))return i.worldMatrix.copy(t.matrixWorld),!1;const n=i.material;for(const e in n){const t=n[e],s=r[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return n[e]=s,!1}if(n.transmission>0){const{width:t,height:r}=e.context;if(i.bufferWidth!==t||i.bufferHeight!==r)return i.bufferWidth=t,i.bufferHeight=r,!1}const a=i.geometry,o=s.attributes,u=a.attributes,l=Object.keys(u),d=Object.keys(o);if(a.id!==s.id)return a.id=s.id,!1;if(l.length!==d.length)return i.geometry.attributes=this.getAttributesData(o),!1;for(const e of l){const t=u[e],r=o[e];if(void 0===r)return delete u[e],!1;if(t.version!==r.version)return t.version=r.version,!1}const c=s.index,h=a.indexVersion,p=c?c.version:null;if(h!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==s.drawRange.start||a.drawRange.count!==s.drawRange.count)return a.drawRange.start=s.drawRange.start,a.drawRange.count=s.drawRange.count,!1;if(i.morphTargetInfluences){let e=!1;for(let r=0;r>>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 bs=e=>ys(e),xs=e=>ys(e),Ts=(...e)=>ys(e);function _s(e,t=!1){const r=[];!0===e.isNode&&(r.push(e.id),e=e.getSelf());for(const{property:s,childNode:i}of vs(e))r.push(ys(s.slice(0,-4)),i.getCacheKey(t));return ys(r)}function*vs(e,t=!1){for(const r in e){if(!0===r.startsWith("_"))continue;const s=e[r];if(!0===Array.isArray(s))for(let e=0;ee.charCodeAt(0))).buffer}var Is=Object.freeze({__proto__:null,arrayBufferToBase64:Ls,base64ToArrayBuffer:Fs,getByteBoundaryFromType:Cs,getCacheKey:_s,getDataFromObject:Bs,getLengthFromType:As,getMemoryLengthFromType:Rs,getNodeChildren:vs,getTypeFromLength:Es,getTypedArrayFromType:ws,getValueFromType:Ps,getValueType:Ms,hash:Ts,hashArray:xs,hashString:bs});const Ds={VERTEX:"vertex",FRAGMENT:"fragment"},Vs={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Us={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Os={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ks=["fragment","vertex"],Gs=["setup","analyze","generate"],zs=[...ks,"compute"],Hs=["x","y","z","w"],$s={analyze:"setup",generate:"analyze"};let Ws=0;class js extends o{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Vs.NONE,this.updateBeforeType=Vs.NONE,this.updateAfterType=Vs.NONE,this.uuid=u.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ws++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Vs.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Vs.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Vs.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of vs(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Ts(_s(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const r=this.getShared(e);if(this!==r)return r.build(e,t);const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const i=$s[e.buildStage];if(i&&!0!==s.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const r of Object.values(t))if(r&&!0===r.isNode){if(!0===r.parents){const t=e.getNodeProperties(r);t.parents=t.parents||[],t.parents.push(this)}r.build(e)}}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const r=this.getNodeType(e),s=e.getDataFromNode(this);n=s.snippet,void 0===n?void 0===s.generated?(s.generated=!0,n=this.generate(e)||"",s.snippet=n):(console.warn("THREE.Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,r,t)}else n=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return vs(this)}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(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}}class qs extends js{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Xs extends js{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(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 Ks extends js{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 Ys extends Ks{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,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 o=0;for(const t of i){if(o>=s){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${r}()' type.`);break}let i,u=t.getNodeType(e),l=e.getTypeLength(u);o+l>s&&(console.error(`THREE.TSL: Length of '${r}()' data exceeds maximum length of output type.`),l=s-o,u=e.getTypeFromLength(l)),o+=l,i=t.build(e,u);const d=e.getComponentType(u);d!==n&&(i=e.format(i,d,n)),a.push(i)}const u=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(u,r,t)}}const Qs=Hs.join("");class Zs extends js{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(Hs.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const 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===Qs.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 Js extends Ks{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}getNodeType(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;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),li=e=>ui(e).split("").sort().join(""),di={setup(e,t){const r=t.shift();return e(Ii(r),...t)},get(e,t,r){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(ni.assign(r,...e),r);if(ai.has(t)){const s=ai.get(t);return e.isStackNode?(...e)=>r.add(s(...e)):(...e)=>s(r,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&ai.has(t.slice(0,t.length-6))){const s=ai.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>r.assign(e[0],s(...e)):(...e)=>r.assign(s(r,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=ui(t),Fi(new Zs(r,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(3).toLowerCase()),r=>Fi(new Js(e,t,Fi(r)));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(4).toLowerCase()),()=>Fi(new ei(Fi(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Fi(new Zs(e,t));if(!0===/^\d+$/.test(t))return Fi(new qs(r,new si(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Fi(new ii(r,e))}return Reflect.get(e,t,r)},set:(e,t,r,s)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,r,s):(s[t].assign(r),!0)},ci=new WeakMap,hi=new WeakMap,pi=function(e,t=null){for(const r in e)e[r]=Fi(e[r],t);return e},gi=function(e,t=null){const r=e.length;for(let s=0;sFi(null!==s?Object.assign(e,s):e);let n,a,o,u=t;function l(t){let r;return r=u?/[a-z]/i.test(u)?u+"()":u:e.type,void 0!==a&&t.lengtho?(console.error(`THREE.TSL: "${r}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?n=(...t)=>i(new e(...Di(l(t)))):null!==r?(r=Fi(r),n=(...s)=>i(new e(t,...Di(l(s)),r))):n=(...r)=>i(new e(t,...Di(l(r)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(u=e,n),n},fi=function(e,...t){return Fi(new e(...Di(t)))};class yi extends js{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let s=hi.get(e.constructor);void 0===s&&(s=new WeakMap,hi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=Fi(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i),o=Fi(i.call(r))}else{const s=t.jsFunc,i=null!==r||s.length>1?s(r||[],e):s(e);o=Fi(i)}return e.subBuildFn=a,t.once&&(s[n]=o),o}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);if("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 r}}class bi extends js{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Ii(e),Fi(new yi(this,e))}setup(){return this.call()}}const xi=[!1,!0],Ti=[0,1,2,3],_i=[-1,-2],vi=[.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],Ni=new Map;for(const e of xi)Ni.set(e,new si(e));const Si=new Map;for(const e of Ti)Si.set(e,new si(e,"uint"));const Ei=new Map([...Si].map((e=>new si(e.value,"int"))));for(const e of _i)Ei.set(e,new si(e,"int"));const wi=new Map([...Ei].map((e=>new si(e.value))));for(const e of vi)wi.set(e,new si(e));for(const e of vi)wi.set(-e,new si(-e));const Ai={bool:Ni,uint:Si,ints:Ei,float:wi},Ri=new Map([...Ni,...wi]),Ci=(e,t)=>Ri.has(e)?Ri.get(e):!0===e.isNode?e:new si(e,t),Mi=function(e,t=null){return(...r)=>{if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every((e=>"object"!=typeof e)))&&(r=[Ps(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return Fi(t.get(r[0]));if(1===r.length){const t=Ci(r[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Fi(t):Fi(new Xs(t,e))}const s=r.map((e=>Ci(e)));return Fi(new Ys(s,e))}},Pi=e=>"object"==typeof e&&null!==e?e.value:e,Bi=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Li(e,t){return new Proxy(new bi(e,t),di)}const Fi=(e,t=null)=>function(e,t=null){const r=Ms(e);if("node"===r){let t=ci.get(e);return void 0===t&&(t=new Proxy(e,di),ci.set(e,t),ci.set(t,t)),t}return null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?Fi(Ci(e,t)):"shader"===r?e.isFn?e:ki(e):e}(e,t),Ii=(e,t=null)=>new pi(e,t),Di=(e,t=null)=>new gi(e,t),Vi=(...e)=>new mi(...e),Ui=(...e)=>new fi(...e);let Oi=0;const ki=(e,t=null)=>{let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:console.error("THREE.TSL: Invalid layout type."),t=null));const s=new Li(e,r),i=(...e)=>{let t;Ii(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];const i=s.call(t);return"void"===r&&i.toStack(),i};if(i.shaderNode=s,i.id=s.id,i.isFn=!0,i.getNodeType=(...e)=>s.getNodeType(...e),i.getCacheKey=(...e)=>s.getCacheKey(...e),i.setLayout=e=>(s.setLayout(e),i),i.once=(e=null)=>(s.once=!0,s.subBuilds=e,i),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+Oi++,type:r,inputs:[]};for(const r in t)"return"!==r&&e.inputs.push({name:r,type:t[r]});t=e}i.setLayout(t)}return i},Gi=e=>{ni=e},zi=()=>ni,Hi=(...e)=>ni.If(...e);function $i(e){return ni&&ni.add(e),e}oi("toStack",$i);const Wi=new Mi("color"),ji=new Mi("float",Ai.float),qi=new Mi("int",Ai.ints),Xi=new Mi("uint",Ai.uint),Ki=new Mi("bool",Ai.bool),Yi=new Mi("vec2"),Qi=new Mi("ivec2"),Zi=new Mi("uvec2"),Ji=new Mi("bvec2"),en=new Mi("vec3"),tn=new Mi("ivec3"),rn=new Mi("uvec3"),sn=new Mi("bvec3"),nn=new Mi("vec4"),an=new Mi("ivec4"),on=new Mi("uvec4"),un=new Mi("bvec4"),ln=new Mi("mat2"),dn=new Mi("mat3"),cn=new Mi("mat4");oi("toColor",Wi),oi("toFloat",ji),oi("toInt",qi),oi("toUint",Xi),oi("toBool",Ki),oi("toVec2",Yi),oi("toIVec2",Qi),oi("toUVec2",Zi),oi("toBVec2",Ji),oi("toVec3",en),oi("toIVec3",tn),oi("toUVec3",rn),oi("toBVec3",sn),oi("toVec4",nn),oi("toIVec4",an),oi("toUVec4",on),oi("toBVec4",un),oi("toMat2",ln),oi("toMat3",dn),oi("toMat4",cn);const hn=Vi(qs).setParameterLength(2),pn=(e,t)=>Fi(new Xs(Fi(e),t));oi("element",hn),oi("convert",pn);oi("append",(e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),$i(e))));class gn extends js{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}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 mn=(e,t)=>Fi(new gn(e,t)),fn=(e,t)=>Fi(new gn(e,t,!0)),yn=Ui(gn,"vec4","DiffuseColor"),bn=Ui(gn,"vec3","EmissiveColor"),xn=Ui(gn,"float","Roughness"),Tn=Ui(gn,"float","Metalness"),_n=Ui(gn,"float","Clearcoat"),vn=Ui(gn,"float","ClearcoatRoughness"),Nn=Ui(gn,"vec3","Sheen"),Sn=Ui(gn,"float","SheenRoughness"),En=Ui(gn,"float","Iridescence"),wn=Ui(gn,"float","IridescenceIOR"),An=Ui(gn,"float","IridescenceThickness"),Rn=Ui(gn,"float","AlphaT"),Cn=Ui(gn,"float","Anisotropy"),Mn=Ui(gn,"vec3","AnisotropyT"),Pn=Ui(gn,"vec3","AnisotropyB"),Bn=Ui(gn,"color","SpecularColor"),Ln=Ui(gn,"float","SpecularF90"),Fn=Ui(gn,"float","Shininess"),In=Ui(gn,"vec4","Output"),Dn=Ui(gn,"float","dashSize"),Vn=Ui(gn,"float","gapSize"),Un=Ui(gn,"float","pointWidth"),On=Ui(gn,"float","IOR"),kn=Ui(gn,"float","Transmission"),Gn=Ui(gn,"float","Thickness"),zn=Ui(gn,"float","AttenuationDistance"),Hn=Ui(gn,"color","AttenuationColor"),$n=Ui(gn,"float","Dispersion");class Wn extends js{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1){super("string"),this.name=e,this.shared=t,this.order=r,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const jn=e=>new Wn(e),qn=(e,t=0)=>new Wn(e,!0,t),Xn=qn("frame"),Kn=qn("render"),Yn=jn("object");class Qn extends ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Yn}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const r=this.getSelf();return e=e.bind(r),super.onUpdate((t=>{const s=e(t,r);void 0!==s&&(this.value=s)}),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.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,r,t)}}const Zn=(e,t)=>{const r=Bi(t||e),s=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Fi(new Qn(s,r))};class Jn extends Ks{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const ea=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Jn(null,r.length,r)}else{const r=e[0],s=e[1];t=new Jn(r,s)}return Fi(t)};oi("toArray",((e,t)=>ea(Array(t).fill(e))));class ta extends Ks{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return Hs.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=e.getNodeProperties(this);s.sourceNode=r,s.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.getNodeType(e),a=r.build(e),o=s.build(e,n),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=a);else if(i){const s=e.getVarFromNode(this,null,n),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)console.error("THREE.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?Di(t):Ii(t[0]),Fi(new sa(Fi(e),t)));oi("call",ia);const na={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class aa extends Ks{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new aa(e,t,r);for(let t=0;t>"===t||"<<"===t)return e.getIntegerType(i);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(i),e.getTypeLength(n));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(i)){if("float"===n)return i;if(e.isVector(n))return e.getVectorFromMatrix(i);if(e.isMatrix(n))return i}else if(e.isMatrix(n)){if("float"===i)return n;if(e.isVector(i))return e.getVectorFromMatrix(n)}return e.getTypeLength(n)>e.getTypeLength(i)?n:i}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e);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),d=i?i.build(e,o):null,c=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===l;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${d} )`,n,t):e.format(`( ${u} ${r} ${d} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${d} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${d} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(c)return e.format(`${c}( ${u}, ${d} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${d} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${d}`,n,t);{let i=`( ${u} ${r} ${d} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return c?e.format(`${c}( ${u}, ${d} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${d} ${r} ${u}`,n,t):e.format(`${u} ${r} ${d}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const oa=Vi(aa,"+").setParameterLength(2,1/0).setName("add"),ua=Vi(aa,"-").setParameterLength(2,1/0).setName("sub"),la=Vi(aa,"*").setParameterLength(2,1/0).setName("mul"),da=Vi(aa,"/").setParameterLength(2,1/0).setName("div"),ca=Vi(aa,"%").setParameterLength(2).setName("mod"),ha=Vi(aa,"==").setParameterLength(2).setName("equal"),pa=Vi(aa,"!=").setParameterLength(2).setName("notEqual"),ga=Vi(aa,"<").setParameterLength(2).setName("lessThan"),ma=Vi(aa,">").setParameterLength(2).setName("greaterThan"),fa=Vi(aa,"<=").setParameterLength(2).setName("lessThanEqual"),ya=Vi(aa,">=").setParameterLength(2).setName("greaterThanEqual"),ba=Vi(aa,"&&").setParameterLength(2,1/0).setName("and"),xa=Vi(aa,"||").setParameterLength(2,1/0).setName("or"),Ta=Vi(aa,"!").setParameterLength(1).setName("not"),_a=Vi(aa,"^^").setParameterLength(2).setName("xor"),va=Vi(aa,"&").setParameterLength(2).setName("bitAnd"),Na=Vi(aa,"~").setParameterLength(2).setName("bitNot"),Sa=Vi(aa,"|").setParameterLength(2).setName("bitOr"),Ea=Vi(aa,"^").setParameterLength(2).setName("bitXor"),wa=Vi(aa,"<<").setParameterLength(2).setName("shiftLeft"),Aa=Vi(aa,">>").setParameterLength(2).setName("shiftRight"),Ra=ki((([e])=>(e.addAssign(1),e))),Ca=ki((([e])=>(e.subAssign(1),e))),Ma=ki((([e])=>{const t=qi(e).toConst();return e.addAssign(1),t})),Pa=ki((([e])=>{const t=qi(e).toConst();return e.subAssign(1),t}));oi("add",oa),oi("sub",ua),oi("mul",la),oi("div",da),oi("mod",ca),oi("equal",ha),oi("notEqual",pa),oi("lessThan",ga),oi("greaterThan",ma),oi("lessThanEqual",fa),oi("greaterThanEqual",ya),oi("and",ba),oi("or",xa),oi("not",Ta),oi("xor",_a),oi("bitAnd",va),oi("bitNot",Na),oi("bitOr",Sa),oi("bitXor",Ea),oi("shiftLeft",wa),oi("shiftRight",Aa),oi("incrementBefore",Ra),oi("decrementBefore",Ca),oi("increment",Ma),oi("decrement",Pa);const Ba=(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),ca(qi(e),qi(t)));oi("modInt",Ba);class La extends Ks{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===La.MAX||e===La.MIN)&&arguments.length>3){let i=new La(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}getNodeType(e){const t=this.method;return t===La.LENGTH||t===La.DISTANCE||t===La.DOT?"float":t===La.CROSS?"vec3":t===La.ALL||t===La.ANY?"bool":t===La.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===La.ONE_MINUS)i=ua(1,t);else if(s===La.RECIPROCAL)i=da(1,t);else if(s===La.DIFFERENCE)i=io(ua(t,r));else if(s===La.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=nn(en(n),0):s=nn(en(s),0);const a=la(s,n).xyz;i=Ya(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===La.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const c=[];return r===La.CROSS?c.push(n.build(e,s),a.build(e,s)):u===l&&r===La.STEP?c.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==l||r!==La.MIN&&r!==La.MAX?r===La.REFRACT?c.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===La.MIX?c.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===d&&r===La.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==La.DFDX&&r!==La.DFDY||(console.warn(`THREE.TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),c.push(n.build(e,i)),null!==a&&c.push(a.build(e,i)),null!==o&&c.push(o.build(e,i))):c.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${c.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}La.ALL="all",La.ANY="any",La.RADIANS="radians",La.DEGREES="degrees",La.EXP="exp",La.EXP2="exp2",La.LOG="log",La.LOG2="log2",La.SQRT="sqrt",La.INVERSE_SQRT="inversesqrt",La.FLOOR="floor",La.CEIL="ceil",La.NORMALIZE="normalize",La.FRACT="fract",La.SIN="sin",La.COS="cos",La.TAN="tan",La.ASIN="asin",La.ACOS="acos",La.ATAN="atan",La.ABS="abs",La.SIGN="sign",La.LENGTH="length",La.NEGATE="negate",La.ONE_MINUS="oneMinus",La.DFDX="dFdx",La.DFDY="dFdy",La.ROUND="round",La.RECIPROCAL="reciprocal",La.TRUNC="trunc",La.FWIDTH="fwidth",La.TRANSPOSE="transpose",La.BITCAST="bitcast",La.EQUALS="equals",La.MIN="min",La.MAX="max",La.STEP="step",La.REFLECT="reflect",La.DISTANCE="distance",La.DIFFERENCE="difference",La.DOT="dot",La.CROSS="cross",La.POW="pow",La.TRANSFORM_DIRECTION="transformDirection",La.MIX="mix",La.CLAMP="clamp",La.REFRACT="refract",La.SMOOTHSTEP="smoothstep",La.FACEFORWARD="faceforward";const Fa=ji(1e-6),Ia=ji(1e6),Da=ji(Math.PI),Va=ji(2*Math.PI),Ua=Vi(La,La.ALL).setParameterLength(1),Oa=Vi(La,La.ANY).setParameterLength(1),ka=Vi(La,La.RADIANS).setParameterLength(1),Ga=Vi(La,La.DEGREES).setParameterLength(1),za=Vi(La,La.EXP).setParameterLength(1),Ha=Vi(La,La.EXP2).setParameterLength(1),$a=Vi(La,La.LOG).setParameterLength(1),Wa=Vi(La,La.LOG2).setParameterLength(1),ja=Vi(La,La.SQRT).setParameterLength(1),qa=Vi(La,La.INVERSE_SQRT).setParameterLength(1),Xa=Vi(La,La.FLOOR).setParameterLength(1),Ka=Vi(La,La.CEIL).setParameterLength(1),Ya=Vi(La,La.NORMALIZE).setParameterLength(1),Qa=Vi(La,La.FRACT).setParameterLength(1),Za=Vi(La,La.SIN).setParameterLength(1),Ja=Vi(La,La.COS).setParameterLength(1),eo=Vi(La,La.TAN).setParameterLength(1),to=Vi(La,La.ASIN).setParameterLength(1),ro=Vi(La,La.ACOS).setParameterLength(1),so=Vi(La,La.ATAN).setParameterLength(1,2),io=Vi(La,La.ABS).setParameterLength(1),no=Vi(La,La.SIGN).setParameterLength(1),ao=Vi(La,La.LENGTH).setParameterLength(1),oo=Vi(La,La.NEGATE).setParameterLength(1),uo=Vi(La,La.ONE_MINUS).setParameterLength(1),lo=Vi(La,La.DFDX).setParameterLength(1),co=Vi(La,La.DFDY).setParameterLength(1),ho=Vi(La,La.ROUND).setParameterLength(1),po=Vi(La,La.RECIPROCAL).setParameterLength(1),go=Vi(La,La.TRUNC).setParameterLength(1),mo=Vi(La,La.FWIDTH).setParameterLength(1),fo=Vi(La,La.TRANSPOSE).setParameterLength(1),yo=Vi(La,La.BITCAST).setParameterLength(2),bo=(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),ha(e,t)),xo=Vi(La,La.MIN).setParameterLength(2,1/0),To=Vi(La,La.MAX).setParameterLength(2,1/0),_o=Vi(La,La.STEP).setParameterLength(2),vo=Vi(La,La.REFLECT).setParameterLength(2),No=Vi(La,La.DISTANCE).setParameterLength(2),So=Vi(La,La.DIFFERENCE).setParameterLength(2),Eo=Vi(La,La.DOT).setParameterLength(2),wo=Vi(La,La.CROSS).setParameterLength(2),Ao=Vi(La,La.POW).setParameterLength(2),Ro=Vi(La,La.POW,2).setParameterLength(1),Co=Vi(La,La.POW,3).setParameterLength(1),Mo=Vi(La,La.POW,4).setParameterLength(1),Po=Vi(La,La.TRANSFORM_DIRECTION).setParameterLength(2),Bo=e=>la(no(e),Ao(io(e),1/3)),Lo=e=>Eo(e,e),Fo=Vi(La,La.MIX).setParameterLength(3),Io=(e,t=0,r=1)=>Fi(new La(La.CLAMP,Fi(e),Fi(t),Fi(r))),Do=e=>Io(e),Vo=Vi(La,La.REFRACT).setParameterLength(3),Uo=Vi(La,La.SMOOTHSTEP).setParameterLength(3),Oo=Vi(La,La.FACEFORWARD).setParameterLength(3),ko=ki((([e])=>{const t=Eo(e.xy,Yi(12.9898,78.233)),r=ca(t,Da);return Qa(Za(r).mul(43758.5453))})),Go=(e,t,r)=>Fo(t,r,e),zo=(e,t,r)=>Uo(t,r,e),Ho=(e,t)=>_o(t,e),$o=(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),so(e,t)),Wo=Oo,jo=qa;oi("all",Ua),oi("any",Oa),oi("equals",bo),oi("radians",ka),oi("degrees",Ga),oi("exp",za),oi("exp2",Ha),oi("log",$a),oi("log2",Wa),oi("sqrt",ja),oi("inverseSqrt",qa),oi("floor",Xa),oi("ceil",Ka),oi("normalize",Ya),oi("fract",Qa),oi("sin",Za),oi("cos",Ja),oi("tan",eo),oi("asin",to),oi("acos",ro),oi("atan",so),oi("abs",io),oi("sign",no),oi("length",ao),oi("lengthSq",Lo),oi("negate",oo),oi("oneMinus",uo),oi("dFdx",lo),oi("dFdy",co),oi("round",ho),oi("reciprocal",po),oi("trunc",go),oi("fwidth",mo),oi("atan2",$o),oi("min",xo),oi("max",To),oi("step",Ho),oi("reflect",vo),oi("distance",No),oi("dot",Eo),oi("cross",wo),oi("pow",Ao),oi("pow2",Ro),oi("pow3",Co),oi("pow4",Mo),oi("transformDirection",Po),oi("mix",Go),oi("clamp",Io),oi("refract",Vo),oi("smoothstep",zo),oi("faceForward",Oo),oi("difference",So),oi("saturate",Do),oi("cbrt",Bo),oi("transpose",fo),oi("rand",ko);class qo extends js{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}getNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),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.cache(),r=this.ifNode.cache(),s=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=r.context({nodeBlock:r}),n.elseNode=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?mn(r).build(e):"";s.nodeProperty=l;const d=i.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${d} ) {\n\n`).addFlowTab();let c=n.build(e,r);if(c&&(u?c=l+" = "+c+";":(c="return "+c+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Xo=Vi(qo).setParameterLength(2,3);oi("select",Xo);class Ko extends js{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const r=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e,t);return e.setContext(r),s}}const Yo=Vi(Ko).setParameterLength(1,2),Qo=(e,t)=>Yo(e,{label:t});oi("context",Yo),oi("label",Qo);class Zo extends js{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;s&&(a=e.isDeterministic(t),o=n?s:a);const u=e.getVectorType(this.getNodeType(e)),l=t.build(e,u),d=e.getVarFromNode(this,r,u,void 0,o),c=e.getPropertyName(d);let h=c;if(o)if(n)h=a?`const ${c}`:`let ${c}`;else{const r=e.getArrayCount(t);h=`const ${e.getVar(d.type,c,r)}`}return e.addLineFlowCode(`${h} = ${l}`,this),c}}const Jo=Vi(Zo),eu=(e,t=null)=>Jo(e,t).toStack(),tu=(e,t=null)=>Jo(e,t,!0).toStack();oi("toVar",eu),oi("toConst",tu);const ru=e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Jo(e));oi("temp",ru);class su extends js{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(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 iu=(e,t,r=null)=>Fi(new su(Fi(e),t,r));class nu extends js{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let 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=iu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.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,Ds.VERTEX);e.flowNodeFromShaderStage(Ds.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const au=Vi(nu).setParameterLength(1,2),ou=e=>au(e);oi("toVarying",au),oi("toVertexStage",ou),oi("varying",((...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),au(...e)))),oi("vertexStage",((...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),au(...e))));const uu=ki((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return Fo(t,r,s)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lu=ki((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return Fo(t,r,s)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),du="WorkingColorSpace";class cu extends Ks{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===du?c.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!==c.enabled&&r!==s&&r&&s?(c.getTransfer(r)===h&&(i=nn(uu(i.rgb),i.a)),c.getPrimaries(r)!==c.getPrimaries(s)&&(i=nn(dn(c._getMatrix(new n,r,s)).mul(i.rgb),i.a)),c.getTransfer(s)===h&&(i=nn(lu(i.rgb),i.a)),i):i}}const hu=(e,t)=>Fi(new cu(Fi(e),du,t)),pu=(e,t)=>Fi(new cu(Fi(e),t,du));oi("workingToColorSpace",hu),oi("colorSpaceToWorking",pu);let gu=class extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class mu extends js{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=Vs.OBJECT}setGroup(e){return this.group=e,this}element(e){return Fi(new gu(this,Fi(e)))}setNodeType(e){const t=Zn(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new fu(e,t,r));class bu extends Ks{static get type(){return"ToneMappingNode"}constructor(e,t=Tu,r=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Ts(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,r=this.toneMapping;if(r===p)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=nn(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const xu=(e,t,r)=>Fi(new bu(e,Fi(t),Fi(r))),Tu=yu("toneMappingExposure","float");oi("toneMapping",((e,t,r)=>xu(t,r,e)));class _u 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=g,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=this.value,s=e.getTypeLength(t),i=this.bufferStride||s,n=this.bufferOffset,a=!0===r.isInterleavedBuffer?r:new m(r,i),o=new f(a,s,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=au(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}}const vu=(e,t=null,r=0,s=0)=>Fi(new _u(e,t,r,s)),Nu=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setUsage(y),Su=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setInstanced(!0),Eu=(e,t=null,r=0,s=0)=>Nu(e,t,r,s).setInstanced(!0);oi("toAttribute",(e=>vu(e.value)));class wu extends js{static get type(){return"ComputeNode"}constructor(e,t,r=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=r,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Vs.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let r=t[0];for(let e=1;eFi(new wu(Fi(e),t,r));oi("compute",Au);class Ru extends js{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),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}}const Cu=(e,t)=>Fi(new Ru(Fi(e),t));oi("cache",Cu);class Mu extends js{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Pu=Vi(Mu).setParameterLength(2);oi("bypass",Pu);class Bu extends js{static get type(){return"RemapNode"}constructor(e,t,r,s=ji(0),i=ji(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=r,this.outLowNode=s,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:r,outLowNode:s,outHighNode:i,doClamp:n}=this;let a=e.sub(t).div(r.sub(t));return!0===n&&(a=a.clamp()),a.mul(i.sub(s)).add(s)}}const Lu=Vi(Bu,null,null,{doClamp:!1}).setParameterLength(3,5),Fu=Vi(Bu).setParameterLength(3,5);oi("remap",Lu),oi("remapClamp",Fu);class Iu extends js{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 Du=Vi(Iu).setParameterLength(1,2),Vu=e=>(e?Xo(e,Du("discard")):Du("discard")).toStack();oi("discard",Vu);class Uu extends Ks{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||p,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||b;return r!==p&&(t=t.toneMapping(r)),s!==b&&s!==c.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Ou=(e,t=null,r=null)=>Fi(new Uu(Fi(e),t,r));oi("renderOutput",Ou);class ku extends Ks{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e),s="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(s.length);let n="";return n+="// #"+s+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+r+" /* ... */\n",n+="// #"+i+"#\n",null!==t?t(e,n):console.log(n),r}}const Gu=(e,t=null)=>Fi(new ku(Fi(e),t));oi("debug",Gu);class zu extends js{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const 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 au(this).build(e,r)}return console.warn(`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 Hu=(e,t=null)=>Fi(new zu(e,t)),$u=(e=0)=>Hu("uv"+(e>0?e:""),"vec2");class Wu extends js{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 ju=Vi(Wu).setParameterLength(1,2);class qu extends Qn{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vs.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 Xu=Vi(qu).setParameterLength(1),Ku=new x;class Yu extends Qn{static get type(){return"TextureNode"}constructor(e=Ku,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.sampler=!0,this.updateMatrix=!1,this.updateType=Vs.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===T?"uvec4":this.value.type===_?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return $u(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Zn(this.value.matrix)),this._matrixUniform.mul(en(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Vs.OBJECT:Vs.NONE,this}setupUV(e,t){const r=this.value;return e.isFlipY()&&(r.image instanceof ImageBitmap&&!0===r.flipY||!0===r.isRenderTargetTexture||!0===r.isFramebufferTexture||!0===r.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this,e)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,r,s,i,n,a,o){const u=this.value;let l;return l=s?e.generateTextureLevel(u,t,r,s,n):i?e.generateTextureBias(u,t,r,i,n):o?e.generateTextureGrad(u,t,r,o,n):a?e.generateTextureCompare(u,t,r,a,n):!1===this.sampler?e.generateTextureLoad(u,t,r,n):e.generateTexture(u,t,r,n),l}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);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:r,biasNode:o,compareNode:u,depthNode:l,gradNode:d}=s,c=this.generateUV(e,t),h=r?r.build(e,"float"):null,p=o?o.build(e,"float"):null,g=l?l.build(e,"int"):null,m=u?u.build(e,"float"):null,f=d?[d[0].build(e,"vec2"),d[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);a=e.getPropertyName(y);const b=this.generateSnippet(e,i,c,h,p,g,m,f);e.addLineFlowCode(`${a} = ${b}`,this),n.snippet=b,n.propertyName=a}let o=a;const u=this.getNodeType(e);return e.needsToWorkingColorSpace(r)&&(o=pu(Du(o,u),r.colorSpace).setup(e).build(e,u)),e.format(o,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}blur(e){const t=this.clone();t.biasNode=Fi(e).mul(Xu(t)),t.referenceNode=this.getSelf();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===v||r.magFilter===v)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Fi(t)}level(e){const t=this.clone();return t.levelNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}size(e){return ju(this,e)}bias(e){const t=this.clone();return t.biasNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}compare(e){const t=this.clone();return t.compareNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}grad(e,t){const r=this.clone();return r.gradNode=[Fi(e),Fi(t)],r.referenceNode=this.getSelf(),Fi(r)}depth(e){const t=this.clone();return t.depthNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}const Qu=Vi(Yu).setParameterLength(1,4).setName("texture"),Zu=(e=Ku,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=Qu(e,t,r,s),i},Ju=(...e)=>Zu(...e).setSampler(!1);class el extends Qn{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const tl=(e,t,r)=>Fi(new el(e,t,r));class rl extends qs{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(),s=this.node.getPaddedType();return e.format(t,s,r)}}class sl extends el{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ms(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Vs.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rFi(new sl(e,t));const nl=Vi(class extends js{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),al=Zn(0,"uint").label("u_cameraIndex").setGroup(qn("cameraIndex")).toVarying("v_cameraIndex"),ol=Zn("float").label("cameraNear").setGroup(Kn).onRenderUpdate((({camera:e})=>e.near)),ul=Zn("float").label("cameraFar").setGroup(Kn).onRenderUpdate((({camera:e})=>e.far)),ll=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);t=il(r).setGroup(Kn).label("cameraProjectionMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrix")}else t=Zn("mat4").label("cameraProjectionMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),dl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);t=il(r).setGroup(Kn).label("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrixInverse")}else t=Zn("mat4").label("cameraProjectionMatrixInverse").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse));return t})).once()(),cl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);t=il(r).setGroup(Kn).label("cameraViewMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraViewMatrix")}else t=Zn("mat4").label("cameraViewMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),hl=Zn("mat4").label("cameraWorldMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorld)),pl=Zn("mat3").label("cameraNormalMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.normalMatrix)),gl=Zn(new r).label("cameraPosition").setGroup(Kn).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),ml=new N;class fl extends js{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Vs.OBJECT,this.uniformNode=new Qn(null)}getNodeType(){const e=this.scope;return e===fl.WORLD_MATRIX?"mat4":e===fl.POSITION||e===fl.VIEW_POSITION||e===fl.DIRECTION||e===fl.SCALE?"vec3":e===fl.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===fl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===fl.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===fl.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===fl.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===fl.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===fl.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),ml.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=ml.radius}}generate(e){const t=this.scope;return t===fl.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===fl.POSITION||t===fl.VIEW_POSITION||t===fl.DIRECTION||t===fl.SCALE?this.uniformNode.nodeType="vec3":t===fl.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}}fl.WORLD_MATRIX="worldMatrix",fl.POSITION="position",fl.SCALE="scale",fl.VIEW_POSITION="viewPosition",fl.DIRECTION="direction",fl.RADIUS="radius";const yl=Vi(fl,fl.DIRECTION).setParameterLength(1),bl=Vi(fl,fl.WORLD_MATRIX).setParameterLength(1),xl=Vi(fl,fl.POSITION).setParameterLength(1),Tl=Vi(fl,fl.SCALE).setParameterLength(1),_l=Vi(fl,fl.VIEW_POSITION).setParameterLength(1),vl=Vi(fl,fl.RADIUS).setParameterLength(1);class Nl extends fl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Sl=Ui(Nl,Nl.DIRECTION),El=Ui(Nl,Nl.WORLD_MATRIX),wl=Ui(Nl,Nl.POSITION),Al=Ui(Nl,Nl.SCALE),Rl=Ui(Nl,Nl.VIEW_POSITION),Cl=Ui(Nl,Nl.RADIUS),Ml=Zn(new n).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),Pl=Zn(new a).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),Bl=ki((e=>e.renderer.overrideNodes.modelViewMatrix||Ll)).once()().toVar("modelViewMatrix"),Ll=cl.mul(El),Fl=ki((e=>(e.context.isHighPrecisionModelViewMatrix=!0,Zn("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highpModelViewMatrix"),Il=ki((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Zn("mat3").onObjectUpdate((({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highpModelNormalViewMatrix"),Dl=Hu("position","vec3"),Vl=Dl.toVarying("positionLocal"),Ul=Dl.toVarying("positionPrevious"),Ol=ki((e=>El.mul(Vl).xyz.toVarying(e.getSubBuildProperty("v_positionWorld"))),"vec3").once(["POSITION"])(),kl=ki((()=>Vl.transformDirection(El).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection")),"vec3").once(["POSITION"])(),Gl=ki((e=>e.context.setupPositionView().toVarying("v_positionView")),"vec3").once(["POSITION"])(),zl=Gl.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Hl extends js{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{renderer:t,material:r}=e;return t.coordinateSystem===l&&r.side===S?"false":e.getFrontFacing()}}const $l=Ui(Hl),Wl=ji($l).mul(2).sub(1),jl=ki((([e],{material:t})=>{const r=t.side;return r===S?e=e.mul(-1):r===E&&(e=e.mul(Wl)),e})),ql=Hu("normal","vec3"),Xl=ki((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),en(0,1,0)):ql),"vec3").once()().toVar("normalLocal"),Kl=Gl.dFdx().cross(Gl.dFdy()).normalize().toVar("normalFlat"),Yl=ki((e=>{let t;return t=!0===e.material.flatShading?Kl:rd(Xl).toVarying("v_normalViewGeometry").normalize(),t}),"vec3").once()().toVar("normalViewGeometry"),Ql=ki((e=>{let t=Yl.transformDirection(cl);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")}),"vec3").once()(),Zl=ki((({subBuildFn:e,material:t,context:r})=>{let s;return"NORMAL"===e||"VERTEX"===e?(s=Yl,!0!==t.flatShading&&(s=jl(s))):s=r.setupNormal().context({getUV:null}),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Jl=Zl.transformDirection(cl).toVar("normalWorld"),ed=ki((({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Zl:t.setupClearcoatNormal().context({getUV:null}),r}),"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),td=ki((([e,t=El])=>{const r=dn(t),s=e.div(en(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz})),rd=ki((([e],t)=>{const r=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==r)return r.transformDirection(e);const s=Ml.mul(e);return cl.transformDirection(s)})),sd=ki((()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Zl))).once(["NORMAL","VERTEX"])(),id=ki((()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Jl))).once(["NORMAL","VERTEX"])(),nd=ki((()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),ed))).once(["NORMAL","VERTEX"])(),ad=new w,od=new a,ud=Zn(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),ld=Zn(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),dd=Zn(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?(ad.copy(r),od.makeRotationFromEuler(ad)):od.identity(),od})),cd=zl.negate().reflect(Zl),hd=zl.negate().refract(Zl,ud),pd=cd.transformDirection(cl).toVar("reflectVector"),gd=hd.transformDirection(cl).toVar("reflectVector"),md=new A;class fd extends Yu{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===R?pd:e.mapping===C?gd:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),en(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return e.renderer.coordinateSystem!==d&&r.isRenderTargetTexture||(t=en(t.x.negate(),t.yz)),dd.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const yd=Vi(fd).setParameterLength(1,4).setName("cubeTexture"),bd=(e=md,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=yd(e,t,r,s),i};class xd extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}}class Td extends js{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=Vs.OBJECT}element(e){return Fi(new xd(this,Fi(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?tl(null,e,this.count):Array.isArray(this.getValueFromReference())?il(null,e):"texture"===e?Zu(null):"cubeTexture"===e?bd(null):Zn(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new Td(e,t,r)),vd=(e,t,r,s)=>Fi(new Td(e,t,s,r));class Nd extends Td{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 Sd=(e,t,r=null)=>Fi(new Nd(e,t,r)),Ed=ki((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Hu("tangent","vec4"))))(),wd=Ed.xyz.toVar("tangentLocal"),Ad=Bl.mul(nn(wd,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView"),Rd=Ad.transformDirection(cl).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),Cd=ki((([e,t],{subBuildFn:r,material:s})=>{let i=e.mul(Ed.w).xyz;return"NORMAL"===r&&!0!==s.flatShading&&(i=i.toVarying(t)),i})).once(["NORMAL"]),Md=Cd(ql.cross(Ed),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Pd=Cd(Xl.cross(wd),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Bd=Cd(Zl.cross(Ad),"v_bitangentView").normalize().toVar("bitangentView"),Ld=Cd(Jl.cross(Rd),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Fd=dn(Ad,Bd,Zl).toVar("TBNViewMatrix"),Id=zl.mul(Fd),Dd=ki((()=>{let e=Pn.cross(zl);return e=e.cross(Pn).normalize(),e=Fo(e,Zl,Cn.mul(xn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})).once()(),Vd=ki((e=>{const{eye_pos:t,surf_norm:r,mapN:s,uv:i}=e,n=t.dFdx(),a=t.dFdy(),o=i.dFdx(),u=i.dFdy(),l=r,d=a.cross(l),c=l.cross(n),h=d.mul(o.x).add(c.mul(u.x)),p=d.mul(o.y).add(c.mul(u.y)),g=h.dot(h).max(p.dot(p)),m=Wl.mul(g.inverseSqrt());return oa(h.mul(s.x,m),p.mul(s.y,m),l.mul(s.z)).normalize()}));class Ud extends Ks{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=M}setup(e){const{normalMapType:t,scaleNode:r}=this;let s=this.node.mul(2).sub(1);null!==r&&(s=en(s.xy.mul(r),s.z));let i=null;if(t===P)i=rd(s);else if(t===M){i=!0===e.hasGeometryAttribute("tangent")?Fd.mul(s).normalize():Vd({eye_pos:Gl,surf_norm:Zl,mapN:s,uv:$u()})}else console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=Zl;return i}}const Od=Vi(Ud).setParameterLength(1,2),kd=ki((({textureNode:e,bumpScale:t})=>{const r=t=>e.cache().context({getUV:e=>t(e.uvNode||$u()),forceUVContext:!0}),s=ji(r((e=>e)));return Yi(ji(r((e=>e.add(e.dFdx())))).sub(s),ji(r((e=>e.add(e.dFdy())))).sub(s)).mul(t)})),Gd=ki((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(Wl),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()}));class zd extends Ks{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=kd({textureNode:this.textureNode,bumpScale:e});return Gd({surf_pos:Gl,surf_norm:Zl,dHdxy:t})}}const Hd=Vi(zd).setParameterLength(1,2),$d=new Map;class Wd extends js{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=$d.get(e);return void 0===r&&(r=Sd(e,t),$d.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===Wd.COLOR){const e=void 0!==t.color?this.getColor(r):en();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Wd.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Wd.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ji(1);else if(r===Wd.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Wd.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Wd.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Wd.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Wd.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===Wd.NORMAL)t.normalMap?(s=Od(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType):s=t.bumpMap?Hd(this.getTexture("bump").r,this.getFloat("bumpScale")):Zl;else if(r===Wd.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Wd.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Wd.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Od(this.getTexture(r),this.getCache(r+"Scale","vec2")):Zl;else if(r===Wd.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===Wd.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(.07,1)}else if(r===Wd.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=ln(Cc.x,Cc.y,Cc.y.negate(),Cc.x).mul(e.rg.mul(2).sub(Yi(1)).normalize().mul(e.b))}else s=Cc;else if(r===Wd.IRIDESCENCE_THICKNESS){const e=_d("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=_d("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Wd.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Wd.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Wd.IOR)s=this.getFloat(r);else if(r===Wd.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Wd.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Wd.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):ji(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Wd.ALPHA_TEST="alphaTest",Wd.COLOR="color",Wd.OPACITY="opacity",Wd.SHININESS="shininess",Wd.SPECULAR="specular",Wd.SPECULAR_STRENGTH="specularStrength",Wd.SPECULAR_INTENSITY="specularIntensity",Wd.SPECULAR_COLOR="specularColor",Wd.REFLECTIVITY="reflectivity",Wd.ROUGHNESS="roughness",Wd.METALNESS="metalness",Wd.NORMAL="normal",Wd.CLEARCOAT="clearcoat",Wd.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Wd.CLEARCOAT_NORMAL="clearcoatNormal",Wd.EMISSIVE="emissive",Wd.ROTATION="rotation",Wd.SHEEN="sheen",Wd.SHEEN_ROUGHNESS="sheenRoughness",Wd.ANISOTROPY="anisotropy",Wd.IRIDESCENCE="iridescence",Wd.IRIDESCENCE_IOR="iridescenceIOR",Wd.IRIDESCENCE_THICKNESS="iridescenceThickness",Wd.IOR="ior",Wd.TRANSMISSION="transmission",Wd.THICKNESS="thickness",Wd.ATTENUATION_DISTANCE="attenuationDistance",Wd.ATTENUATION_COLOR="attenuationColor",Wd.LINE_SCALE="scale",Wd.LINE_DASH_SIZE="dashSize",Wd.LINE_GAP_SIZE="gapSize",Wd.LINE_WIDTH="linewidth",Wd.LINE_DASH_OFFSET="dashOffset",Wd.POINT_SIZE="size",Wd.DISPERSION="dispersion",Wd.LIGHT_MAP="light",Wd.AO="ao";const jd=Ui(Wd,Wd.ALPHA_TEST),qd=Ui(Wd,Wd.COLOR),Xd=Ui(Wd,Wd.SHININESS),Kd=Ui(Wd,Wd.EMISSIVE),Yd=Ui(Wd,Wd.OPACITY),Qd=Ui(Wd,Wd.SPECULAR),Zd=Ui(Wd,Wd.SPECULAR_INTENSITY),Jd=Ui(Wd,Wd.SPECULAR_COLOR),ec=Ui(Wd,Wd.SPECULAR_STRENGTH),tc=Ui(Wd,Wd.REFLECTIVITY),rc=Ui(Wd,Wd.ROUGHNESS),sc=Ui(Wd,Wd.METALNESS),ic=Ui(Wd,Wd.NORMAL),nc=Ui(Wd,Wd.CLEARCOAT),ac=Ui(Wd,Wd.CLEARCOAT_ROUGHNESS),oc=Ui(Wd,Wd.CLEARCOAT_NORMAL),uc=Ui(Wd,Wd.ROTATION),lc=Ui(Wd,Wd.SHEEN),dc=Ui(Wd,Wd.SHEEN_ROUGHNESS),cc=Ui(Wd,Wd.ANISOTROPY),hc=Ui(Wd,Wd.IRIDESCENCE),pc=Ui(Wd,Wd.IRIDESCENCE_IOR),gc=Ui(Wd,Wd.IRIDESCENCE_THICKNESS),mc=Ui(Wd,Wd.TRANSMISSION),fc=Ui(Wd,Wd.THICKNESS),yc=Ui(Wd,Wd.IOR),bc=Ui(Wd,Wd.ATTENUATION_DISTANCE),xc=Ui(Wd,Wd.ATTENUATION_COLOR),Tc=Ui(Wd,Wd.LINE_SCALE),_c=Ui(Wd,Wd.LINE_DASH_SIZE),vc=Ui(Wd,Wd.LINE_GAP_SIZE),Nc=Ui(Wd,Wd.LINE_WIDTH),Sc=Ui(Wd,Wd.LINE_DASH_OFFSET),Ec=Ui(Wd,Wd.POINT_SIZE),wc=Ui(Wd,Wd.DISPERSION),Ac=Ui(Wd,Wd.LIGHT_MAP),Rc=Ui(Wd,Wd.AO),Cc=Zn(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))})),Mc=ki((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Pc extends js{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===Pc.VERTEX)s=e.getVertexIndex();else if(r===Pc.INSTANCE)s=e.getInstanceIndex();else if(r===Pc.DRAW)s=e.getDrawIndex();else if(r===Pc.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===Pc.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==Pc.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=au(this).build(e,t)}return i}}Pc.VERTEX="vertex",Pc.INSTANCE="instance",Pc.SUBGROUP="subgroup",Pc.INVOCATION_LOCAL="invocationLocal",Pc.INVOCATION_SUBGROUP="invocationSubgroup",Pc.DRAW="draw";const Bc=Ui(Pc,Pc.VERTEX),Lc=Ui(Pc,Pc.INSTANCE),Fc=Ui(Pc,Pc.SUBGROUP),Ic=Ui(Pc,Pc.INVOCATION_SUBGROUP),Dc=Ui(Pc,Pc.INVOCATION_LOCAL),Vc=Ui(Pc,Pc.DRAW);class Uc extends js{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=Vs.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:r,instanceColor:s}=this;let{instanceMatrixNode:i,instanceColorNode:n}=this;if(null===i){if(t<=1e3)i=tl(r.array,"mat4",Math.max(t,1)).element(Lc);else{const e=new B(r.array,16,1);this.buffer=e;const t=r.usage===y?Eu:Su,s=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];i=cn(...s)}this.instanceMatrixNode=i}if(s&&null===n){const e=new L(s.array,3),t=s.usage===y?Eu:Su;this.bufferColor=e,n=en(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=i.mul(Vl).xyz;if(Vl.assign(a),e.hasGeometryAttribute("normal")){const e=td(Xl,i);Xl.assign(e)}null!==this.instanceColorNode&&fn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==y&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==y&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}const Oc=Vi(Uc).setParameterLength(2,3);class kc extends Uc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Gc=Vi(kc).setParameterLength(1);class zc extends js{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Lc:this.batchingIdNode=Vc);const t=ki((([e])=>{const t=qi(ju(Ju(this.batchMesh._indirectTexture),0).x),r=qi(e).mod(t),s=qi(e).div(t);return Ju(this.batchMesh._indirectTexture,Qi(r,s)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(qi(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=qi(ju(Ju(s),0).x),n=ji(r).mul(4).toInt().toVar(),a=n.mod(i),o=n.div(i),u=cn(Ju(s,Qi(a,o)),Ju(s,Qi(a.add(1),o)),Ju(s,Qi(a.add(2),o)),Ju(s,Qi(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=ki((([e])=>{const t=qi(ju(Ju(l),0).x),r=e,s=r.mod(t),i=r.div(t);return Ju(l,Qi(s,i)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);fn("vec3","vBatchColor").assign(t)}const d=dn(u);Vl.assign(u.mul(Vl));const c=Xl.div(en(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Xl.assign(h),e.hasGeometryAttribute("tangent")&&wd.mulAssign(d)}}const Hc=Vi(zc).setParameterLength(1);class $c extends qs{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 Wc=Vi($c).setParameterLength(2);class jc extends el{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=Es(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=Os.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){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Wc(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Os.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=vu(this.value),this._varying=au(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(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 qc=(e,t=null,r=0)=>Fi(new jc(e,t,r)),Xc=new WeakMap;class Kc extends js{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Vs.OBJECT,this.skinIndexNode=Hu("skinIndex","uvec4"),this.skinWeightNode=Hu("skinWeight","vec4"),this.bindMatrixNode=_d("bindMatrix","mat4"),this.bindMatrixInverseNode=_d("bindMatrixInverse","mat4"),this.boneMatricesNode=vd("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Vl,this.toPositionNode=Vl,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=oa(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}getSkinnedNormal(e=this.boneMatricesNode,t=Xl){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);let d=oa(s.x.mul(a),s.y.mul(o),s.z.mul(u),s.w.mul(l));return d=n.mul(d).mul(i),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=vd("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Ul)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Bs(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Ul.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Xl.assign(t),e.hasGeometryAttribute("tangent")&&wd.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Xc.get(t)!==e.frameId&&(Xc.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const Yc=e=>Fi(new Kc(e));class Qc extends js{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;eNumber(u)?">=":"<")),a)n=`while ( ${u} )`;else{const r={start:o,end:u},s=r.start,i=r.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=h)switch(typeof h){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(d,h);break;case"string":a=l+" "+h;break;default:h.isNode?a=l+" "+p()+" "+h.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else h="int"===d||"uint"===d?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+h;n=`for ( ${e.getVar(d,l)+" = "+s}; ${l+" "+c+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tFi(new Qc(Di(e,"int"))).toStack(),Jc=()=>Du("break").toStack(),eh=new WeakMap,th=new s,rh=ki((({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=qi(Bc).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ju(e,Qi(u,o)).depth(i).xyz.mul(t)}));class sh extends js{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Zn(1),this.updateType=Vs.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=eh.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 F(m,h,p,a);f.type=I,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=ji(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ju(this.mesh.morphTexture,Qi(qi(e).add(1),qi(Lc))).r):t.assign(_d("morphTargetInfluences","float").element(e).toVar()),Hi(t.notEqual(0),(()=>{!0===s&&Vl.addAssign(rh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(0)})),!0===i&&Xl.addAssign(rh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(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 ih=Vi(sh).setParameterLength(1);class nh extends js{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class ah extends nh{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class oh extends Ko{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:en().toVar("directDiffuse"),directSpecular:en().toVar("directSpecular"),indirectDiffuse:en().toVar("indirectDiffuse"),indirectSpecular:en().toVar("indirectSpecular")};return{radiance:en().toVar("radiance"),irradiance:en().toVar("irradiance"),iblIrradiance:en().toVar("iblIrradiance"),ambientOcclusion:ji(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 uh=Vi(oh);class lh extends nh{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let dh,ch;class hh extends js{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===hh.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Vs.NONE;return this.scope!==hh.SIZE&&this.scope!==hh.VIEWPORT||(e=Vs.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===hh.VIEWPORT?null!==t?ch.copy(t.viewport):(e.getViewport(ch),ch.multiplyScalar(e.getPixelRatio())):null!==t?(dh.width=t.width,dh.height=t.height):e.getDrawingBufferSize(dh)}setup(){const e=this.scope;let r=null;return r=e===hh.SIZE?Zn(dh||(dh=new t)):e===hh.VIEWPORT?Zn(ch||(ch=new s)):Yi(mh.div(gh)),r}generate(e){if(this.scope===hh.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(gh).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}hh.COORDINATE="coordinate",hh.VIEWPORT="viewport",hh.SIZE="size",hh.UV="uv";const ph=Ui(hh,hh.UV),gh=Ui(hh,hh.SIZE),mh=Ui(hh,hh.COORDINATE),fh=Ui(hh,hh.VIEWPORT),yh=fh.zw,bh=mh.sub(fh.xy),xh=bh.div(yh),Th=ki((()=>(console.warn('THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),gh)),"vec2").once()(),_h=new t;class vh extends Yu{static get type(){return"ViewportTextureNode"}constructor(e=ph,t=null,r=null){null===r&&((r=new D).minFilter=V),super(r,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Vs.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(_h);const r=this.value;r.image.width===_h.width&&r.image.height===_h.height||(r.image.width=_h.width,r.image.height=_h.height,r.needsUpdate=!0);const s=r.generateMipmaps;r.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(r),r.generateMipmaps=s}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Nh=Vi(vh).setParameterLength(0,3),Sh=Vi(vh,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Eh=null;class wh extends vh{static get type(){return"ViewportDepthTextureNode"}constructor(e=ph,t=null){null===Eh&&(Eh=new U),super(e,t,Eh)}}const Ah=Vi(wh).setParameterLength(0,2);class Rh extends js{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===Rh.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Rh.DEPTH_BASE)null!==r&&(s=Lh().assign(r));else if(t===Rh.DEPTH)s=e.isPerspectiveCamera?Mh(Gl.z,ol,ul):Ch(Gl.z,ol,ul);else if(t===Rh.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=Ph(r,ol,ul);s=Ch(e,ol,ul)}else s=r;else s=Ch(Gl.z,ol,ul);return s}}Rh.DEPTH_BASE="depthBase",Rh.DEPTH="depth",Rh.LINEAR_DEPTH="linearDepth";const Ch=(e,t,r)=>e.add(t).div(t.sub(r)),Mh=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),Ph=(e,t,r)=>t.mul(r).div(r.sub(t).mul(e).sub(r)),Bh=(e,t,r)=>{t=t.max(1e-6).toVar();const s=Wa(e.negate().div(t)),i=Wa(r.div(t));return s.div(i)},Lh=Vi(Rh,Rh.DEPTH_BASE),Fh=Ui(Rh,Rh.DEPTH),Ih=Vi(Rh,Rh.LINEAR_DEPTH).setParameterLength(0,1),Dh=Ih(Ah());Fh.assign=e=>Lh(e);class Vh extends js{static get type(){return"ClippingNode"}constructor(e=Vh.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===Vh.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===Vh.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return ki((()=>{const r=ji().toVar("distanceToPlane"),s=ji().toVar("distanceToGradient"),i=ji(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=il(t);Zc(n,(({i:t})=>{const n=e.element(t);r.assign(Gl.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Uo(s.negate(),s,r))}))}const a=e.length;if(a>0){const t=il(e),n=ji(1).toVar("intersectionClipOpacity");Zc(a,(({i:e})=>{const i=t.element(e);r.assign(Gl.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Uo(s.negate(),s,r).oneMinus())})),i.mulAssign(n.oneMinus())}yn.a.mulAssign(i),yn.a.equal(0).discard()}))()}setupDefault(e,t){return ki((()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=il(t);Zc(r,(({i:t})=>{const r=e.element(t);Gl.dot(r.xyz).greaterThan(r.w).discard()}))}const s=e.length;if(s>0){const t=il(e),r=Ki(!0).toVar("clipped");Zc(s,(({i:e})=>{const s=t.element(e);r.assign(Gl.dot(s.xyz).greaterThan(s.w).and(r))})),r.discard()}}))()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),ki((()=>{const s=il(e),i=nl(t.getClipDistance());Zc(r,(({i:e})=>{const t=s.element(e),r=Gl.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)}))}))()}}Vh.ALPHA_TO_COVERAGE="alphaToCoverage",Vh.DEFAULT="default",Vh.HARDWARE="hardware";const Uh=ki((([e])=>Qa(la(1e4,Za(la(17,e.x).add(la(.1,e.y)))).mul(oa(.1,io(Za(la(13,e.y).add(e.x)))))))),Oh=ki((([e])=>Uh(Yi(Uh(e.xy),e.z)))),kh=ki((([e])=>{const t=To(ao(lo(e.xyz)),ao(co(e.xyz))),r=ji(1).div(ji(.05).mul(t)).toVar("pixScale"),s=Yi(Ha(Xa(Wa(r))),Ha(Ka(Wa(r)))),i=Yi(Oh(Xa(s.x.mul(e.xyz))),Oh(Xa(s.y.mul(e.xyz)))),n=Qa(Wa(r)),a=oa(la(n.oneMinus(),i.x),la(n,i.y)),o=xo(n,n.oneMinus()),u=en(a.mul(a).div(la(2,o).mul(ua(1,o))),a.sub(la(.5,o)).div(ua(1,o)),ua(1,ua(1,a).mul(ua(1,a)).div(la(2,o).mul(ua(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Io(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Gh extends zu{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 zh=(e=0)=>Fi(new Gh(e)),Hh=ki((([e,t])=>xo(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),$h=ki((([e,t])=>xo(e.div(t.oneMinus()),1))).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Wh=ki((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),jh=ki((([e,t])=>Fo(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),_o(.5,e)))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),qh=ki((([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return nn(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"}]}),Xh=ki((([e])=>nn(e.rgb.mul(e.a),e.a)),{color:"vec4",return:"vec4"}),Kh=ki((([e])=>(Hi(e.a.equal(0),(()=>nn(0))),nn(e.rgb.div(e.a),e.a))),{color:"vec4",return:"vec4"});class Yh extends O{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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+_s(this)}build(e){this.setup(e)}setupObserver(e){return new fs(e)}setup(e){e.context.setupNormal=()=>iu(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=iu(this.setupVertex(e),"VERTEX"),i=this.vertexNode||s;let n;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.add(a);const i=nn(s,yn.a).max(0);n=this.setupOutput(e,i),In.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&In.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=nn(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.samples;this.alphaToCoverage&&t>1?s=Fi(new Vh(Vh.ALPHA_TO_COVERAGE)):e.stack.add(Fi(new Vh))}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.add(Fi(new Vh(Vh.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?Bh(Gl.z,ol,ul):Ch(Gl.z,ol,ul))}null!==s&&Fh.assign(s).toStack()}setupPositionView(){return Bl.mul(Vl).xyz}setupModelViewProjection(){return ll.mul(Gl)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Mc}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&ih(t).toStack(),!0===t.isSkinnedMesh&&Yc(t).toStack(),this.displacementMap){const e=Sd("displacementMap","texture"),t=Sd("displacementScale","float"),r=Sd("displacementBias","float");Vl.addAssign(Xl.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Hc(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Gc(t).toStack(),null!==this.positionNode&&Vl.assign(iu(this.positionNode,"POSITION","vec3")),Vl}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&Ki(this.maskNode).not().discard();let r=this.colorNode?nn(this.colorNode):qd;if(!0===this.vertexColors&&t.hasAttribute("color")&&(r=r.mul(zh())),e.instanceColor){r=fn("vec3","vInstanceColor").mul(r)}if(e.isBatchedMesh&&e._colorsTexture){r=fn("vec3","vBatchColor").mul(r)}yn.assign(r);const s=this.opacityNode?ji(this.opacityNode):Yd;yn.a.assign(yn.a.mul(s));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?ji(this.alphaTestNode):jd,yn.a.lessThanEqual(i).discard()),!0===this.alphaHash&&yn.a.lessThan(kh(Vl)).discard();!1===this.transparent&&this.blending===k&&!1===this.alphaToCoverage?yn.a.assign(1):null===i&&yn.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?en(0):yn.rgb}setupNormal(){return this.normalNode?en(this.normalNode):ic}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Sd("envMap","cubeTexture"):Sd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new lh(Ac)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);if(s&&s.isLightingNode&&t.push(s),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Rc;t.push(new ah(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}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=uh(n,t,r,s)}else null!==r&&(a=en(null!==s?Fo(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(bn.assign(en(i||Kd)),a=a.add(bn)),a}setupFog(e,t){const r=e.fogNode;return r&&(In.assign(t),t=nn(r)),t}setupPremultipliedAlpha(e,t){return Xh(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=O.prototype.toJSON.call(this,e),s=vs(this);r.inputNodes={};for(const{property:t,childNode:i}of s)r.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=i(e.textures),s=i(e.images),n=i(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Qh=new G;class Zh extends Yh{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Qh),this.setValues(e)}}const Jh=new z;class ep extends Yh{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Jh),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ji(this.offsetNode):Sc,t=this.dashScaleNode?ji(this.dashScaleNode):Tc,r=this.dashSizeNode?ji(this.dashSizeNode):_c,s=this.gapSizeNode?ji(this.gapSizeNode):vc;Dn.assign(r),Vn.assign(s);const i=au(Hu("lineDistance").mul(t));(e?i.add(e):i).mod(Dn.add(Vn)).greaterThan(Dn).discard()}}let tp=null;class rp extends vh{static get type(){return"ViewportSharedTextureNode"}constructor(e=ph,t=null){null===tp&&(tp=new D),super(e,t,tp)}updateReference(){return this}}const sp=Vi(rp).setParameterLength(0,2),ip=new z;class np extends Yh{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(ip),this.useColor=e.vertexColors,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=H,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.useColor,i=this._useDash,n=this._useWorldUnits,a=ki((({start:e,end:t})=>{const r=ll.element(2).element(2),s=ll.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return nn(Fo(e.xyz,t.xyz,s),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=ki((()=>{const e=Hu("instanceStart"),t=Hu("instanceEnd"),r=nn(Bl.mul(nn(e,1))).toVar("start"),s=nn(Bl.mul(nn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?ji(this.dashScaleNode):Tc,t=this.offsetNode?ji(this.offsetNode):Sc,r=Hu("instanceDistanceStart"),s=Hu("instanceDistanceEnd");let i=Dl.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),fn("float","lineDistance").assign(i)}n&&(fn("vec3","worldStart").assign(r.xyz),fn("vec3","worldEnd").assign(s.xyz));const o=fh.z.div(fh.w),u=ll.element(2).element(3).equal(-1);Hi(u,(()=>{Hi(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=ll.mul(r),d=ll.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=nn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=Fo(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=fn("vec4","worldPos");o.assign(Dl.y.lessThan(.5).select(r,s));const u=Nc.mul(.5);o.addAssign(nn(Dl.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(nn(Dl.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(nn(a.mul(u),0)),Hi(Dl.y.greaterThan(1).or(Dl.y.lessThan(0)),(()=>{o.subAssign(nn(a.mul(2).mul(u),0))}))),g.assign(ll.mul(o));const l=en().toVar();l.assign(Dl.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=Yi(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(Dl.x.lessThan(0).select(e.negate(),e)),Hi(Dl.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(Dl.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(Nc)),e.assign(e.div(fh.w)),g.assign(Dl.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(nn(e,0,0)))}return g}))();const o=ki((({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 Yi(h,p)}));if(this.colorNode=ki((()=>{const e=$u();if(i){const t=this.dashSizeNode?ji(this.dashSizeNode):_c,r=this.gapSizeNode?ji(this.gapSizeNode):vc;Dn.assign(t),Vn.assign(r);const s=fn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(Dn.add(Vn)).greaterThan(Dn).discard()}const a=ji(1).toVar("alpha");if(n){const e=fn("vec3","worldStart"),s=fn("vec3","worldEnd"),n=fn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:en(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(Nc);if(!i)if(r&&t.samples>1){const e=h.fwidth();a.assign(Uo(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.samples>1){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=ji(s.fwidth()).toVar("dlen");Hi(e.y.abs().greaterThan(1),(()=>{a.assign(Uo(i.oneMinus(),i.add(1),s).oneMinus())}))}else Hi(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=Hu("instanceColorStart"),t=Hu("instanceColorEnd");u=Dl.y.lessThan(.5).select(e,t).mul(qd)}else u=qd;return nn(u,a)}))(),this.transparent){const e=this.opacityNode?ji(this.opacityNode):Yd;this.outputNode=nn(this.colorNode.rgb.mul(e).add(sp().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)}}const ap=e=>Fi(e).mul(.5).add(.5),op=new $;class up extends Yh{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(op),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ji(this.opacityNode):Yd;yn.assign(pu(nn(ap(Zl),e),W))}}class lp extends Ks{static get type(){return"EquirectUVNode"}constructor(e=kl){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,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 Yi(t,r)}}const dp=Vi(lp).setParameterLength(0,1);class cp extends j{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 q(5,5,5),n=dp(kl),a=new Yh;a.colorNode=Zu(t,n,0),a.side=S,a.blending=H;const o=new X(i,a),u=new K;u.add(o),t.minFilter===V&&(t.minFilter=Y);const l=new Q(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.currentGenerateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}}const hp=new WeakMap;class pp extends Ks{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=bd(null);const t=new A;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Vs.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===Z||r===J){if(hp.has(e)){const t=hp.get(e);mp(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new cp(r.height);s.fromEquirectangularTexture(t,e),mp(s.texture,e.mapping),this._cubeTexture=s.texture,hp.set(e,s.texture),e.addEventListener("dispose",gp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function gp(e){const t=e.target;t.removeEventListener("dispose",gp);const r=hp.get(t);void 0!==r&&(hp.delete(t),r.dispose())}function mp(e,t){t===Z?e.mapping=R:t===J&&(e.mapping=C)}const fp=Vi(pp).setParameterLength(1);class yp extends nh{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=fp(this.envNode)}}class bp extends nh{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ji(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class xp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Tp extends xp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(nn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(nn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(yn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case re:s.rgb.assign(Fo(s.rgb,s.rgb.mul(i.rgb),ec.mul(tc)));break;case te:s.rgb.assign(Fo(s.rgb,i.rgb,ec.mul(tc)));break;case ee:s.rgb.addAssign(i.rgb.mul(ec.mul(tc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const _p=new se;class vp extends Yh{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(_p),this.setValues(e)}setupNormal(){return jl(Yl)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new bp(Ac)),t}setupOutgoingLight(){return yn.rgb}setupLightingModel(){return new Tp}}const Np=ki((({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))})),Sp=ki((e=>e.diffuseColor.mul(1/Math.PI))),Ep=ki((({dotNH:e})=>Fn.mul(ji(.5)).add(1).mul(ji(1/Math.PI)).mul(e.pow(Fn)))),wp=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(t).clamp(),s=zl.dot(t).clamp(),i=Np({f0:Bn,f90:1,dotVH:s}),n=ji(.25),a=Ep({dotNH:r});return i.mul(n).mul(a)}));class Ap extends Tp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Sp({diffuseColor:yn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(wp({lightDirection:e})).mul(ec))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Sp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const Rp=new ie;class Cp extends Yh{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Rp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yp(t):null}setupLightingModel(){return new Ap(!1)}}const Mp=new ne;class Pp extends Yh{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Mp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yp(t):null}setupLightingModel(){return new Ap}setupVariants(){const e=(this.shininessNode?ji(this.shininessNode):Xd).max(1e-4);Fn.assign(e);const t=this.specularNode||Qd;Bn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Bp=ki((e=>{if(!1===e.geometry.hasAttribute("normal"))return ji(0);const t=Yl.dFdx().abs().max(Yl.dFdy().abs());return t.x.max(t.y).max(t.z)})),Lp=ki((e=>{const{roughness:t}=e,r=Bp();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s})),Fp=ki((({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(Fa))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Ip=ki((({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(en(e.mul(r),t.mul(s),a).length()),l=a.mul(en(e.mul(i),t.mul(n),o).length());return da(.5,u.add(l)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Dp=ki((({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"}]}),Vp=ji(1/Math.PI),Up=ki((({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=en(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return Vp.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"}]}),Op=ki((({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Zl,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(zl).normalize(),d=n.dot(e).clamp(),c=n.dot(zl).clamp(),h=n.dot(l).clamp(),p=zl.dot(l).clamp();let g,m,f=Np({f0:t,f90:r,dotVH:p});if(Pi(a)&&(f=En.mix(f,i)),Pi(o)){const t=Mn.dot(e),r=Mn.dot(zl),s=Mn.dot(l),i=Pn.dot(e),n=Pn.dot(zl),a=Pn.dot(l);g=Ip({alphaT:Rn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=Up({alphaT:Rn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=Fp({alpha:u,dotNL:d,dotNV:c}),m=Dp({alpha:u,dotNH:h});return f.mul(g).mul(m)})),kp=ki((({roughness:e,dotNV:t})=>{const r=nn(-1,-.0275,-.572,.022),s=nn(1,.0425,1.04,-.04),i=e.mul(r).add(s),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return Yi(-1.04,1.04).mul(n).add(i.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),Gp=ki((e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=kp({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))})),zp=ki((({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(en(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"}]}),Hp=ki((({roughness:e,dotNH:t})=>{const r=e.pow2(),s=ji(1).div(r),i=t.pow2().oneMinus().max(.0078125);return ji(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"}]}),$p=ki((({dotNV:e,dotNL:t})=>ji(1).div(ji(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Wp=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(e).clamp(),s=Zl.dot(zl).clamp(),i=Zl.dot(t).clamp(),n=Hp({roughness:Sn,dotNH:i}),a=$p({dotNV:s,dotNL:r});return Nn.mul(n).mul(a)})),jp=ki((({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=Yi(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"}]}),qp=ki((({f:e})=>{const t=e.length();return To(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Xp=ki((({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,To(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"}]}),Kp=ki((({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=en().toVar();return Hi(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(dn(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=en(0).toVar();f.addAssign(Xp({v1:h,v2:p})),f.addAssign(Xp({v1:p,v2:g})),f.addAssign(Xp({v1:g,v2:m})),f.addAssign(Xp({v1:m,v2:h})),c.assign(en(qp({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"}]}),Yp=ki((({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=en().toVar();return Hi(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=en(0).toVar();d.addAssign(Xp({v1:n,v2:a})),d.addAssign(Xp({v1:a,v2:o})),d.addAssign(Xp({v1:o,v2:l})),d.addAssign(Xp({v1:l,v2:n})),u.assign(en(qp({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"}]}),Qp=1/6,Zp=e=>la(Qp,la(e,la(e,e.negate().add(3)).sub(3)).add(1)),Jp=e=>la(Qp,la(e,la(e,la(3,e).sub(6))).add(4)),eg=e=>la(Qp,la(e,la(e,la(-3,e).add(3)).add(3)).add(1)),tg=e=>la(Qp,Ao(e,3)),rg=e=>Zp(e).add(Jp(e)),sg=e=>eg(e).add(tg(e)),ig=e=>oa(-1,Jp(e).div(Zp(e).add(Jp(e)))),ng=e=>oa(1,tg(e).div(eg(e).add(tg(e)))),ag=(e,t,r)=>{const s=e.uvNode,i=la(s,t.zw).add(.5),n=Xa(i),a=Qa(i),o=rg(a.x),u=sg(a.x),l=ig(a.x),d=ng(a.x),c=ig(a.y),h=ng(a.y),p=Yi(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Yi(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=Yi(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Yi(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=rg(a.y).mul(oa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=sg(a.y).mul(oa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},og=ki((([e,t=ji(3)])=>{const r=Yi(e.size(qi(t))),s=Yi(e.size(qi(t.add(1)))),i=da(1,r),n=da(1,s),a=ag(e,nn(i,r),Xa(t)),o=ag(e,nn(n,s),Ka(t));return Qa(t).mix(a,o)})),ug=ki((([e,t,r,s,i])=>{const n=en(Vo(t.negate(),Ya(e),da(1,s))),a=en(ao(i[0].xyz),ao(i[1].xyz),ao(i[2].xyz));return Ya(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"}]}),lg=ki((([e,t])=>e.mul(Io(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),dg=Sh(),cg=Sh(),hg=ki((([e,t,r],{material:s})=>{const i=(s.side===S?dg:cg).sample(e),n=Wa(gh.x).mul(lg(t,r));return og(i,n)})),pg=ki((([e,t,r])=>(Hi(r.notEqual(0),(()=>{const s=$a(t).negate().div(r);return za(s.negate().mul(e))})),en(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),gg=ki((([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=nn().toVar(),f=en().toVar();const i=d.sub(1).mul(g.mul(.025)),n=en(d.sub(i),d,d.add(i));Zc({start:0,end:3},(({i:i})=>{const d=n.element(i),g=ug(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(nn(y,1))),x=Yi(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Yi(x.x,x.y.oneMinus()));const T=hg(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(pg(ao(g),h,p).element(i)))})),m.a.divAssign(3)}else{const i=ug(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(nn(n,1))),y=Yi(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Yi(y.x,y.y.oneMinus())),m=hg(y,r,d),f=s.mul(pg(ao(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=en(Gp({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return nn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())})),mg=dn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),fg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),yg=ki((({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=Fo(e,t,Uo(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();Hi(a.lessThan(0),(()=>en(1)));const o=a.sqrt(),u=fg(n,e),l=Np({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=ji(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return en(1).add(t).div(en(1).sub(t))})(i.clamp(0,.9999)),g=fg(p,n.toVec3()),m=Np({f0:g,f90:1,dotVH:o}),f=en(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=en(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(en(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Zc({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=en(54856e-17,44201e-17,52481e-17),i=en(1681e3,1795300,2208400),n=en(43278e5,93046e5,66121e5),a=ji(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=en(o.x.add(a),o.y,o.z).div(1.0685e-7),mg.mul(o)})(ji(e).mul(y),ji(e).mul(b)).mul(2);v.addAssign(N.mul(t))})),v.max(en(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"}]}),bg=ki((({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.pow2(),n=Xo(r.lessThan(.25),ji(-339.2).mul(i).add(ji(161.4).mul(r)).sub(25.9),ji(-8.48).mul(i).add(ji(14.3).mul(r)).sub(9.95)),a=Xo(r.lessThan(.25),ji(44).mul(i).sub(ji(23.7).mul(r)).add(3.26),ji(1.97).mul(i).sub(ji(3.27).mul(r)).add(.72));return Xo(r.lessThan(.25),0,ji(.1).mul(r).sub(.025)).add(n.mul(s).add(a).exp()).mul(1/Math.PI).saturate()})),xg=en(.04),Tg=ji(1);class _g extends xp{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}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=en().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=en().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=en().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=en().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=en().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Zl.dot(zl).clamp();this.iridescenceFresnel=yg({outsideIOR:ji(1),eta2:wn,cosTheta1:e,thinFilmThickness:An,baseF0:Bn}),this.iridescenceF0=zp({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Ol,r=gl.sub(Ol).normalize(),s=Jl,i=e.context;i.backdrop=gg(s,r,xn,yn,Bn,Ln,t,El,cl,ll,On,Gn,Hn,zn,this.dispersion?$n:null),i.backdropAlpha=kn,yn.a.mulAssign(Fo(1,i.backdrop.a,kn))}super.start(e)}computeMultiscattering(e,t,r){const s=Zl.dot(zl).clamp(),i=kp({roughness:xn,dotNV:s}),n=(this.iridescenceF0?En.mix(Bn,this.iridescenceF0):Bn).mul(i.x).add(r.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=Bn.add(Bn.oneMinus().mul(.047619)),u=n.mul(o).div(a.mul(o).oneMinus());e.addAssign(n),t.addAssign(u.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(s.mul(Wp({lightDirection:e}))),!0===this.clearcoat){const r=ed.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(Op({lightDirection:e,f0:xg,f90:Tg,roughness:vn,normalView:ed})))}r.directDiffuse.addAssign(s.mul(Sp({diffuseColor:yn.rgb}))),r.directSpecular.addAssign(s.mul(Op({lightDirection:e,f0:Bn,f90:1,roughness:xn,iridescence:this.iridescence,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=Zl,h=zl,p=Gl.toVar(),g=jp({N:c,V:h,roughness:xn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=dn(en(m.x,0,m.y),en(0,1,0),en(m.z,0,m.w)).toVar(),b=Bn.mul(f.x).add(Bn.oneMinus().mul(f.y)).toVar();i.directSpecular.addAssign(e.mul(b).mul(Kp({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(yn).mul(Kp({N:c,V:h,P:p,mInv:dn(1,0,0,0,1,0,0,0,1),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;r.indirectDiffuse.addAssign(t.mul(Sp({diffuseColor:yn})))}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Nn,bg({normal:Zl,viewDir:zl,roughness:Sn}))),!0===this.clearcoat){const e=ed.dot(zl).clamp(),t=Gp({dotNV:e,specularColor:xg,specularF90:Tg,roughness:vn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=en().toVar("singleScattering"),n=en().toVar("multiScattering"),a=r.mul(1/Math.PI);this.computeMultiscattering(i,n,Ln);const o=i.add(n),u=yn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(t.mul(i)),s.indirectSpecular.addAssign(n.mul(a)),s.indirectDiffuse.addAssign(u.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Zl.dot(zl).clamp().add(t),i=xn.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=ed.dot(zl).clamp(),r=Np({dotVH:e,f0:xg,f90:Tg}),s=t.mul(_n.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(_n));t.assign(s)}if(!0===this.sheen){const e=Nn.r.max(Nn.g).max(Nn.b).mul(.157).oneMinus(),r=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(r)}}}const vg=ji(1),Ng=ji(-2),Sg=ji(.8),Eg=ji(-1),wg=ji(.4),Ag=ji(2),Rg=ji(.305),Cg=ji(3),Mg=ji(.21),Pg=ji(4),Bg=ji(4),Lg=ji(16),Fg=ki((([e])=>{const t=en(io(e)).toVar(),r=ji(-1).toVar();return Hi(t.x.greaterThan(t.z),(()=>{Hi(t.x.greaterThan(t.y),(()=>{r.assign(Xo(e.x.greaterThan(0),0,3))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})).Else((()=>{Hi(t.z.greaterThan(t.y),(()=>{r.assign(Xo(e.z.greaterThan(0),2,5))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})),r})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Ig=ki((([e,t])=>{const r=Yi().toVar();return Hi(t.equal(0),(()=>{r.assign(Yi(e.z,e.y).div(io(e.x)))})).ElseIf(t.equal(1),(()=>{r.assign(Yi(e.x.negate(),e.z.negate()).div(io(e.y)))})).ElseIf(t.equal(2),(()=>{r.assign(Yi(e.x.negate(),e.y).div(io(e.z)))})).ElseIf(t.equal(3),(()=>{r.assign(Yi(e.z.negate(),e.y).div(io(e.x)))})).ElseIf(t.equal(4),(()=>{r.assign(Yi(e.x.negate(),e.z).div(io(e.y)))})).Else((()=>{r.assign(Yi(e.x,e.y).div(io(e.z)))})),la(.5,r.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Dg=ki((([e])=>{const t=ji(0).toVar();return Hi(e.greaterThanEqual(Sg),(()=>{t.assign(vg.sub(e).mul(Eg.sub(Ng)).div(vg.sub(Sg)).add(Ng))})).ElseIf(e.greaterThanEqual(wg),(()=>{t.assign(Sg.sub(e).mul(Ag.sub(Eg)).div(Sg.sub(wg)).add(Eg))})).ElseIf(e.greaterThanEqual(Rg),(()=>{t.assign(wg.sub(e).mul(Cg.sub(Ag)).div(wg.sub(Rg)).add(Ag))})).ElseIf(e.greaterThanEqual(Mg),(()=>{t.assign(Rg.sub(e).mul(Pg.sub(Cg)).div(Rg.sub(Mg)).add(Cg))})).Else((()=>{t.assign(ji(-2).mul(Wa(la(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Vg=ki((([e,t])=>{const r=e.toVar();r.assign(la(2,r).sub(1));const s=en(r,1).toVar();return Hi(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"}]}),Ug=ki((([e,t,r,s,i,n])=>{const a=ji(r),o=en(t),u=Io(Dg(a),Ng,n),l=Qa(u),d=Xa(u),c=en(Og(e,o,d,s,i,n)).toVar();return Hi(l.notEqual(0),(()=>{const t=en(Og(e,o,d.add(1),s,i,n)).toVar();c.assign(Fo(c,t,l))})),c})),Og=ki((([e,t,r,s,i,n])=>{const a=ji(r).toVar(),o=en(t),u=ji(Fg(o)).toVar(),l=ji(To(Bg.sub(a),0)).toVar();a.assign(To(a,Bg));const d=ji(Ha(a)).toVar(),c=Yi(Ig(o,u).mul(d.sub(2)).add(1)).toVar();return Hi(u.greaterThan(2),(()=>{c.y.addAssign(d),u.subAssign(3)})),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(la(3,Lg))),c.y.addAssign(la(4,Ha(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(Yi(),Yi())})),kg=ki((({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Ja(s),l=r.mul(u).add(i.cross(r).mul(Za(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return Og(e,l,t,n,a,o)})),Gg=ki((({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=en(Xo(t,r,wo(r,s))).toVar();Hi(h.equal(en(0)),(()=>{h.assign(en(s.z,0,s.x.negate()))})),h.assign(Ya(h));const p=en().toVar();return p.addAssign(i.element(0).mul(kg({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Zc({start:qi(1),end:e},(({i:e})=>{Hi(e.greaterThanEqual(n),(()=>{Jc()}));const t=ji(a.mul(ji(e))).toVar();p.addAssign(i.element(e).mul(kg({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(kg({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))})),nn(p,1)})),zg=[.125,.215,.35,.446,.526,.582],Hg=20,$g=new ae(-1,1,1,-1,0,1),Wg=new oe(90,1),jg=new e;let qg=null,Xg=0,Kg=0;const Yg=(1+Math.sqrt(5))/2,Qg=1/Yg,Zg=[new r(-Yg,Qg,0),new r(Yg,Qg,0),new r(-Qg,0,Yg),new r(Qg,0,Yg),new r(0,Yg,-Qg),new r(0,Yg,Qg),new r(-1,1,-1),new r(1,1,-1),new r(-1,1,1),new r(1,1,1)],Jg=new r,em=new WeakMap,tm=[3,1,5,0,4,2],rm=Vg($u(),Hu("faceIndex")).normalize(),sm=en(rm.x,rm.y,rm.z);class im{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Jg,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}qg=this._renderer.getRenderTarget(),Xg=this._renderer.getActiveCubeFace(),Kg=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!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=um(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=lm(),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===R||e.mapping===C?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?u=zg[o-e+4-1]:0===o&&(u=0),s.push(u);const l=1/(a-2),d=-l,c=1+l,h=[d,d,c,d,c,c,d,d,c,c,d,c],p=6,g=6,m=3,f=2,y=1,b=new Float32Array(m*g*p),x=new Float32Array(f*g*p),T=new Float32Array(y*g*p);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=tm[e];b.set(s,m*g*i),x.set(h,f*g*i);const n=[i,i,i,i,i,i];T.set(n,y*g*i)}const _=new pe;_.setAttribute("position",new ge(b,m)),_.setAttribute("uv",new ge(x,f)),_.setAttribute("faceIndex",new ge(T,y)),t.push(_),i.push(new X(_,null)),n>4&&n--}return{lodPlanes:t,sizeLods:r,sigmas:s,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,s){const i=il(new Array(Hg).fill(0)),n=Zn(new r(0,1,0)),a=Zn(0),o=ji(Hg),u=Zn(0),l=Zn(1),d=Zu(null),c=Zn(0),h=ji(1/t),p=ji(1/s),g=ji(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:sm,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=om("blur");return f.fragmentNode=Gg({...m,latitudinal:u.equal(1)}),em.set(f,m),f}(t,e.width,e.height)}}async _compileMaterial(e){const t=new X(this._lodPlanes[0],e);await this._renderer.compile(t,$g)}_sceneToCubeUV(e,t,r,s,i){const n=Wg;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(jg),u.autoClear=!1;let d=this._backgroundBox;if(null===d){const e=new se({name:"PMREM.Background",side:S,depthWrite:!1,depthTest:!1});d=new X(new q,e)}let c=!1;const h=e.background;h?h.isColor&&(d.material.color.copy(h),e.background=null,c=!0):(d.material.color.copy(jg),c=!0),u.setRenderTarget(s),u.clear(),c&&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;am(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=h}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===R||e.mapping===C;s?null===this._cubemapMaterial&&(this._cubemapMaterial=um(e)):null===this._equirectMaterial&&(this._equirectMaterial=lm(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;am(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,$g)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let t=1;tHg&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${g} samples when the maximum is set to 20`);const m=[];let f=0;for(let e=0;ey-4?s-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(l,$g)}}function nm(e,t){const r=new ue(e,t,{magFilter:Y,minFilter:Y,generateMipmaps:!1,type:ce,format:de,colorSpace:le});return r.texture.mapping=he,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function am(e,t,r,s,i){e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i)}function om(e){const t=new Yh;return t.depthTest=!1,t.depthWrite=!1,t.blending=H,t.name=`PMREM_${e}`,t}function um(e){const t=om("cubemap");return t.fragmentNode=bd(e,sm),t}function lm(e){const t=om("equirect");return t.fragmentNode=Zu(e,dp(sm),0),t}const dm=new WeakMap;function cm(e,t,r){const s=function(e){let t=dm.get(e);void 0===t&&(t=new WeakMap,dm.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 hm extends Ks{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 x;s.isRenderTargetTexture=!0,this._texture=Zu(s),this._width=Zn(0),this._height=Zn(0),this._maxMip=Zn(0),this.updateBeforeType=Vs.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:cm(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new im(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=dd.mul(en(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),Ug(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const pm=Vi(hm).setParameterLength(1,3),gm=new WeakMap;class mm extends nh{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 e=r.isTextureNode?r.value:t[r.property];let s=gm.get(e);void 0===s&&(s=pm(e),gm.set(e,s)),r=s}const s=!0===t.useAnisotropy||t.anisotropy>0?Dd:Zl,i=r.context(fm(xn,s)).mul(ld),n=r.context(ym(Jl)).mul(Math.PI).mul(ld),a=Cu(i),o=Cu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(fm(vn,ed)).mul(ld),t=Cu(e);u.addAssign(t)}}}const fm=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=zl.negate().reflect(t),r=e.mul(e).mix(r,t).normalize(),r=r.transformDirection(cl)),r),getTextureLevel:()=>e}},ym=e=>({getUV:()=>e,getTextureLevel:()=>ji(1)}),bm=new me;class xm extends Yh{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(bm),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new mm(t):null}setupLightingModel(){return new _g}setupSpecular(){const e=Fo(en(.04),yn.rgb,Tn);Bn.assign(e),Ln.assign(1)}setupVariants(){const e=this.metalnessNode?ji(this.metalnessNode):sc;Tn.assign(e);let t=this.roughnessNode?ji(this.roughnessNode):rc;t=Lp({roughness:t}),xn.assign(t),this.setupSpecular(),yn.assign(nn(yn.rgb.mul(e.oneMinus()),yn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Tm=new fe;class _m extends xm{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(Tm),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?ji(this.iorNode):yc;On.assign(e),Bn.assign(Fo(xo(Ro(On.sub(1).div(On.add(1))).mul(Jd),en(1)).mul(Zd),yn.rgb,Tn)),Ln.assign(Fo(Zd,1,Tn))}setupLightingModel(){return new _g(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ji(this.clearcoatNode):nc,t=this.clearcoatRoughnessNode?ji(this.clearcoatRoughnessNode):ac;_n.assign(e),vn.assign(Lp({roughness:t}))}if(this.useSheen){const e=this.sheenNode?en(this.sheenNode):lc,t=this.sheenRoughnessNode?ji(this.sheenRoughnessNode):dc;Nn.assign(e),Sn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ji(this.iridescenceNode):hc,t=this.iridescenceIORNode?ji(this.iridescenceIORNode):pc,r=this.iridescenceThicknessNode?ji(this.iridescenceThicknessNode):gc;En.assign(e),wn.assign(t),An.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?Yi(this.anisotropyNode):cc).toVar();Cn.assign(e.length()),Hi(Cn.equal(0),(()=>{e.assign(Yi(1,0))})).Else((()=>{e.divAssign(Yi(Cn)),Cn.assign(Cn.saturate())})),Rn.assign(Cn.pow2().mix(xn.pow2(),1)),Mn.assign(Fd[0].mul(e.x).add(Fd[1].mul(e.y))),Pn.assign(Fd[1].mul(e.x).sub(Fd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ji(this.transmissionNode):mc,t=this.thicknessNode?ji(this.thicknessNode):fc,r=this.attenuationDistanceNode?ji(this.attenuationDistanceNode):bc,s=this.attenuationColorNode?en(this.attenuationColorNode):xc;if(kn.assign(e),Gn.assign(t),zn.assign(r),Hn.assign(s),this.useDispersion){const e=this.dispersionNode?ji(this.dispersionNode):wc;$n.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?en(this.clearcoatNormalNode):oc}setup(e){e.context.setupClearcoatNormal=()=>iu(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.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 vm extends _g{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(Zl.mul(a)).normalize(),h=ji(zl.dot(c.negate()).saturate().pow(l).mul(d)),p=en(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Nm extends _m{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=ji(.1),this.thicknessAmbientNode=ji(0),this.thicknessAttenuationNode=ji(.1),this.thicknessPowerNode=ji(2),this.thicknessScaleNode=ji(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new vm(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 Sm=ki((({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=Yi(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Sd("gradientMap","texture").context({getUV:()=>i});return en(e.r)}{const e=i.fwidth().mul(.5);return Fo(en(.7),en(1),Uo(ji(.7).sub(e.x),ji(.7).add(e.x),i.x))}}));class Em extends xp{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Sm({normal:ql,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Sp({diffuseColor:yn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Sp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const wm=new ye;class Am extends Yh{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(wm),this.setValues(e)}setupLightingModel(){return new Em}}class Rm extends Ks{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=en(zl.z,0,zl.x.negate()).normalize(),t=zl.cross(e);return Yi(e.dot(Zl),t.dot(Zl)).mul(.495).add(.5)}}const Cm=Ui(Rm),Mm=new be;class Pm extends Yh{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Mm),this.setValues(e)}setupVariants(e){const t=Cm;let r;r=e.material.matcap?Sd("matcap","texture").context({getUV:()=>t}):en(Fo(.2,.8,t.y)),yn.rgb.mulAssign(r.rgb)}}class Bm extends Ks{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode: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=cn(nn(1,0,0,0),nn(0,Ja(e.x),Za(e.x).negate(),0),nn(0,Za(e.x),Ja(e.x),0),nn(0,0,0,1)),i=cn(nn(Ja(e.y),0,Za(e.y),0),nn(0,1,0,0),nn(Za(e.y).negate(),0,Ja(e.y),0),nn(0,0,0,1)),n=cn(nn(Ja(e.z),Za(e.z).negate(),0,0),nn(Za(e.z),Ja(e.z),0,0),nn(0,0,1,0),nn(0,0,0,1));return s.mul(i).mul(n).mul(nn(r,1)).xyz}}}const Lm=Vi(Bm).setParameterLength(2),Fm=new xe;class Im extends Yh{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(Fm),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,s=this.sizeAttenuation,{positionNode:i,rotationNode:n,scaleNode:a}=this,o=Bl.mul(en(i||0));let u=Yi(El[0].xyz.length(),El[1].xyz.length());if(null!==a&&(u=u.mul(Yi(a))),!1===s)if(r.isPerspectiveCamera)u=u.mul(o.z.negate());else{const e=ji(2).div(ll.element(1).element(1));u=u.mul(e.mul(2))}let l=Dl.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>Fi(new mu(e,t,r)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=ji(n||uc),c=Lm(l,d);return nn(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 Dm=new Te;class Vm extends Im{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(Dm),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Bl.mul(en(e||Vl)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:r,scaleNode:s,sizeNode:i}=this,n=Dl.xy.toVar(),a=fh.z.div(fh.w);if(r&&r.isNode){const e=ji(r);n.assign(Lm(n,e))}let o=null!==i?Yi(i):Ec;return!0===this.sizeAttenuation&&(o=o.mul(o.div(Gl.z.negate()))),s&&s.isNode&&(o=o.mul(Yi(s))),n.mulAssign(o.mul(2)),n.assign(n.div(fh.z)),n.y.assign(n.y.mul(a)),n.assign(n.mul(t.w)),t.addAssign(nn(n,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class Um extends xp{constructor(){super(),this.shadowNode=ji(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){yn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(yn.rgb)}}const Om=new _e;class km extends Yh{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Om),this.setValues(e)}setupLightingModel(){return new Um}}const Gm=mn("vec3"),zm=mn("vec3"),Hm=mn("vec3");class $m extends xp{constructor(){super()}start(e){const{material:t,context:r}=e,s=mn("vec3"),i=mn("vec3");Hi(gl.sub(Ol).length().greaterThan(Cl.mul(2)),(()=>{s.assign(gl),i.assign(Ol)})).Else((()=>{s.assign(Ol),i.assign(gl)}));const n=i.sub(s),a=Zn("int").onRenderUpdate((({material:e})=>e.steps)),o=n.length().div(a).toVar(),u=n.normalize().toVar(),l=ji(0).toVar(),d=en(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(o)),Zc(a,(()=>{const i=s.add(u.mul(l)),n=cl.mul(nn(i,1)).xyz;let a;null!==t.depthNode&&(zm.assign(Ih(Mh(n.z,ol,ul))),r.sceneDepthNode=Ih(t.depthNode).toVar()),r.positionWorld=i,r.shadowPositionWorld=i,r.positionView=n,Gm.assign(0),t.scatteringNode&&(a=t.scatteringNode({positionRay:i})),super.start(e),a&&Gm.mulAssign(a);const c=Gm.mul(.01).negate().mul(o).exp();d.mulAssign(c),l.addAssign(o)})),Hm.addAssign(d.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?Hi(r.greaterThanEqual(zm),(()=>{Gm.addAssign(e)})):Gm.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(Yp({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(Hm)}}class Wm extends Yh{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=S,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new $m}}class jm{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,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,null!==this._animationLoop&&this._animationLoop(t,r)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class qm{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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)}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.version),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&&(r+=e.uuid+","),r+=e.receiveShadow+",",bs(r)}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=Ts(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ts(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Ym=[];class Qm{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);Ym[0]=e,Ym[1]=t,Ym[2]=n,Ym[3]=i;let l=u.get(Ym);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Ym,l)):(l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Ym.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new qm)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new Km(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Zm{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 Jm=1,ef=2,tf=3,rf=4,sf=16;class nf extends Zm{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===Jm?this.backend.createAttribute(e):t===ef?this.backend.createIndexAttribute(e):t===tf?this.backend.createStorageAttribute(e):t===rf&&this.backend.createIndirectStorageAttribute(e),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version{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)};t.addEventListener("dispose",r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,tf):this.updateAttribute(e,Jm);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,ef);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,rf)}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}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=of(t),e.set(t,r)):r.version!==af(t)&&(this.attributes.delete(r),r=of(t),e.set(t,r)),s=r}return s}}class lf{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,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):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class df{constructor(e){this.cacheKey=e,this.usedTimes=0}}class cf extends df{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class hf extends df{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let pf=0;class gf{constructor(e,t,r,s=null,i=null){this.id=pf++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class mf extends Zm{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend: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 gf(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.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 gf(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new gf(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.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}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 hf(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 cf(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)}_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 ff extends Zm{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))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?rf:tf;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(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?rf:tf;this.attributes.update(e,r)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(s=!0);const o=t.update(),u=t.texture;o&&this.textures.updateTexture(u);const l=r.get(u);if(void 0!==l.externalTexture||e.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===r.isWebGPUBackend&&void 0===l.texture&&void 0===l.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,u,t.textureNode.value,s),this.textures.updateTexture(u),s=!0),!0===u.isStorageTexture){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)}}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function yf(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 bf(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 xf(e){return(e.transmission>0||e.transmissionNode)&&e.side===E&&!1===e.forceSinglePass}class Tf{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?(xf(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?(xf(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||yf),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||bf),this.transparent.length>1&&this.transparent.sort(t||bf)}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 U,l.format=e.stencilBuffer?we:Ae,l.type=e.stencilBuffer?Re:T,l.image.width=o,l.image.height=u,l.image.depth=a.depth,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{e.removeEventListener("dispose",t);for(let e=0;e0){const s=e.image;if(void 0===s)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)console.warn("THREE.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),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version}if(!0!==r.initialized){r.initialized=!0,r.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}r.version=e.version}getSize(e,t=Mf){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),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.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class Bf extends e{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Lf extends gn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class Ff extends js{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const r=new Li(t);return this._currentCond=Xo(e,r),this.add(this._currentCond)}ElseIf(e,t){const r=new Li(t),s=Xo(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Li(e),this}Switch(e){return this._expressionNode=Fi(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let r=0;r"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=0;for(const r of this.membersLayout){const s=r.type,i=Rs(s)*e,n=t%8,a=n%Cs(s),o=n+a;t+=a,0!==o&&8-oe.name===t));return r?r.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.addInclude(this)}generate(e){return this.getNodeType(e)}}class Vf extends js{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structLayoutNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structLayoutNode.getNodeType(e)}getMemberType(e,t){return this.structLayoutNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structLayoutNode.membersLayout,this.values)}`,this),t.name}}class Uf extends js{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t{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)})),$f=(e,t)=>Ao(la(4,e.mul(ua(1,e))),t),Wf=ki((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),jf=ki((([e])=>en(Wf(e.z.add(Wf(e.y.mul(1)))),Wf(e.z.add(Wf(e.x.mul(1)))),Wf(e.y.add(Wf(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),qf=ki((([e,t,r])=>{const s=en(e).toVar(),i=ji(1.4).toVar(),n=ji(0).toVar(),a=en(s).toVar();return Zc({start:ji(0),end:ji(3),type:"float",condition:"<="},(()=>{const e=en(jf(a.mul(2))).toVar();s.addAssign(e.add(r.mul(ji(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=ji(Wf(s.z.add(Wf(s.x.add(Wf(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 Xf extends js{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null,this.global=!0}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let r=this._candidateFnCall;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._candidateFnCall=r=s(...t)}return r}}const Kf=Vi(Xf),Yf=e=>(...t)=>Kf(e,...t),Qf=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.time)),Zf=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.deltaTime)),Jf=Zn(0,"uint").setGroup(Kn).onRenderUpdate((e=>e.frameId)),ey=ki((([e,t,r=Yi(.5)])=>Lm(e.sub(r),t).add(r))),ty=ki((([e,t,r=Yi(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))})),ry=ki((({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=El.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=El;const i=cl.mul(s);return Pi(t)&&(i[0][0]=El[0].length(),i[0][1]=0,i[0][2]=0),Pi(r)&&(i[1][0]=0,i[1][1]=El[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,ll.mul(i).mul(Vl)})),sy=ki((([e=null])=>{const t=Ih();return Ih(Ah(e)).sub(t).lessThan(0).select(ph,e)}));class iy extends js{static get type(){return"SpriteSheetUVNode"}constructor(e,t=$u(),r=ji(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=r}setup(){const{frameNode:e,uvNode:t,countNode:r}=this,{width:s,height:i}=r,n=e.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=r.reciprocal(),l=Yi(a,o);return t.add(l).mul(u)}}const ny=Vi(iy).setParameterLength(3);class ay extends js{static get type(){return"TriplanarTexturesNode"}constructor(e,t=null,r=null,s=ji(1),i=Vl,n=Xl){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=r,this.scaleNode=s,this.positionNode=i,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:r,scaleNode:s,positionNode:i,normalNode:n}=this;let a=n.abs().normalize();a=a.div(a.dot(en(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=Zu(d,o).mul(a.x),g=Zu(c,u).mul(a.y),m=Zu(h,l).mul(a.z);return oa(p,g,m)}}const oy=Vi(ay).setParameterLength(1,6),uy=new Me,ly=new r,dy=new r,cy=new r,hy=new a,py=new r(0,0,-1),gy=new s,my=new r,fy=new r,yy=new s,by=new t,xy=new ue,Ty=ph.flipX();xy.depthTexture=new U(1,1);let _y=!1;class vy extends Yu{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||xy.texture,Ty),this._reflectorBaseNode=e.reflector||new Ny(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=Fi(new vy({defaultTexture:xy.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._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class Ny extends js{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new Pe,resolution:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1}=t;this.textureNode=e,this.target=r,this.resolution=s,this.generateMipmaps=i,this.bounces=n,this.depth=a,this.updateBeforeType=n?Vs.RENDER:Vs.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolution;t.getDrawingBufferSize(by),e.setSize(Math.round(by.width*r),Math.round(by.height*r))}setup(e){return this._updateResolution(xy,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 ue(0,0,{type:ce}),!0===this.generateMipmaps&&(t.texture.minFilter=Be,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new U),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&_y)return!1;_y=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(by),this._updateResolution(o,s),dy.setFromMatrixPosition(n.matrixWorld),cy.setFromMatrixPosition(r.matrixWorld),hy.extractRotation(n.matrixWorld),ly.set(0,0,1),ly.applyMatrix4(hy),my.subVectors(dy,cy);let u=!1;if(!0===my.dot(ly)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(_y=!1);u=!0}my.reflect(ly).negate(),my.add(dy),hy.extractRotation(r.matrixWorld),py.set(0,0,-1),py.applyMatrix4(hy),py.add(cy),fy.subVectors(dy,py),fy.reflect(ly).negate(),fy.add(dy),a.coordinateSystem=r.coordinateSystem,a.position.copy(my),a.up.set(0,1,0),a.up.applyMatrix4(hy),a.up.reflect(ly),a.lookAt(fy),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),uy.setFromNormalAndCoplanarPoint(ly,dy),uy.applyMatrix4(a.matrixWorldInverse),gy.set(uy.normal.x,uy.normal.y,uy.normal.z,uy.constant);const l=a.projectionMatrix;yy.x=(Math.sign(gy.x)+l.elements[8])/l.elements[0],yy.y=(Math.sign(gy.y)+l.elements[9])/l.elements[5],yy.z=-1,yy.w=(1+l.elements[10])/l.elements[14],gy.multiplyScalar(1/gy.dot(yy));l.elements[2]=gy.x,l.elements[6]=gy.y,l.elements[10]=s.coordinateSystem===d?gy.z-0:gy.z+1-0,l.elements[14]=gy.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const c=s.getRenderTarget(),h=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0,u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),s.setMRT(h),s.setRenderTarget(c),s.autoClear=p,i.visible=!0,_y=!1,this.forceUpdate=!1}}const Sy=new ae(-1,1,1,-1,0,1);class Ey extends pe{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Le([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Le(t,2))}}const wy=new Ey;class Ay extends X{constructor(e=null){super(wy,e),this.camera=Sy,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,Sy)}render(e){e.render(this,Sy)}}const Ry=new t;class Cy extends Yu{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:ce}){const i=new ue(t,r,s);super(i.texture,$u()),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 Ay(new Yh),this.updateBeforeType=Vs.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(Ry),s=r.width*t,i=r.height*t;s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}this._quadMesh.material.fragmentNode=this._rttNode;const t=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){const e=new Yu(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const My=(e,...t)=>Fi(new Cy(Fi(e),...t)),Py=ki((([e,t,r],s)=>{let i;s.renderer.coordinateSystem===d?(e=Yi(e.x,e.y.oneMinus()).mul(2).sub(1),i=nn(en(e,t),1)):i=nn(en(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=nn(r.mul(i));return n.xyz.div(n.w)})),By=ki((([e,t])=>{const r=t.mul(nn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return Yi(s.x,s.y.oneMinus())})),Ly=ki((([e,t,r])=>{const s=ju(Ju(t)),i=Qi(e.mul(s)).toVar(),n=Ju(t,i).toVar(),a=Ju(t,i.sub(Qi(2,0))).toVar(),o=Ju(t,i.sub(Qi(1,0))).toVar(),u=Ju(t,i.add(Qi(1,0))).toVar(),l=Ju(t,i.add(Qi(2,0))).toVar(),d=Ju(t,i.add(Qi(0,2))).toVar(),c=Ju(t,i.add(Qi(0,1))).toVar(),h=Ju(t,i.sub(Qi(0,1))).toVar(),p=Ju(t,i.sub(Qi(0,2))).toVar(),g=io(ua(ji(2).mul(o).sub(a),n)).toVar(),m=io(ua(ji(2).mul(u).sub(l),n)).toVar(),f=io(ua(ji(2).mul(c).sub(d),n)).toVar(),y=io(ua(ji(2).mul(h).sub(p),n)).toVar(),b=Py(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(Py(e.sub(Yi(ji(1).div(s.x),0)),o,r)),b.negate().add(Py(e.add(Yi(ji(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(Py(e.add(Yi(0,ji(1).div(s.y))),c,r)),b.negate().add(Py(e.sub(Yi(0,ji(1).div(s.y))),h,r)));return Ya(wo(x,T))}));class Fy extends L{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Iy extends ge{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class Dy extends js{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Vy=Ui(Dy),Uy=new w,Oy=new a;class ky extends js{static get type(){return"SceneNode"}constructor(e=ky.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,r=null!==this.scene?this.scene:e.scene;let s;return t===ky.BACKGROUND_BLURRINESS?s=_d("backgroundBlurriness","float",r):t===ky.BACKGROUND_INTENSITY?s=_d("backgroundIntensity","float",r):t===ky.BACKGROUND_ROTATION?s=Zn("mat4").label("backgroundRotation").setGroup(Kn).onRenderUpdate((()=>{const e=r.background;return null!==e&&e.isTexture&&e.mapping!==Fe?(Uy.copy(r.backgroundRotation),Uy.x*=-1,Uy.y*=-1,Uy.z*=-1,Oy.makeRotationFromEuler(Uy)):Oy.identity(),Oy})):console.error("THREE.SceneNode: Unknown scope:",t),s}}ky.BACKGROUND_BLURRINESS="backgroundBlurriness",ky.BACKGROUND_INTENSITY="backgroundIntensity",ky.BACKGROUND_ROTATION="backgroundRotation";const Gy=Ui(ky,ky.BACKGROUND_BLURRINESS),zy=Ui(ky,ky.BACKGROUND_INTENSITY),Hy=Ui(ky,ky.BACKGROUND_ROTATION);class $y extends Yu{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.isStorageTextureNode=!0,this.access=Os.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}generate(e,t){let r;return r=null!==this.storeNode?this.generateStore(e):super.generate(e,t),r}toReadWrite(){return this.setAccess(Os.READ_WRITE)}toReadOnly(){return this.setAccess(Os.READ_ONLY)}toWriteOnly(){return this.setAccess(Os.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,"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(e,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e}}const Wy=Vi($y).setParameterLength(1,3),jy=ki((({texture:e,uv:t})=>{const r=1e-4,s=en().toVar();return Hi(t.x.lessThan(r),(()=>{s.assign(en(1,0,0))})).ElseIf(t.y.lessThan(r),(()=>{s.assign(en(0,1,0))})).ElseIf(t.z.lessThan(r),(()=>{s.assign(en(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{s.assign(en(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{s.assign(en(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{s.assign(en(0,0,-1))})).Else((()=>{const r=.01,i=e.sample(t.add(en(-.01,0,0))).r.sub(e.sample(t.add(en(r,0,0))).r),n=e.sample(t.add(en(0,-.01,0))).r.sub(e.sample(t.add(en(0,r,0))).r),a=e.sample(t.add(en(0,0,-.01))).r.sub(e.sample(t.add(en(0,0,r))).r);s.assign(en(i,n,a))})),s.normalize()}));class qy extends Yu{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return en(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!e.isFlipY()||!0!==r.isRenderTargetTexture&&!0!==r.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return jy({texture:this,uv:e})}}const Xy=Vi(qy).setParameterLength(1,3);class Ky extends Td{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 Yy=new WeakMap;class Qy extends Ks{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=Vs.OBJECT,this.updateAfterType=Vs.OBJECT,this.previousModelWorldMatrix=Zn(new a),this.previousProjectionMatrix=Zn(new a).setGroup(Kn),this.previousCameraViewMatrix=Zn(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=Jy(r);this.previousModelWorldMatrix.value.copy(s);const i=Zy(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}){Jy(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?ll:Zn(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(Bl).mul(Vl),s=this.previousProjectionMatrix.mul(t).mul(Ul),i=r.xy.div(r.w),n=s.xy.div(s.w);return ua(i,n)}}function Zy(e){let t=Yy.get(e);return void 0===t&&(t={},Yy.set(e,t)),t}function Jy(e,t=0){const r=Zy(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const eb=Ui(Qy),tb=ki((([e])=>nb(e.rgb))),rb=ki((([e,t=ji(1)])=>t.mix(nb(e.rgb),e.rgb))),sb=ki((([e,t=ji(1)])=>{const r=oa(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 Fo(e.rgb,s,i)})),ib=ki((([e,t=ji(1)])=>{const r=en(.57735,.57735,.57735),s=t.cos();return en(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(Eo(r,e.rgb).mul(s.oneMinus())))))})),nb=(e,t=en(c.getLuminanceCoefficients(new r)))=>Eo(e,t),ab=ki((([e,t=en(1),s=en(0),i=en(1),n=ji(1),a=en(c.getLuminanceCoefficients(new r,le))])=>{const o=e.rgb.dot(en(a)),u=To(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return Hi(u.r.greaterThan(0),(()=>{u.r.assign(l.r)})),Hi(u.g.greaterThan(0),(()=>{u.g.assign(l.g)})),Hi(u.b.greaterThan(0),(()=>{u.b.assign(l.b)})),u.assign(o.add(u.sub(o).mul(n))),nn(u.rgb,e.a)}));class ob extends Ks{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const ub=Vi(ob).setParameterLength(2),lb=new t;class db extends Yu{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class cb extends db{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class hb extends Ks{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 U;i.isRenderTargetTexture=!0,i.name="depth";const n=new ue(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Zn(0),this._cameraFar=Zn(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=Vs.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}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=Fi(new cb(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=Fi(new cb(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=Ph(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=Ch(i,r,s)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===hb.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),lb.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(lb)),this._pixelRatio=i,this.setSize(lb.width,lb.height);const a=t.getRenderTarget(),o=t.getMRT(),u=s.layers.mask;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);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(r,s),t.setRenderTarget(a),t.setMRT(o),s.layers.mask=u}setSize(e,t){this._width=e,this._height=t;const r=this._width*this._pixelRatio*this._resolution,s=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(r,s)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}hb.COLOR="color",hb.DEPTH="depth";class pb extends hb{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(hb.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap}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 Yh;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=S;const t=Xl.negate(),r=ll.mul(Bl),s=ji(1),i=r.mul(nn(Vl,1)),n=r.mul(nn(Vl.add(t),1)),a=Ya(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=nn(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 gb=ki((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),mb=ki((([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"}]}),fb=ki((([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"}]}),yb=ki((([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)})),bb=ki((([e,t])=>{const r=dn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=dn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=yb(e),(e=s.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),xb=dn(en(1.6605,-.1246,-.0182),en(-.5876,1.1329,-.1006),en(-.0728,-.0083,1.1187)),Tb=dn(en(.6274,.0691,.0164),en(.3293,.9195,.088),en(.0433,.0113,.8956)),_b=ki((([e])=>{const t=en(e).toVar(),r=en(t.mul(t)).toVar(),s=en(r.mul(r)).toVar();return ji(15.5).mul(s.mul(r)).sub(la(40.14,s.mul(t))).add(la(31.96,s).sub(la(6.868,r.mul(t))).add(la(.4298,r).add(la(.1191,t).sub(.00232))))})),vb=ki((([e,t])=>{const r=en(e).toVar(),s=dn(en(.856627153315983,.137318972929847,.11189821299995),en(.0951212405381588,.761241990602591,.0767994186031903),en(.0482516061458583,.101439036467562,.811302368396859)),i=dn(en(1.1271005818144368,-.1413297634984383,-.14132976349843826),en(-.11060664309660323,1.157823702216272,-.11060664309660294),en(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ji(-12.47393),a=ji(4.026069);return r.mulAssign(t),r.assign(Tb.mul(r)),r.assign(s.mul(r)),r.assign(To(r,1e-10)),r.assign(Wa(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Io(r,0,1)),r.assign(_b(r)),r.assign(i.mul(r)),r.assign(Ao(To(en(0),r),en(2.2))),r.assign(xb.mul(r)),r.assign(Io(r,0,1)),r})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Nb=ki((([e,t])=>{const r=ji(.76),s=ji(.15);e=e.mul(t);const i=xo(e.r,xo(e.g,e.b)),n=Xo(i.lessThan(.08),i.sub(la(6.25,i.mul(i))),.04);e.subAssign(n);const a=To(e.r,To(e.g,e.b));Hi(a.lessThan(r),(()=>e));const o=ua(1,r),u=ua(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=ua(1,da(1,s.mul(a.sub(u)).add(1)));return Fo(e,en(u),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Sb extends js{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 Eb=Vi(Sb).setParameterLength(1,3);class wb extends Sb{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}getNodeType(e){return this.getNodeFunction(e).type}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 Ab=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};class Rb extends js{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new o,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:ji()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ls(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?Fs(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const Cb=Vi(Rb).setParameterLength(1);class Mb extends Map{get(e,t=null,...r){if(this.has(e))return super.get(e);if(null!==t){const s=t(...r);return this.set(e,s),s}}}class Pb{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const Bb=new Mb;class Lb extends js{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new Mb,this._output=Cb(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const r=this._outputs;return void 0===r[e]?r[e]=Cb(t):r[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const r=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),r[e]=t,r[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),r[e]=t,r[e].events.addEventListener("refresh",this.onRefresh)):void 0===r[e]?(r[e]=Cb(t),r[e].events.addEventListener("refresh",this.onRefresh)):r[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const r=this.getObject()[e];if("function"==typeof r)return r(...t)}async callAsync(e,...t){const r=this.getObject()[e];if("function"==typeof r)return"AsyncFunction"===r.constructor.name?await r(...t):r(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new Pb(this),t=Bb.get("THREE"),r=Bb.get("TSL"),s=this.getMethod(),i=[e,this._local,Bb,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,r];this._object=s(...i);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:ji()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",r="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],r),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[bs(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const r in this.parameters)t.push(this.parameters[r].getCacheKey(e));return xs(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const Fb=Vi(Lb).setParameterLength(1,2);function Ib(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||Gl.z).negate()}const Db=ki((([e,t],r)=>{const s=Ib(r);return Uo(e,t,s)})),Vb=ki((([e],t)=>{const r=Ib(t);return e.mul(e,r,r).negate().exp().oneMinus()})),Ub=ki((([e,t])=>nn(t.toFloat().mix(In.rgb,e.toVec3()),In.a)));let Ob=null,kb=null;class Gb extends js{static get type(){return"RangeNode"}constructor(e=ji(),t=ji()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Ms(this.minNode.value)),r=e.getTypeLength(Ms(this.maxNode.value));return t>r?t:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.minNode.value,n=this.maxNode.value,a=e.getTypeLength(Ms(i)),o=e.getTypeLength(Ms(n));Ob=Ob||new s,kb=kb||new s,Ob.setScalar(0),kb.setScalar(0),1===a?Ob.setScalar(i):i.isColor?Ob.set(i.r,i.g,i.b,1):Ob.set(i.x,i.y,i.z||0,i.w||0),1===o?kb.setScalar(n):n.isColor?kb.set(n.r,n.g,n.b,1):kb.set(n.x,n.y,n.z||0,n.w||0);const l=4,d=l*t.count,c=new Float32Array(d);for(let e=0;eFi(new Hb(e,t)),Wb=$b("numWorkgroups","uvec3"),jb=$b("workgroupId","uvec3"),qb=$b("globalId","uvec3"),Xb=$b("localId","uvec3"),Kb=$b("subgroupSize","uint");const Yb=Vi(class extends js{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class Qb extends qs{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 Zb extends js{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e}label(e){return this.name=e,this}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return Fi(new Qb(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class Jb extends js{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)}getNodeType(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(!(1===r.length&&!0===r[0].isStackNode))return void 0===t.constNode&&(t.constNode=Du(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}Jb.ATOMIC_LOAD="atomicLoad",Jb.ATOMIC_STORE="atomicStore",Jb.ATOMIC_ADD="atomicAdd",Jb.ATOMIC_SUB="atomicSub",Jb.ATOMIC_MAX="atomicMax",Jb.ATOMIC_MIN="atomicMin",Jb.ATOMIC_AND="atomicAnd",Jb.ATOMIC_OR="atomicOr",Jb.ATOMIC_XOR="atomicXor";const ex=Vi(Jb),tx=(e,t,r)=>ex(e,t,r).toStack();let rx;function sx(e){rx=rx||new WeakMap;let t=rx.get(e);return void 0===t&&rx.set(e,t={}),t}function ix(e){const t=sx(e);return t.shadowMatrix||(t.shadowMatrix=Zn("mat4").setGroup(Kn).onRenderUpdate((t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix))))}function nx(e,t=Ol){const r=ix(e).mul(t);return r.xyz.div(r.w)}function ax(e){const t=sx(e);return t.position||(t.position=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld))))}function ox(e){const t=sx(e);return t.targetPosition||(t.targetPosition=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld))))}function ux(e){const t=sx(e);return t.viewPosition||(t.viewPosition=Zn(new r).setGroup(Kn).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const lx=e=>cl.transformDirection(ax(e).sub(ox(e))),dx=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},cx=new WeakMap,hx=[];class px extends js{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=mn("vec3","totalDiffuse"),this.totalSpecularNode=mn("vec3","totalSpecular"),this.outgoingLightNode=mn("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(Fi(e));else{let s=null;if(null!==r&&(s=dx(e.id,r)),null===s){const r=i.getLightNodeClass(e.constructor);if(null===r){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let s=null;cx.has(e)?s=cx.get(e):(s=Fi(new r(e)),cx.set(e,s)),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=en(null!==l?l.mix(g,u):u),s.material.transparent=!0),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 gx extends js{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Vs.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){mx.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ol)}}const mx=mn("vec3","shadowPositionWorld");function fx(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 yx(e,t){return t=fx(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function bx(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 xx(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function Tx(e,t){return t=xx(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function _x(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function vx(e,t,r){return r=Tx(t,r=yx(e,r))}function Nx(e,t,r){bx(e,r),_x(t,r)}var Sx=Object.freeze({__proto__:null,resetRendererAndSceneState:vx,resetRendererState:yx,resetSceneState:Tx,restoreRendererAndSceneState:Nx,restoreRendererState:bx,restoreSceneState:_x,saveRendererAndSceneState:function(e,t,r={}){return r=xx(t,r=fx(e,r))},saveRendererState:fx,saveSceneState:xx});const Ex=new WeakMap,wx=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Zu(e,t.xy).label("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)})),Ax=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=_d("radius","float",r).setGroup(Kn),o=Yi(1).div(n),u=o.x.negate().mul(a),l=o.y.negate().mul(a),d=o.x.mul(a),c=o.y.mul(a),h=u.div(2),p=l.div(2),g=d.div(2),m=c.div(2);return oa(i(t.xy.add(Yi(u,l)),t.z),i(t.xy.add(Yi(0,l)),t.z),i(t.xy.add(Yi(d,l)),t.z),i(t.xy.add(Yi(h,p)),t.z),i(t.xy.add(Yi(0,p)),t.z),i(t.xy.add(Yi(g,p)),t.z),i(t.xy.add(Yi(u,0)),t.z),i(t.xy.add(Yi(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(Yi(g,0)),t.z),i(t.xy.add(Yi(d,0)),t.z),i(t.xy.add(Yi(h,m)),t.z),i(t.xy.add(Yi(0,m)),t.z),i(t.xy.add(Yi(g,m)),t.z),i(t.xy.add(Yi(u,c)),t.z),i(t.xy.add(Yi(0,c)),t.z),i(t.xy.add(Yi(d,c)),t.z)).mul(1/17)})),Rx=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=Yi(1).div(n),o=a.x,u=a.y,l=t.xy,d=Qa(l.mul(n).add(.5));return l.subAssign(d.mul(a)),oa(i(l,t.z),i(l.add(Yi(o,0)),t.z),i(l.add(Yi(0,u)),t.z),i(l.add(a),t.z),Fo(i(l.add(Yi(o.negate(),0)),t.z),i(l.add(Yi(o.mul(2),0)),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u)),t.z),i(l.add(Yi(o.mul(2),u)),t.z),d.x),Fo(i(l.add(Yi(0,u.negate())),t.z),i(l.add(Yi(0,u.mul(2))),t.z),d.y),Fo(i(l.add(Yi(o,u.negate())),t.z),i(l.add(Yi(o,u.mul(2))),t.z),d.y),Fo(Fo(i(l.add(Yi(o.negate(),u.negate())),t.z),i(l.add(Yi(o.mul(2),u.negate())),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u.mul(2))),t.z),i(l.add(Yi(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)})),Cx=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{const s=ji(1).toVar();let i=Zu(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=_o(t.z,i.x);return Hi(n.notEqual(ji(1)),(()=>{const e=t.z.sub(i.x),r=To(0,i.y.mul(i.y));let a=r.div(r.add(e.mul(e)));a=Io(ua(a,.3).div(.95-.3)),s.assign(Io(To(n,a)))})),s})),Mx=ki((([e,t,r])=>{let s=Ol.sub(e).length();return s=s.sub(t).div(r.sub(t)),s=s.saturate(),s})),Px=e=>{let t=Ex.get(e);if(void 0===t){const r=e.isPointLight?(e=>{const t=e.shadow.camera,r=_d("near","float",t).setGroup(Kn),s=_d("far","float",t).setGroup(Kn),i=xl(e);return Mx(i,r,s)})(e):null;t=new Yh,t.colorNode=nn(0,0,0,1),t.depthNode=r,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,Ex.set(e,t)}return t},Bx=new qm,Lx=[],Fx=(e,t,r,s)=>{Lx[0]=e,Lx[1]=t;let i=Bx.get(Lx);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===Ie)&&(s&&(Bs(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,Bx.set(Lx,i)),Lx[0]=null,Lx[1]=null,i},Ix=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanVertical"),a=ji(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));Zc({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(mh.xy,Yi(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=ja(a.sub(n.mul(n)));return Yi(n,l)})),Dx=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanHorizontal"),a=ji(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));Zc({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(mh.xy,Yi(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(oa(d.y.mul(d.y),d.x.mul(d.x)))})),n.divAssign(e),a.divAssign(e);const l=ja(a.sub(n.mul(n)));return Yi(n,l)})),Vx=[wx,Ax,Rx,Cx];let Ux;const Ox=new Ay;class kx extends gx{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture: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,ji(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=_d("bias","float",r).setGroup(Kn);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,s.coordinateSystem===d&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=_d("near","float",r.camera).setGroup(Kn),s=_d("far","float",r.camera).setGroup(Kn);n=Bh(e.negate(),t,s)}return a=en(a.x,a.y.oneMinus(),n.add(i)),a}getShadowFilterFn(e){return Vx[e]}setupRenderTarget(e,t){const r=new U(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=De;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}=e,{light:r,shadow:s}=this,i=t.shadowMap.type,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(s,e);if(s.camera.updateProjectionMatrix(),i===Ie&&!0!==s.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}));let t=Zu(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Zu(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const i=_d("blurSamples","float",s).setGroup(Kn),o=_d("radius","float",s).setGroup(Kn),u=_d("mapSize","vec2",s).setGroup(Kn);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Yh);l.fragmentNode=Ix({samples:i,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Yh),l.fragmentNode=Dx({samples:i,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=_d("intensity","float",s).setGroup(Kn),u=_d("normalBias","float",s).setGroup(Kn),l=ix(r).mul(mx.add(Jl.mul(u))),d=this.setupShadowCoord(e,l),c=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const h=i===Ie&&!0!==s.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:a.texture,depthTexture:h,shadowCoord:d,shadow:s,depthLayer:this.depthLayer});let g=Zu(a.texture,d);n.isArrayTexture&&(g=g.depth(this.depthLayer));const m=Fo(1,p.rgb.mix(g,1),o.mul(g.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return ki((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth),i.render(n,t.camera)}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");Ux=vx(i,n,Ux),n.overrideMaterial=Px(r),i.setRenderObjectFunction(Fx(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===Ie&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,Nx(i,n,Ux)}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),Ox.material=this.vsmMaterialVertical,Ox.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Ox.material=this.vsmMaterialHorizontal,Ox.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let 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 Gx=(e,t)=>Fi(new kx(e,t)),zx=new e,Hx=ki((([e,t])=>{const r=e.toVar(),s=io(r),i=da(1,To(s.x,To(s.y,s.z)));s.mulAssign(i),r.mulAssign(i.mul(t.mul(2).oneMinus()));const n=Yi(r.xy).toVar(),a=t.mul(1.5).oneMinus();return Hi(s.z.greaterThanEqual(a),(()=>{Hi(r.z.greaterThan(0),(()=>{n.x.assign(ua(4,r.x))}))})).ElseIf(s.x.greaterThanEqual(a),(()=>{const e=no(r.x);n.x.assign(r.z.mul(e).add(e.mul(2)))})).ElseIf(s.y.greaterThanEqual(a),(()=>{const e=no(r.y);n.x.assign(r.x.add(e.mul(2)).add(2)),n.y.assign(r.z.mul(e).sub(2))})),Yi(.125,.25).mul(n).add(Yi(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),$x=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s})=>Zu(e,Hx(t,s.y)).compare(r))),Wx=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s,shadow:i})=>{const n=_d("radius","float",i).setGroup(Kn),a=Yi(-1,1).mul(n).mul(s.y);return Zu(e,Hx(t.add(a.xyy),s.y)).compare(r).add(Zu(e,Hx(t.add(a.yyy),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.xyx),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.yyx),s.y)).compare(r)).add(Zu(e,Hx(t,s.y)).compare(r)).add(Zu(e,Hx(t.add(a.xxy),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.yxy),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.xxx),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.yxx),s.y)).compare(r)).mul(1/9)})),jx=ki((({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s})=>{const i=r.xyz.toVar(),n=i.length(),a=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.near)),o=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.far)),u=_d("bias","float",s).setGroup(Kn),l=Zn(s.mapSize).setGroup(Kn),d=ji(1).toVar();return Hi(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),(()=>{const r=n.sub(a).div(o.sub(a)).toVar();r.addAssign(u);const c=i.normalize(),h=Yi(1).div(l.mul(Yi(4,2)));d.assign(e({depthTexture:t,bd3D:c,dp:r,texelSize:h,shadow:s}))})),d})),qx=new s,Xx=new t,Kx=new t;class Yx extends kx{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Ue?$x:Wx}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n}){return jx({filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.getFrameExtents();Kx.copy(t.mapSize),Kx.multiply(a),r.setSize(Kx.width,Kx.height),Xx.copy(t.mapSize);const o=i.autoClear,u=i.getClearColor(zx),l=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const d=t.getViewportCount();for(let e=0;eFi(new Yx(e,t));class Zx extends nh{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Zn(this.color).setGroup(Kn),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vs.FRAME}getHash(){return this.light.uuid}getLightVector(e){return ux(this.light).sub(e.context.positionView||Gl)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return Gx(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?Fi(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}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 Jx=ki((({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)})),eT=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=Jx({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class tT extends Zx{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(2).setGroup(Kn)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return Qx(this.light)}setupDirect(e){return eT({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const rT=ki((([e=t()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()})),sT=ki((([e=$u()],{renderer:t,material:r})=>{const s=Lo(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.samples>1){const e=ji(s.fwidth()).toVar();i=Uo(e.oneMinus(),e.add(1),s).oneMinus()}else i=Xo(s.greaterThan(1),0,1);return i})),iT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Ki(e).toVar();return Xo(n,i,s)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),nT=ki((([e,t])=>{const r=Ki(t).toVar(),s=ji(e).toVar();return Xo(r,s.negate(),s)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),aT=ki((([e])=>{const t=ji(e).toVar();return qi(Xa(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),oT=ki((([e,t])=>{const r=ji(e).toVar();return t.assign(aT(r)),r.sub(ji(t))})),uT=Yf([ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=ji(s).toVar(),l=ji(r).toVar(),d=ji(t).toVar(),c=ji(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]}),ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=en(s).toVar(),l=en(r).toVar(),d=en(t).toVar(),c=en(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]})]),lT=Yf([ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=ji(o).toVar(),m=ji(a).toVar(),f=ji(n).toVar(),y=ji(i).toVar(),b=ji(s).toVar(),x=ji(r).toVar(),T=ji(t).toVar(),_=ji(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]}),ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=en(o).toVar(),m=en(a).toVar(),f=en(n).toVar(),y=en(i).toVar(),b=en(s).toVar(),x=en(r).toVar(),T=en(t).toVar(),_=en(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]})]),dT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Xi(e).toVar(),a=Xi(n.bitAnd(Xi(7))).toVar(),o=ji(iT(a.lessThan(Xi(4)),i,s)).toVar(),u=ji(la(2,iT(a.lessThan(Xi(4)),s,i))).toVar();return nT(o,Ki(a.bitAnd(Xi(1)))).add(nT(u,Ki(a.bitAnd(Xi(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),cT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=Xi(e).toVar(),u=Xi(o.bitAnd(Xi(15))).toVar(),l=ji(iT(u.lessThan(Xi(8)),a,n)).toVar(),d=ji(iT(u.lessThan(Xi(4)),n,iT(u.equal(Xi(12)).or(u.equal(Xi(14))),a,i))).toVar();return nT(l,Ki(u.bitAnd(Xi(1)))).add(nT(d,Ki(u.bitAnd(Xi(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"}]}),hT=Yf([dT,cT]),pT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=rn(e).toVar();return en(hT(n.x,i,s),hT(n.y,i,s),hT(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"}]}),gT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=rn(e).toVar();return en(hT(o.x,a,n,i),hT(o.y,a,n,i),hT(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"}]}),mT=Yf([pT,gT]),fT=ki((([e])=>{const t=ji(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),yT=ki((([e])=>{const t=ji(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),bT=Yf([fT,ki((([e])=>{const t=en(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),xT=Yf([yT,ki((([e])=>{const t=en(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),TT=ki((([e,t])=>{const r=qi(t).toVar(),s=Xi(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(qi(32).sub(r)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),_T=ki((([e,t,r])=>{e.subAssign(r),e.bitXorAssign(TT(r,qi(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(TT(e,qi(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(TT(t,qi(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(TT(r,qi(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(TT(e,qi(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(TT(t,qi(4))),t.addAssign(e)})),vT=ki((([e,t,r])=>{const s=Xi(r).toVar(),i=Xi(t).toVar(),n=Xi(e).toVar();return s.bitXorAssign(i),s.subAssign(TT(i,qi(14))),n.bitXorAssign(s),n.subAssign(TT(s,qi(11))),i.bitXorAssign(n),i.subAssign(TT(n,qi(25))),s.bitXorAssign(i),s.subAssign(TT(i,qi(16))),n.bitXorAssign(s),n.subAssign(TT(s,qi(4))),i.bitXorAssign(n),i.subAssign(TT(n,qi(14))),s.bitXorAssign(i),s.subAssign(TT(i,qi(24))),s})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),NT=ki((([e])=>{const t=Xi(e).toVar();return ji(t).div(ji(Xi(qi(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),ST=ki((([e])=>{const t=ji(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"}]}),ET=Yf([ki((([e])=>{const t=qi(e).toVar(),r=Xi(Xi(1)).toVar(),s=Xi(Xi(qi(3735928559)).add(r.shiftLeft(Xi(2))).add(Xi(13))).toVar();return vT(s.add(Xi(t)),s,s)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(Xi(2)).toVar(),n=Xi().toVar(),a=Xi().toVar(),o=Xi().toVar();return n.assign(a.assign(o.assign(Xi(qi(3735928559)).add(i.shiftLeft(Xi(2))).add(Xi(13))))),n.addAssign(Xi(s)),a.addAssign(Xi(r)),vT(n,a,o)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(Xi(3)).toVar(),o=Xi().toVar(),u=Xi().toVar(),l=Xi().toVar();return o.assign(u.assign(l.assign(Xi(qi(3735928559)).add(a.shiftLeft(Xi(2))).add(Xi(13))))),o.addAssign(Xi(n)),u.addAssign(Xi(i)),l.addAssign(Xi(s)),vT(o,u,l)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),ki((([e,t,r,s])=>{const i=qi(s).toVar(),n=qi(r).toVar(),a=qi(t).toVar(),o=qi(e).toVar(),u=Xi(Xi(4)).toVar(),l=Xi().toVar(),d=Xi().toVar(),c=Xi().toVar();return l.assign(d.assign(c.assign(Xi(qi(3735928559)).add(u.shiftLeft(Xi(2))).add(Xi(13))))),l.addAssign(Xi(o)),d.addAssign(Xi(a)),c.addAssign(Xi(n)),_T(l,d,c),l.addAssign(Xi(i)),vT(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"}]}),ki((([e,t,r,s,i])=>{const n=qi(i).toVar(),a=qi(s).toVar(),o=qi(r).toVar(),u=qi(t).toVar(),l=qi(e).toVar(),d=Xi(Xi(5)).toVar(),c=Xi().toVar(),h=Xi().toVar(),p=Xi().toVar();return c.assign(h.assign(p.assign(Xi(qi(3735928559)).add(d.shiftLeft(Xi(2))).add(Xi(13))))),c.addAssign(Xi(l)),h.addAssign(Xi(u)),p.addAssign(Xi(o)),_T(c,h,p),c.addAssign(Xi(a)),h.addAssign(Xi(n)),vT(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"}]})]),wT=Yf([ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(ET(s,r)).toVar(),n=rn().toVar();return n.x.assign(i.bitAnd(qi(255))),n.y.assign(i.shiftRight(qi(8)).bitAnd(qi(255))),n.z.assign(i.shiftRight(qi(16)).bitAnd(qi(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(ET(n,i,s)).toVar(),o=rn().toVar();return o.x.assign(a.bitAnd(qi(255))),o.y.assign(a.shiftRight(qi(8)).bitAnd(qi(255))),o.z.assign(a.shiftRight(qi(16)).bitAnd(qi(255))),o})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),AT=Yf([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(oT(t.x,r)).toVar(),n=ji(oT(t.y,s)).toVar(),a=ji(ST(i)).toVar(),o=ji(ST(n)).toVar(),u=ji(uT(hT(ET(r,s),i,n),hT(ET(r.add(qi(1)),s),i.sub(1),n),hT(ET(r,s.add(qi(1))),i,n.sub(1)),hT(ET(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return bT(u)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(oT(t.x,r)).toVar(),a=ji(oT(t.y,s)).toVar(),o=ji(oT(t.z,i)).toVar(),u=ji(ST(n)).toVar(),l=ji(ST(a)).toVar(),d=ji(ST(o)).toVar(),c=ji(lT(hT(ET(r,s,i),n,a,o),hT(ET(r.add(qi(1)),s,i),n.sub(1),a,o),hT(ET(r,s.add(qi(1)),i),n,a.sub(1),o),hT(ET(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),hT(ET(r,s,i.add(qi(1))),n,a,o.sub(1)),hT(ET(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),hT(ET(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),hT(ET(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return xT(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),RT=Yf([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(oT(t.x,r)).toVar(),n=ji(oT(t.y,s)).toVar(),a=ji(ST(i)).toVar(),o=ji(ST(n)).toVar(),u=en(uT(mT(wT(r,s),i,n),mT(wT(r.add(qi(1)),s),i.sub(1),n),mT(wT(r,s.add(qi(1))),i,n.sub(1)),mT(wT(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return bT(u)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(oT(t.x,r)).toVar(),a=ji(oT(t.y,s)).toVar(),o=ji(oT(t.z,i)).toVar(),u=ji(ST(n)).toVar(),l=ji(ST(a)).toVar(),d=ji(ST(o)).toVar(),c=en(lT(mT(wT(r,s,i),n,a,o),mT(wT(r.add(qi(1)),s,i),n.sub(1),a,o),mT(wT(r,s.add(qi(1)),i),n,a.sub(1),o),mT(wT(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),mT(wT(r,s,i.add(qi(1))),n,a,o.sub(1)),mT(wT(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),mT(wT(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),mT(wT(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return xT(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),CT=Yf([ki((([e])=>{const t=ji(e).toVar(),r=qi(aT(t)).toVar();return NT(ET(r))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar();return NT(ET(r,s))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar();return NT(ET(r,s,i))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar(),n=qi(aT(t.w)).toVar();return NT(ET(r,s,i,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),MT=Yf([ki((([e])=>{const t=ji(e).toVar(),r=qi(aT(t)).toVar();return en(NT(ET(r,qi(0))),NT(ET(r,qi(1))),NT(ET(r,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar();return en(NT(ET(r,s,qi(0))),NT(ET(r,s,qi(1))),NT(ET(r,s,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar();return en(NT(ET(r,s,i,qi(0))),NT(ET(r,s,i,qi(1))),NT(ET(r,s,i,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar(),n=qi(aT(t.w)).toVar();return en(NT(ET(r,s,i,n,qi(0))),NT(ET(r,s,i,n,qi(1))),NT(ET(r,s,i,n,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),PT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=ji(0).toVar(),l=ji(1).toVar();return Zc(a,(()=>{u.addAssign(l.mul(AT(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"}]}),BT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en(0).toVar(),l=ji(1).toVar();return Zc(a,(()=>{u.addAssign(l.mul(RT(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"}]}),LT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar();return Yi(PT(o,a,n,i),PT(o.add(en(qi(19),qi(193),qi(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"}]}),FT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en(BT(o,a,n,i)).toVar(),l=ji(PT(o.add(en(qi(19),qi(193),qi(17))),a,n,i)).toVar();return nn(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"}]}),IT=Yf([ki((([e,t,r,s,i,n,a])=>{const o=qi(a).toVar(),u=ji(n).toVar(),l=qi(i).toVar(),d=qi(s).toVar(),c=qi(r).toVar(),h=qi(t).toVar(),p=Yi(e).toVar(),g=en(MT(Yi(h.add(d),c.add(l)))).toVar(),m=Yi(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Yi(Yi(ji(h),ji(c)).add(m)).toVar(),y=Yi(f.sub(p)).toVar();return Hi(o.equal(qi(2)),(()=>io(y.x).add(io(y.y)))),Hi(o.equal(qi(3)),(()=>To(io(y.x),io(y.y)))),Eo(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"}]}),ki((([e,t,r,s,i,n,a,o,u])=>{const l=qi(u).toVar(),d=ji(o).toVar(),c=qi(a).toVar(),h=qi(n).toVar(),p=qi(i).toVar(),g=qi(s).toVar(),m=qi(r).toVar(),f=qi(t).toVar(),y=en(e).toVar(),b=en(MT(en(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=en(en(ji(f),ji(m),ji(g)).add(b)).toVar(),T=en(x.sub(y)).toVar();return Hi(l.equal(qi(2)),(()=>io(T.x).add(io(T.y)).add(io(T.z)))),Hi(l.equal(qi(3)),(()=>To(io(T.x),io(T.y),io(T.z)))),Eo(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"}]})]),DT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(oT(n.x,a),oT(n.y,o)).toVar(),l=ji(1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(IT(u,e,t,a,o,i,s)).toVar();l.assign(xo(l,r))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),VT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(oT(n.x,a),oT(n.y,o)).toVar(),l=Yi(1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(IT(u,e,t,a,o,i,s)).toVar();Hi(r.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(r)})).ElseIf(r.lessThan(l.y),(()=>{l.y.assign(r)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),UT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(oT(n.x,a),oT(n.y,o)).toVar(),l=en(1e6,1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(IT(u,e,t,a,o,i,s)).toVar();Hi(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)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),OT=Yf([DT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(oT(n.x,a),oT(n.y,o),oT(n.z,u)).toVar(),d=ji(1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{Zc({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(IT(l,e,t,r,a,o,u,i,s)).toVar();d.assign(xo(d,n))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),kT=Yf([VT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(oT(n.x,a),oT(n.y,o),oT(n.z,u)).toVar(),d=Yi(1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{Zc({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(IT(l,e,t,r,a,o,u,i,s)).toVar();Hi(n.lessThan(d.x),(()=>{d.y.assign(d.x),d.x.assign(n)})).ElseIf(n.lessThan(d.y),(()=>{d.y.assign(n)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),GT=Yf([UT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(oT(n.x,a),oT(n.y,o),oT(n.z,u)).toVar(),d=en(1e6,1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{Zc({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(IT(l,e,t,r,a,o,u,i,s)).toVar();Hi(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)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),zT=ki((([e])=>{const t=e.y,r=e.z,s=en().toVar();return Hi(t.lessThan(1e-4),(()=>{s.assign(en(r,r,r))})).Else((()=>{let i=e.x;i=i.sub(Xa(i)).mul(6).toVar();const n=qi(go(i)),a=i.sub(ji(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());Hi(n.equal(qi(0)),(()=>{s.assign(en(r,l,o))})).ElseIf(n.equal(qi(1)),(()=>{s.assign(en(u,r,o))})).ElseIf(n.equal(qi(2)),(()=>{s.assign(en(o,r,l))})).ElseIf(n.equal(qi(3)),(()=>{s.assign(en(o,u,r))})).ElseIf(n.equal(qi(4)),(()=>{s.assign(en(l,o,r))})).Else((()=>{s.assign(en(r,o,u))}))})),s})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),HT=ki((([e])=>{const t=en(e).toVar(),r=ji(t.x).toVar(),s=ji(t.y).toVar(),i=ji(t.z).toVar(),n=ji(xo(r,xo(s,i))).toVar(),a=ji(To(r,To(s,i))).toVar(),o=ji(a.sub(n)).toVar(),u=ji().toVar(),l=ji().toVar(),d=ji().toVar();return d.assign(a),Hi(a.greaterThan(0),(()=>{l.assign(o.div(a))})).Else((()=>{l.assign(0)})),Hi(l.lessThanEqual(0),(()=>{u.assign(0)})).Else((()=>{Hi(r.greaterThanEqual(a),(()=>{u.assign(s.sub(i).div(o))})).ElseIf(s.greaterThanEqual(a),(()=>{u.assign(oa(2,i.sub(r).div(o)))})).Else((()=>{u.assign(oa(4,r.sub(s).div(o)))})),u.mulAssign(1/6),Hi(u.lessThan(0),(()=>{u.addAssign(1)}))})),en(u,l,d)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),$T=ki((([e])=>{const t=en(e).toVar(),r=sn(ma(t,en(.04045))).toVar(),s=en(t.div(12.92)).toVar(),i=en(Ao(To(t.add(en(.055)),en(0)).div(1.055),en(2.4))).toVar();return Fo(s,i,r)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),WT=(e,t)=>{e=ji(e),t=ji(t);const r=Yi(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Uo(e.sub(r),e.add(r),t)},jT=(e,t,r,s)=>Fo(e,t,r[s].clamp()),qT=(e,t,r,s,i)=>Fo(e,t,WT(r,s[i])),XT=ki((([e,t,r])=>{const s=Ya(e).toVar(),i=ua(ji(.5).mul(t.sub(r)),Ol).div(s).toVar(),n=ua(ji(-.5).mul(t.sub(r)),Ol).div(s).toVar(),a=en().toVar();a.x=s.x.greaterThan(ji(0)).select(i.x,n.x),a.y=s.y.greaterThan(ji(0)).select(i.y,n.y),a.z=s.z.greaterThan(ji(0)).select(i.z,n.z);const o=xo(a.x,a.y,a.z).toVar();return Ol.add(s.mul(o)).toVar().sub(r)})),KT=ki((([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(la(r,r).sub(la(s,s)))),n}));var YT=Object.freeze({__proto__:null,BRDF_GGX:Op,BRDF_Lambert:Sp,BasicPointShadowFilter:$x,BasicShadowFilter:wx,Break:Jc,Const:tu,Continue:()=>Du("continue").toStack(),DFGApprox:kp,D_GGX:Dp,Discard:Vu,EPSILON:Fa,F_Schlick:Np,Fn:ki,INFINITY:Ia,If:Hi,Loop:Zc,NodeAccess:Os,NodeShaderStage:Ds,NodeType:Us,NodeUpdateType:Vs,PCFShadowFilter:Ax,PCFSoftShadowFilter:Rx,PI:Da,PI2:Va,PointShadowFilter:Wx,Return:()=>Du("return").toStack(),Schlick_to_F0:zp,ScriptableNodeResources:Bb,ShaderNode:Li,Stack:$i,Switch:(...e)=>ni.Switch(...e),TBNViewMatrix:Fd,VSMShadowFilter:Cx,V_GGX_SmithCorrelated:Fp,Var:eu,abs:io,acesFilmicToneMapping:bb,acos:ro,add:oa,addMethodChaining:oi,addNodeElement:function(e){console.warn("THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:vb,all:Ua,alphaT:Rn,and:ba,anisotropy:Cn,anisotropyB:Pn,anisotropyT:Mn,any:Oa,append:e=>(console.warn("THREE.TSL: append() has been renamed to Stack()."),$i(e)),array:ea,arrayBuffer:e=>Fi(new si(e,"ArrayBuffer")),asin:to,assign:ra,atan:so,atan2:$o,atomicAdd:(e,t)=>tx(Jb.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>tx(Jb.ATOMIC_AND,e,t),atomicFunc:tx,atomicLoad:e=>tx(Jb.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>tx(Jb.ATOMIC_MAX,e,t),atomicMin:(e,t)=>tx(Jb.ATOMIC_MIN,e,t),atomicOr:(e,t)=>tx(Jb.ATOMIC_OR,e,t),atomicStore:(e,t)=>tx(Jb.ATOMIC_STORE,e,t),atomicSub:(e,t)=>tx(Jb.ATOMIC_SUB,e,t),atomicXor:(e,t)=>tx(Jb.ATOMIC_XOR,e,t),attenuationColor:Hn,attenuationDistance:zn,attribute:Hu,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new Iy(e,r,s);return qc(i,t,e)},backgroundBlurriness:Gy,backgroundIntensity:zy,backgroundRotation:Hy,batch:Hc,bentNormalView:Dd,billboarding:ry,bitAnd:va,bitNot:Na,bitOr:Sa,bitXor:Ea,bitangentGeometry:Md,bitangentLocal:Pd,bitangentView:Bd,bitangentWorld:Ld,bitcast:yo,blendBurn:Hh,blendColor:qh,blendDodge:$h,blendOverlay:jh,blendScreen:Wh,blur:Gg,bool:Ki,buffer:tl,bufferAttribute:vu,bumpMap:Hd,burn:(...e)=>(console.warn('THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.'),Hh(e)),bvec2:Ji,bvec3:sn,bvec4:un,bypass:Pu,cache:Cu,call:ia,cameraFar:ul,cameraIndex:al,cameraNear:ol,cameraNormalMatrix:pl,cameraPosition:gl,cameraProjectionMatrix:ll,cameraProjectionMatrixInverse:dl,cameraViewMatrix:cl,cameraWorldMatrix:hl,cbrt:Bo,cdl:ab,ceil:Ka,checker:rT,cineonToneMapping:fb,clamp:Io,clearcoat:_n,clearcoatNormalView:ed,clearcoatRoughness:vn,code:Eb,color:Wi,colorSpaceToWorking:pu,colorToDirection:e=>Fi(e).mul(2).sub(1),compute:Au,computeSkinning:(e,t=null)=>{const r=new Kc(e);return r.positionNode=qc(new L(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(Lc).toVar(),r.skinIndexNode=qc(new L(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(Lc).toVar(),r.skinWeightNode=qc(new L(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(Lc).toVar(),r.bindMatrixNode=Zn(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Zn(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=tl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,Fi(r)},context:Yo,convert:pn,convertColorSpace:(e,t,r)=>Fi(new cu(Fi(e),t,r)),convertToTexture:(e,...t)=>e.isTextureNode?e:e.isPassNode?e.getTextureNode():My(e,...t),cos:Ja,cross:wo,cubeTexture:bd,cubeTextureBase:yd,cubeToUV:Hx,dFdx:lo,dFdy:co,dashSize:Dn,debug:Gu,decrement:Pa,decrementBefore:Ca,defaultBuildStages:Gs,defaultShaderStages:ks,defined:Pi,degrees:Ga,deltaTime:Zf,densityFog:function(e,t){return console.warn('THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),Ub(e,Vb(t))},densityFogFactor:Vb,depth:Fh,depthPass:(e,t,r)=>Fi(new hb(hb.DEPTH,e,t,r)),difference:So,diffuseColor:yn,directPointLight:eT,directionToColor:ap,directionToFaceDirection:jl,dispersion:$n,distance:No,div:da,dodge:(...e)=>(console.warn('THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.'),$h(e)),dot:Eo,drawIndex:Vc,dynamicBufferAttribute:Nu,element:hn,emissive:bn,equal:ha,equals:bo,equirectUV:dp,exp:za,exp2:Ha,expression:Du,faceDirection:Wl,faceForward:Oo,faceforward:Wo,float:ji,floor:Xa,fog:Ub,fract:Qa,frameGroup:Xn,frameId:Jf,frontFacing:$l,fwidth:mo,gain:(e,t)=>e.lessThan(.5)?$f(e.mul(2),t).div(2):ua(1,$f(la(ua(1,e),2),t).div(2)),gapSize:Vn,getConstNodeType:Bi,getCurrentStack:zi,getDirection:Vg,getDistanceAttenuation:Jx,getGeometryRoughness:Bp,getNormalFromDepth:Ly,getParallaxCorrectNormal:XT,getRoughness:Lp,getScreenPosition:By,getShIrradianceAt:KT,getShadowMaterial:Px,getShadowRenderObjectFunction:Fx,getTextureIndex:kf,getViewPosition:Py,globalId:qb,glsl:(e,t)=>Eb(e,t,"glsl"),glslFn:(e,t)=>Ab(e,t,"glsl"),grayscale:tb,greaterThan:ma,greaterThanEqual:ya,hash:Hf,highpModelNormalViewMatrix:Il,highpModelViewMatrix:Fl,hue:ib,increment:Ma,incrementBefore:Ra,instance:Oc,instanceIndex:Lc,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new Fy(e,r,s);return qc(i,t,e)},instancedBufferAttribute:Su,instancedDynamicBufferAttribute:Eu,instancedMesh:Gc,int:qi,inverseSqrt:qa,inversesqrt:jo,invocationLocalIndex:Dc,invocationSubgroupIndex:Ic,ior:On,iridescence:En,iridescenceIOR:wn,iridescenceThickness:An,ivec2:Qi,ivec3:tn,ivec4:an,js:(e,t)=>Eb(e,t,"js"),label:Qo,length:ao,lengthSq:Lo,lessThan:ga,lessThanEqual:fa,lightPosition:ax,lightProjectionUV:nx,lightShadowMatrix:ix,lightTargetDirection:lx,lightTargetPosition:ox,lightViewPosition:ux,lightingContext:uh,lights:(e=[])=>Fi(new px).setLights(e),linearDepth:Ih,linearToneMapping:gb,localId:Xb,log:$a,log2:Wa,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul($a(r.div(t)));return ji(Math.E).pow(s).mul(t).negate()},luminance:nb,mat2:ln,mat3:dn,mat4:cn,matcapUV:Cm,materialAO:Rc,materialAlphaTest:jd,materialAnisotropy:cc,materialAnisotropyVector:Cc,materialAttenuationColor:xc,materialAttenuationDistance:bc,materialClearcoat:nc,materialClearcoatNormal:oc,materialClearcoatRoughness:ac,materialColor:qd,materialDispersion:wc,materialEmissive:Kd,materialEnvIntensity:ld,materialEnvRotation:dd,materialIOR:yc,materialIridescence:hc,materialIridescenceIOR:pc,materialIridescenceThickness:gc,materialLightMap:Ac,materialLineDashOffset:Sc,materialLineDashSize:_c,materialLineGapSize:vc,materialLineScale:Tc,materialLineWidth:Nc,materialMetalness:sc,materialNormal:ic,materialOpacity:Yd,materialPointSize:Ec,materialReference:Sd,materialReflectivity:tc,materialRefractionRatio:ud,materialRotation:uc,materialRoughness:rc,materialSheen:lc,materialSheenRoughness:dc,materialShininess:Xd,materialSpecular:Qd,materialSpecularColor:Jd,materialSpecularIntensity:Zd,materialSpecularStrength:ec,materialThickness:fc,materialTransmission:mc,max:To,maxMipLevel:Xu,mediumpModelViewMatrix:Ll,metalness:Tn,min:xo,mix:Fo,mixElement:Go,mod:ca,modInt:Ba,modelDirection:Sl,modelNormalMatrix:Ml,modelPosition:wl,modelRadius:Cl,modelScale:Al,modelViewMatrix:Bl,modelViewPosition:Rl,modelViewProjection:Mc,modelWorldMatrix:El,modelWorldMatrixInverse:Pl,morphReference:ih,mrt:zf,mul:la,mx_aastep:WT,mx_cell_noise_float:(e=$u())=>CT(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>ji(e).sub(r).mul(t).add(r),mx_fractal_noise_float:(e=$u(),t=3,r=2,s=.5,i=1)=>PT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec2:(e=$u(),t=3,r=2,s=.5,i=1)=>LT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec3:(e=$u(),t=3,r=2,s=.5,i=1)=>BT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec4:(e=$u(),t=3,r=2,s=.5,i=1)=>FT(e,qi(t),r,s).mul(i),mx_hsvtorgb:zT,mx_noise_float:(e=$u(),t=1,r=0)=>AT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=$u(),t=1,r=0)=>RT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=$u(),t=1,r=0)=>{e=e.convert("vec2|vec3");return nn(RT(e),AT(e.add(Yi(19,73)))).mul(t).add(r)},mx_ramplr:(e,t,r=$u())=>jT(e,t,r,"x"),mx_ramptb:(e,t,r=$u())=>jT(e,t,r,"y"),mx_rgbtohsv:HT,mx_safepower:(e,t=1)=>(e=ji(e)).abs().pow(t).mul(e.sign()),mx_splitlr:(e,t,r,s=$u())=>qT(e,t,r,s,"x"),mx_splittb:(e,t,r,s=$u())=>qT(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:$T,mx_transform_uv:(e=1,t=0,r=$u())=>r.mul(e).add(t),mx_worley_noise_float:(e=$u(),t=1)=>OT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec2:(e=$u(),t=1)=>kT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec3:(e=$u(),t=1)=>GT(e.convert("vec2|vec3"),t,qi(1)),negate:oo,neutralToneMapping:Nb,nodeArray:Di,nodeImmutable:Ui,nodeObject:Fi,nodeObjects:Ii,nodeProxy:Vi,normalFlat:Kl,normalGeometry:ql,normalLocal:Xl,normalMap:Od,normalView:Zl,normalViewGeometry:Yl,normalWorld:Jl,normalWorldGeometry:Ql,normalize:Ya,not:Ta,notEqual:pa,numWorkgroups:Wb,objectDirection:yl,objectGroup:Yn,objectPosition:xl,objectRadius:vl,objectScale:Tl,objectViewPosition:_l,objectWorldMatrix:bl,oneMinus:uo,or:xa,orthographicDepthToViewZ:(e,t,r)=>t.sub(r).mul(e).sub(t),oscSawtooth:(e=Qf)=>e.fract(),oscSine:(e=Qf)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=Qf)=>e.fract().round(),oscTriangle:(e=Qf)=>e.add(.5).fract().mul(2).sub(1).abs(),output:In,outputStruct:Of,overlay:(...e)=>(console.warn('THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),jh(e)),overloadingFn:Yf,parabola:$f,parallaxDirection:Id,parallaxUV:(e,t)=>e.sub(Id.mul(t)),parameter:(e,t)=>Fi(new Lf(e,t)),pass:(e,t,r)=>Fi(new hb(hb.COLOR,e,t,r)),passTexture:(e,t)=>Fi(new db(e,t)),pcurve:(e,t,r)=>Ao(da(Ao(e,t),oa(Ao(e,t),Ao(ua(1,e),r))),1/t),perspectiveDepthToViewZ:Ph,pmremTexture:pm,pointShadow:Qx,pointUV:Vy,pointWidth:Un,positionGeometry:Dl,positionLocal:Vl,positionPrevious:Ul,positionView:Gl,positionViewDirection:zl,positionWorld:Ol,positionWorldDirection:kl,posterize:ub,pow:Ao,pow2:Ro,pow3:Co,pow4:Mo,premultiplyAlpha:Xh,property:mn,radians:ka,rand:ko,range:zb,rangeFog:function(e,t,r){return console.warn('THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),Ub(e,Db(t,r))},rangeFogFactor:Db,reciprocal:po,reference:_d,referenceBuffer:vd,reflect:vo,reflectVector:pd,reflectView:cd,reflector:e=>Fi(new vy(e)),refract:Vo,refractVector:gd,refractView:hd,reinhardToneMapping:mb,remap:Lu,remapClamp:Fu,renderGroup:Kn,renderOutput:Ou,rendererReference:yu,rotate:Lm,rotateUV:ey,roughness:xn,round:ho,rtt:My,sRGBTransferEOTF:uu,sRGBTransferOETF:lu,sampler:e=>(!0===e.isNode?e:Zu(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Zu(e)).convert("samplerComparison"),saturate:Do,saturation:rb,screen:(...e)=>(console.warn('THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.'),Wh(e)),screenCoordinate:mh,screenSize:gh,screenUV:ph,scriptable:Fb,scriptableValue:Cb,select:Xo,setCurrentStack:Gi,shaderStages:zs,shadow:Gx,shadowPositionWorld:mx,shapeCircle:sT,sharedUniformGroup:qn,sheen:Nn,sheenRoughness:Sn,shiftLeft:wa,shiftRight:Aa,shininess:Fn,sign:no,sin:Za,sinc:(e,t)=>Za(Da.mul(t.mul(e).sub(1))).div(Da.mul(t.mul(e).sub(1))),skinning:Yc,smoothstep:Uo,smoothstepElement:zo,specularColor:Bn,specularF90:Ln,spherizeUV:ty,split:(e,t)=>Fi(new Zs(Fi(e),t)),spritesheetUV:ny,sqrt:ja,stack:If,step:_o,stepElement:Ho,storage:qc,storageBarrier:()=>Yb("storage").toStack(),storageObject:(e,t,r)=>(console.warn('THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),qc(e,t,r).setPBO(!0)),storageTexture:Wy,string:(e="")=>Fi(new si(e,"string")),struct:(e,t=null)=>{const r=new Df(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;eYb("texture").toStack(),textureBicubic:og,textureCubeUV:Ug,textureLoad:Ju,textureSize:ju,textureStore:(e,t,r)=>{const s=Wy(e,t,r);return null!==r&&s.toStack(),s},thickness:Gn,time:Qf,timerDelta:(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),Zf.mul(e)),timerGlobal:(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),Qf.mul(e)),timerLocal:(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),Qf.mul(e)),toneMapping:xu,toneMappingExposure:Tu,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>Fi(new pb(t,r,Fi(s),Fi(i),Fi(n))),transformDirection:Po,transformNormal:td,transformNormalToView:rd,transformedClearcoatNormalView:nd,transformedNormalView:sd,transformedNormalWorld:id,transmission:kn,transpose:fo,triNoise3D:qf,triplanarTexture:(...e)=>oy(...e),triplanarTextures:oy,trunc:go,uint:Xi,uniform:Zn,uniformArray:il,uniformCubeTexture:(e=md)=>yd(e),uniformGroup:jn,uniformTexture:(e=Ku)=>Zu(e),unpremultiplyAlpha:Kh,userData:(e,t,r)=>Fi(new Ky(e,t,r)),uv:$u,uvec2:Zi,uvec3:rn,uvec4:on,varying:au,varyingProperty:fn,vec2:Yi,vec3:en,vec4:nn,vectorComponents:Hs,velocity:eb,vertexColor:zh,vertexIndex:Bc,vertexStage:ou,vibrance:sb,viewZToLogarithmicDepth:Bh,viewZToOrthographicDepth:Ch,viewZToPerspectiveDepth:Mh,viewport:fh,viewportCoordinate:bh,viewportDepthTexture:Ah,viewportLinearDepth:Dh,viewportMipTexture:Sh,viewportResolution:Th,viewportSafeUV:sy,viewportSharedTexture:sp,viewportSize:yh,viewportTexture:Nh,viewportUV:xh,wgsl:(e,t)=>Eb(e,t,"wgsl"),wgslFn:(e,t)=>Ab(e,t,"wgsl"),workgroupArray:(e,t)=>Fi(new Zb("Workgroup",e,t)),workgroupBarrier:()=>Yb("workgroup").toStack(),workgroupId:jb,workingToColorSpace:hu,xor:_a});const QT=new Bf;class ZT extends Zm{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(QT),QT.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(QT),QT.a=1,n=!0;else if(!0===i.isNode){const o=this.get(e),u=i;QT.copy(s._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=Yo(nn(u).mul(zy),{getUV:()=>Hy.mul(Ql),getTextureLevel:()=>Gy});let h=Mc;h=h.setZ(h.w);const p=new Yh;function g(){i.removeEventListener("dispose",g),l.material.dispose(),l.geometry.dispose()}p.name="Background.material",p.side=S,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=h,p.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new X(new Oe(1,32,32),p),l.frustumCulled=!1,l.name="Background.mesh",l.onBeforeRender=function(e,t,r){this.matrixWorld.copyPosition(r.matrixWorld)},i.addEventListener("dispose",g)}const d=u.getCacheKey();o.backgroundCacheKey!==d&&(o.backgroundMeshNode.node=nn(u).mul(zy),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=d),t.unshift(l,l.geometry,l.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?QT.set(0,0,0,1):"alpha-blend"===a&&QT.set(0,0,0,0),!0===s.autoClear||!0===n){const m=r.clearColorValue;m.r=QT.r,m.g=QT.g,m.b=QT.b,m.a=QT.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),r.depthClearValue=s._clearDepth,r.stencilClearValue=s._clearStencil,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 JT=0;class e_{constructor(e="",t=[],r=0,s=[]){this.name=e,this.bindings=t,this.index=r,this.bindingsReference=s,this.id=JT++}}class t_{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 e_(t.name,[],t.index,t);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class r_{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class s_{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class i_{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class n_ extends i_{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class a_{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let o_=0;class u_{constructor(e=null){this.id=o_++,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 l_{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class d_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class c_ extends d_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class h_ extends d_{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class p_ extends d_{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class g_ extends d_{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class m_ extends d_{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class f_ extends d_{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class y_ extends d_{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class b_ extends d_{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class x_ extends c_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class T_ extends h_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class __ extends p_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class v_ extends g_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class N_ extends m_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class S_ extends f_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class E_ extends y_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class w_ extends b_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const A_=new WeakMap,R_=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),C_=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class M_{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.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=If(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new u_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=A_.get(this.renderer);return void 0===e&&(e=new qm,A_.set(this.renderer,e)),e}createRenderTarget(e,t,r){return new ue(e,t,r)}createCubeRenderTarget(e,t){return new cp(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=this.getBindGroupsCache(),s=[];let i,n=!0;for(const e of t)s.push(e),n=n&&!0!==e.groupNode.shared;return n?(i=r.get(s),void 0===i&&(i=new e_(e,s,this.bindingsIndexes[e].group,s),r.set(s,i))):i=new e_(e,s,this.bindingsIndexes[e].group,s),i}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 zs)for(const s in r[e]){const i=r[e][s];(t[s]||(t[s]=[])).push(...i)}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")}( ${C_(n.r)}, ${C_(n.g)}, ${C_(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 r_(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===_)return"int";if(t===T)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=Es(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return R_.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 ze||!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")}addStack(){return this.stack=If(this.stack),this.stacks.push(zi()||this.stack),Gi(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Gi(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);let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new r_("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}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 e=this.structs.index++;null===r&&(r="StructType"+e),n=new l_(r,t),this.structs[s].push(n),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 s_(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,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=this.getArrayCount(e);o=new i_(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 n_(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,console.warn(`THREE.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 a_("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 wb,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 Lf(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,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 u_,this.stack=If();for(const r of Gs)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(){console.warn("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(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e){let t="";const r=this.vars[e];if(void 0!==r)for(const e of r)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("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(){console.warn("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}build(){const{object:e,material:t,renderer:r}=this;if(null!==t){let e=r.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new Yh),e.build(this)}else this.addFlow("compute",e);for(const e of Gs){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of zs){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}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new x_(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new T_(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new __(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new v_(e);if("color"===t)return new N_(e);if("mat2"===t)return new S_(e);if("mat3"===t)return new E_(e);if("mat4"===t)return new w_(e);throw new Error(`Uniform "${t}" not declared.`)}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${He} - Node System\n`}*[Symbol.iterator](){}}class P_{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.frameId&&!1!==e.update(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.renderId&&!1!==e.update(this)&&t.set(r,this.renderId)}else t===Vs.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 B_{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}B_.isNodeFunctionInput=!0;class L_ extends Zx{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:lx(this.light),lightColor:e}}}const F_=new a,I_=new a;let D_=null;class V_ extends Zx{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Zn(new r).setGroup(Kn),this.halfWidth=Zn(new r).setGroup(Kn),this.updateType=Vs.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;I_.identity(),F_.copy(t.matrixWorld),F_.premultiply(r),I_.extractRotation(F_),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(I_),this.halfHeight.value.applyMatrix4(I_)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Zu(D_.LTC_FLOAT_1),r=Zu(D_.LTC_FLOAT_2)):(t=Zu(D_.LTC_HALF_1),r=Zu(D_.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:ux(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){D_=e}}class U_ extends Zx{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Zn(0).setGroup(Kn),this.penumbraCosNode=Zn(0).setGroup(Kn),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(0).setGroup(Kn),this.colorNode=Zn(this.color).setGroup(Kn)}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 Uo(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=nx(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(lx(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=Jx({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=Zu(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 O_ extends U_{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=Zu(r,Yi(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}const k_=ki((([e,t])=>{const r=e.abs().sub(t);return ao(To(r,0)).add(xo(To(r.x,r.y),0))}));class G_ extends U_{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=this.penumbraCosNode,r=this.getLightCoord(e),s=r.xyz.div(r.w),i=k_(s.xy.sub(Yi(.5)),Yi(.5)),n=da(-1,ua(1,ro(t)).sub(1));return Do(i.mul(-2).mul(n))}}class z_ extends Zx{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class H_ extends Zx{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=ax(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Zn(new e).setGroup(Kn)}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=Jl.dot(s).mul(.5).add(.5),n=Fo(r,t,i);e.context.irradiance.addAssign(n)}}class $_ extends Zx{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=il(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=KT(Jl,this.lightProbe);e.context.irradiance.addAssign(t)}}class W_{parseFunction(){console.warn("Abstract function.")}}class j_{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){console.warn("Abstract function.")}}j_.isNodeFunction=!0;const q_=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,X_=/[a-z_0-9]+/gi,K_="#pragma main";class Y_ extends j_{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(K_),r=-1!==t?e.slice(t+12):e,s=r.match(q_);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=X_.exec(i));)n.push(a);const o=[];let u=0;for(;u0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,(()=>{if(!0===r.isCubeTexture||r.mapping===Z||r.mapping===J||r.mapping===he){if(e.backgroundBlurriness>0||r.mapping===he)return pm(r);{let e;return e=!0===r.isCubeTexture?bd(r):Zu(r),fp(e)}}if(!0===r.isTexture)return Zu(r,ph.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&console.error("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=_d("color","color",r).setGroup(Kn),t=_d("density","float",r).setGroup(Kn);return Ub(e,Vb(t))}if(r.isFog){const e=_d("color","color",r).setGroup(Kn),t=_d("near","float",r).setGroup(Kn),s=_d("far","float",r).setGroup(Kn);return Ub(e,Db(t,s))}console.error("THREE.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?bd(r):!0===r.isTexture?Zu(r):void console.error("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}hasOutputChange(e){return Z_.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,r=this.getOutputCacheKey(),s=e.isArrayTexture?Xy(e,en(ph,nl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Zu(e,ph).renderOutput(t.toneMapping,t.currentColorSpace);return Z_.set(e,r),s}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 P_,this.nodeBuilderCache=new Map,this.cacheLib={}}}const rv=new Me;class sv{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;i0,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 cv(i.framebufferWidth,i.framebufferHeight,{format:de,type:Ce,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),n.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,i.layers.mask=n.layers.mask|a.layers.mask;const o=e.parent,u=i.cameras;mv(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 xv(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 Tv(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(e,t,this._renderTarget),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(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 tv(this,r),this._animation=new jm(this._nodes,this.info),this._attributes=new nf(r),this._background=new ZT(this,this._nodes),this._geometries=new uf(this._attributes,this.info),this._textures=new Pf(this,r,this.info),this._pipelines=new mf(r,this._nodes),this._bindings=new ff(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Qm(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new vf(this.lighting),this._bundles=new av,this._renderContexts=new Cf,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}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._compilationPromises,u=!0===e.isScene?e:_v;null===r&&(r=e);const l=this._renderTarget,d=this._renderContexts.get(r,t,l),c=this._activeMipmapLevel,h=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,s.renderId++,s.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new sv),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,d.clippingContext),r!==e&&r.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);d.textures=e.textures,d.depthTexture=e.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(u,p,d);const g=p.opaque,m=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,y),!0===this.transparent&&m.length>0&&this._renderTransparents(m,f,t,u,y),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=Fl,this.overrideNodes.modelNormalViewMatrix=Il):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===Fl&&this.overrideNodes.modelNormalViewMatrix===Il}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i),u=this.backend.get(o);void 0===u.renderContexts&&(u.renderContexts=new Set);const l=s.version!==u.version,d=!1===u.renderContexts.has(a)||l;if(u.renderContexts.add(a),d){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>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=T,p.viewport=!1===p.viewportValue.equals(Nv),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Nv),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new sv),p.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const _=t.isArrayCamera?Ev:Sv;t.isArrayCamera||(wv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_.setFromProjectionMatrix(wv,g));const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,p.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=h,p.depth=h.depthBuffer,p.stencil=h.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=d,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._background.update(u,v,p),p.camera=t,this.backend.beginRender(p);const{bundles:N,lightsNode:S,transparentDoublePass:E,transparent:w,opaque:A}=v;return N.length>0&&this._renderBundles(N,u,S),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,S),!0===this.transparent&&w.length>0&&this._renderTransparents(w,E,t,u,S),this.backend.finishRender(p),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==s&&(this.setRenderTarget(l,d,c),this._renderOutput(h)),u.onAfterRender(this,e,t,h),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,r);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.getForClear(s),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,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){!1===this._initialized&&await this.init(),this.clear(e,t,r)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:p}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:le}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,r=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const s=this.backend,i=this._pipelines,n=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(const t of o){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),n.delete(t),a.delete(t)};t.addEventListener("dispose",e);const r=t.onInitFunction;null!==r&&r.call(t,{renderer:this})}a.updateForCompute(t),n.updateForCompute(t);const r=n.getForCompute(t),o=i.getForCompute(t,r);s.compute(e,t,r,o)}s.finishCompute(e),t.renderId=r}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=Av.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Av.copy(t).floor()}else t=Av.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)}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)}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?Ev:Sv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&Av.setFromMatrixPosition(e.matrixWorld).applyMatrix4(wv);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,Av.z,null,i)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?Ev:Sv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Av.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(wv)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=S;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=je;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=E}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(c=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(d=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(l=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&i.side===E&&!1===i.forceSinglePass?(i.side=S,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=je,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=E):this._handleObjectFunction(e,i,t,r,a,n,o,u),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==d&&(t.overrideMaterial.colorNode=d),e.onAfterRender(this,t,r,s,i,n)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n;const l=this._nodes.needsRefresh(u);if(l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u)}_createObjectPipeline(e,t,r,s,i,n,a,o){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)}get compile(){return this.compileAsync}}class Cv{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class Mv extends Cv{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(sf-e%sf)%sf;var e}get buffer(){return this._buffer}update(){return!0}}class Pv extends Mv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Bv=0;class Lv extends Pv{constructor(e,t){super("UniformBuffer_"+Bv++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class Fv extends Pv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r0?s:"";t=`${e.name} {\n\t${r} ${i.name}[${n}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,n=!0}const a=i.node.precision;if(null!==a&&(t=Hv[a]+" "+t),n){t="\t"+t;const e=i.groupNode.name;(s[e]||(s[e]=[])).push(t)}else t="uniform "+t,r.push(t)}let i="";for(const t in s){const r=s[t];i+=this._getGLSLUniformStruct(e+"_"+t,r.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==_){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+=`${Wv[s.interpolationType]||s.interpolationType} ${jv[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+=`${Wv[e.interpolationType]||e.interpolationType} ${jv[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`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,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=$v[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)}$v[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];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r}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 Ov(i.name,i.node,s),u.push(a);else if("cubeTexture"===t)a=new kv(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new Gv(i.name,i.node,s),u.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new Lv(e,s);t.name=e.name,u.push(t),a=t}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let n=e[o];void 0===n&&(n=new Dv(r+"_"+o,s),e[o]=n,u.push(n)),a=this.getNodeUniform(i,t),n.addUniform(a)}n.uniformGPU=a}return i}}let Kv=null,Yv=null;class Qv{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void pt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void pt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Kv=Kv||new t,this.renderer.getDrawingBufferSize(Kv)}setScissorTest(){}getClearColor(){const e=this.renderer;return Yv=Yv||new Bf,e.getClearColor(Yv),Yv.getRGB(Yv),Yv}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${He} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let Zv,Jv,eN=0;class tN{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 rN{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(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===_,id:eN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new tN(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;e1?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 nN,aN,oN,uN=!1;class lN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===uN&&(this._init(),uN=!0)}_init(){const e=this.gl;nN={[Nr]:e.REPEAT,[vr]:e.CLAMP_TO_EDGE,[_r]:e.MIRRORED_REPEAT},aN={[v]:e.NEAREST,[Sr]:e.NEAREST_MIPMAP_NEAREST,[Ge]:e.NEAREST_MIPMAP_LINEAR,[Y]:e.LINEAR,[ke]:e.LINEAR_MIPMAP_NEAREST,[V]:e.LINEAR_MIPMAP_LINEAR},oN={[Pr]:e.NEVER,[Mr]:e.ALWAYS,[De]:e.LESS,[Cr]:e.LEQUAL,[Rr]:e.EQUAL,[Ar]:e.GEQUAL,[wr]:e.GREATER,[Er]: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=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(r===n.FLOAT&&(o=n.R32F),r===n.HALF_FLOAT&&(o=n.R16F),r===n.UNSIGNED_BYTE&&(o=n.R8),r===n.UNSIGNED_SHORT&&(o=n.R16),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.R8UI),r===n.UNSIGNED_SHORT&&(o=n.R16UI),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RG&&(r===n.FLOAT&&(o=n.RG32F),r===n.HALF_FLOAT&&(o=n.RG16F),r===n.UNSIGNED_BYTE&&(o=n.RG8),r===n.UNSIGNED_SHORT&&(o=n.RG16),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RG8UI),r===n.UNSIGNED_SHORT&&(o=n.RG16UI),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RGB){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGB32F),r===n.HALF_FLOAT&&(o=n.RGB16F),r===n.UNSIGNED_BYTE&&(o=n.RGB8),r===n.UNSIGNED_SHORT&&(o=n.RGB16),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8:n.RGB8),r===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),r===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5)}if(t===n.RGB_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGB8UI),r===n.UNSIGNED_SHORT&&(o=n.RGB16UI),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGBA32F),r===n.HALF_FLOAT&&(o=n.RGBA16F),r===n.UNSIGNED_BYTE&&(o=n.RGBA8),r===n.UNSIGNED_SHORT&&(o=n.RGBA16),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8_ALPHA8:n.RGBA8),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),r===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(r===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),r===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),r===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&r===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,n=c.getPrimaries(c.workingColorSpace),a=t.colorSpace===b?null:c.getPrimaries(t.colorSpace),o=t.colorSpace===b||n===a?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),r.texParameteri(e,r.TEXTURE_WRAP_S,nN[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,nN[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,nN[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,aN[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,l=t.minFilter===Y&&u?V:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,aN[l]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,oN[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===v)return;if(t.minFilter!==Ge&&t.minFilter!==V)return;if(t.type===I&&!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.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,isDefault:!0})}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.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,{textureGPU:i,glTextureType:n,glFormat:a,glType:o}=s.get(t),{width:u,height:l}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(n,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(n,0,0,0,u,l,a,o,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,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();o.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),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}}function dN(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 cN{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 hN{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const pN={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class gN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const 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){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,r]of this.queryStates)if("ended"===r){const r=this.queries[t];e.push(this.resolveQuery(r))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let 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){console.error("Error checking query:",e),t(this.lastValue)}};n()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}const yN=new t;class bN extends Qv{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.samples>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 cN(this),this.capabilities=new hN(this),this.attributeUtils=new rN(this),this.textureUtils=new lN(this),this.bufferRenderer=new gN(this),this.state=new sN(this),this.utils=new iN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return l}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,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&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new fN(this.gl,t,2048));const r=this.timestampQueryPool[t];null!==r.allocateQueriesForContext(e)&&r.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize(yN);t.viewport(0,0,e,r)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}this.initTimestampQuery(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;e0&&!1===this._useMultisampledExtension(o)){const i=s.framebuffers[e.getCacheKey()];let n=t.COLOR_BUFFER_BIT;o.resolveDepthBuffer&&(o.depthBuffer&&(n|=t.DEPTH_BUFFER_BIT),o.stencilBuffer&&o.resolveStencilBuffer&&(n|=t.STENCIL_BUFFER_BIT));const a=s.msaaFrameBuffer,u=s.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,a),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),d)for(let e=0;e{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(pt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):pt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?b.renderInstances(_,x,T):b.render(_,x)};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()}));t.push(i)}else 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");console.error("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&&console.warn("THREE.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})}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;epN[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=Ef(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;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,0)}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&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const xN="point-list",TN="line-list",_N="line-strip",vN="triangle-list",NN="triangle-strip",SN="never",EN="less",wN="equal",AN="less-equal",RN="greater",CN="not-equal",MN="greater-equal",PN="always",BN="store",LN="load",FN="clear",IN="ccw",DN="none",VN="front",UN="back",ON="uint16",kN="uint32",GN="r8unorm",zN="r8snorm",HN="r8uint",$N="r8sint",WN="r16uint",jN="r16sint",qN="r16float",XN="rg8unorm",KN="rg8snorm",YN="rg8uint",QN="rg8sint",ZN="r32uint",JN="r32sint",eS="r32float",tS="rg16uint",rS="rg16sint",sS="rg16float",iS="rgba8unorm",nS="rgba8unorm-srgb",aS="rgba8snorm",oS="rgba8uint",uS="rgba8sint",lS="bgra8unorm",dS="bgra8unorm-srgb",cS="rgb9e5ufloat",hS="rgb10a2unorm",pS="rgb10a2unorm",gS="rg32uint",mS="rg32sint",fS="rg32float",yS="rgba16uint",bS="rgba16sint",xS="rgba16float",TS="rgba32uint",_S="rgba32sint",vS="rgba32float",NS="depth16unorm",SS="depth24plus",ES="depth24plus-stencil8",wS="depth32float",AS="depth32float-stencil8",RS="bc1-rgba-unorm",CS="bc1-rgba-unorm-srgb",MS="bc2-rgba-unorm",PS="bc2-rgba-unorm-srgb",BS="bc3-rgba-unorm",LS="bc3-rgba-unorm-srgb",FS="bc4-r-unorm",IS="bc4-r-snorm",DS="bc5-rg-unorm",VS="bc5-rg-snorm",US="bc6h-rgb-ufloat",OS="bc6h-rgb-float",kS="bc7-rgba-unorm",GS="bc7-rgba-srgb",zS="etc2-rgb8unorm",HS="etc2-rgb8unorm-srgb",$S="etc2-rgb8a1unorm",WS="etc2-rgb8a1unorm-srgb",jS="etc2-rgba8unorm",qS="etc2-rgba8unorm-srgb",XS="eac-r11unorm",KS="eac-r11snorm",YS="eac-rg11unorm",QS="eac-rg11snorm",ZS="astc-4x4-unorm",JS="astc-4x4-unorm-srgb",eE="astc-5x4-unorm",tE="astc-5x4-unorm-srgb",rE="astc-5x5-unorm",sE="astc-5x5-unorm-srgb",iE="astc-6x5-unorm",nE="astc-6x5-unorm-srgb",aE="astc-6x6-unorm",oE="astc-6x6-unorm-srgb",uE="astc-8x5-unorm",lE="astc-8x5-unorm-srgb",dE="astc-8x6-unorm",cE="astc-8x6-unorm-srgb",hE="astc-8x8-unorm",pE="astc-8x8-unorm-srgb",gE="astc-10x5-unorm",mE="astc-10x5-unorm-srgb",fE="astc-10x6-unorm",yE="astc-10x6-unorm-srgb",bE="astc-10x8-unorm",xE="astc-10x8-unorm-srgb",TE="astc-10x10-unorm",_E="astc-10x10-unorm-srgb",vE="astc-12x10-unorm",NE="astc-12x10-unorm-srgb",SE="astc-12x12-unorm",EE="astc-12x12-unorm-srgb",wE="clamp-to-edge",AE="repeat",RE="mirror-repeat",CE="linear",ME="nearest",PE="zero",BE="one",LE="src",FE="one-minus-src",IE="src-alpha",DE="one-minus-src-alpha",VE="dst",UE="one-minus-dst",OE="dst-alpha",kE="one-minus-dst-alpha",GE="src-alpha-saturated",zE="constant",HE="one-minus-constant",$E="add",WE="subtract",jE="reverse-subtract",qE="min",XE="max",KE=0,YE=15,QE="keep",ZE="zero",JE="replace",ew="invert",tw="increment-clamp",rw="decrement-clamp",sw="increment-wrap",iw="decrement-wrap",nw="storage",aw="read-only-storage",ow="write-only",uw="read-only",lw="read-write",dw="non-filtering",cw="comparison",hw="float",pw="unfilterable-float",gw="depth",mw="sint",fw="uint",yw="2d",bw="3d",xw="2d",Tw="2d-array",_w="cube",vw="3d",Nw="all",Sw="vertex",Ew="instance",ww={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class Aw extends Cv{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class Rw extends Aw{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){this.texture=this.textureNode.value}}class Cw extends Mv{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let Mw=0;class Pw extends Cw{constructor(e,t){super("StorageBuffer_"+Mw++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Os.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class Bw extends Zm{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:CE}),this.flipYSampler=e.createSampler({minFilter:ME}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:NN,stripIndexFormat:kN},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:NN,stripIndexFormat:kN},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.getTransferPipeline(s),o=this.getFlipYPipeline(s),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:xw,baseArrayLayer:r}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:xw,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,r)=>{const s=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:r,loadOp:FN,storeOp:BN,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(a,l,d),h(o,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,r=0){const s=this.get(e);void 0===s.useCount&&(s.useCount=0,s.layers=[]);const i=s.layers[r]||this._mipmapCreateBundles(e,t,r),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,i),this.device.queue.submit([n.finish()]),0!==s.useCount&&(s.layers[r]=i),s.useCount++}_mipmapCreateBundles(e,t,r){const s=this.getTransferPipeline(t.format),i=s.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:xw,baseArrayLayer:r});const a=[];for(let o=1;o1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,Uw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,Ow={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 kw extends j_{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(Vw);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=Uw.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 Gw extends W_{parseFunction(e){return new kw(e)}}const zw="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},Hw={[Os.READ_ONLY]:"read",[Os.WRITE_ONLY]:"write",[Os.READ_WRITE]:"read_write"},$w={[Nr]:"repeat",[vr]:"clamp",[_r]:"mirror"},Ww={vertex:zw?zw.VERTEX:1,fragment:zw?zw.FRAGMENT:2,compute:zw?zw.COMPUTE:4},jw={instance:!0,swizzleAssign:!1,storageBuffer:!0},qw={"^^":"tsl_xor"},Xw={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"},Kw={},Yw={tsl_xor:new Sb("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Sb("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Sb("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Sb("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Sb("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Sb("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Sb("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Sb("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 Sb("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 Sb("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Sb("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 Sb("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Sb("\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")},Qw={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"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(Yw.pow_float=new Sb("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),Yw.pow_vec2=new Sb("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[Yw.pow_float]),Yw.pow_vec3=new Sb("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[Yw.pow_float]),Yw.pow_vec4=new Sb("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[Yw.pow_float]),Qw.pow_float="tsl_pow_float",Qw.pow_vec2="tsl_pow_vec2",Qw.pow_vec3="tsl_pow_vec3",Qw.pow_vec4="tsl_pow_vec4");let Zw="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(Zw+="diagnostic( off, derivative_uniformity );\n");class Jw extends M_{constructor(e,t){super(e,t,new Gw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==b}_generateTextureSample(e,t,r,s,i=this.shaderStage){return"fragment"===i?s?`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this._generateTextureSampleLevel(e,t,r,"0",s)}_generateVideoSample(e,t,r=this.shaderStage){if("fragment"===r)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${r} shader.`)}_generateTextureSampleLevel(e,t,r,s,i){return!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,s):this.generateTextureLod(e,t,r,i,s)}generateWrapFunction(e){const t=`tsl_coord_${$w[e.wrapS]}S_${$w[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let r=Kw[t];if(void 0===r){const s=[],i=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===Nr?(s.push(Yw.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===vr?(s.push(Yw.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===_r?(s.push(Yw.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",Kw[t]=r=new Sb(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.globalCache);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.isData3DTexture?"vec3":"vec2",n=u||e.isVideoTexture||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Zo(new Iu(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Zo(new Iu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Zo(new Iu("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${r} ), ${this.generateTextureDimension(e,t,s)}, u32( ${s} ) )`}generateTextureLod(e,t,r,s,i="0u"){const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i),o=e.isData3DTexture?"vec3":"vec2",u=`${o}( ${n}( ${r} ) * ${o}( ${a} ) )`;return this.generateTextureLoad(e,t,u,s,i)}generateTextureLoad(e,t,r,s,i="0u"){let n;return!0===e.isVideoTexture?n=`textureLoad( ${t}, ${r} )`:s?n=`textureLoad( ${t}, ${r}, ${s}, u32( ${i} ) )`:(n=`textureLoad( ${t}, ${r}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(n+=".x")),n}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}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===I||!1===this.isSampleCompare(e)&&e.minFilter===v&&e.magFilter===v||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,r,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,"0",i):this._generateTextureSample(e,t,r,s,i),n}generateTextureGrad(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return!0===e.isDepthTexture&&!0===e.isArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,r,s,i,n=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,r,n):this._generateTextureSampleLevel(e,t,r,s,i),a}generateTextureBias(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===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=qw[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Os.READ_ONLY:e.access}getStorageAccess(e,t){return Hw[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||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);if("texture"===t||"storageTexture"===t?s=new Ov(i.name,i.node,o,n):"cubeTexture"===t?s=new kv(i.name,i.node,o,n):"texture3D"===t&&(s=new Gv(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.setVisibility(Ww[r]),!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new Rw(`${i.name}_sampler`,i.node,o);e.setVisibility(Ww[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?Lv:Pw)(e,o);n.setVisibility(Ww[r]),l.push(n),a=n,i.name=s||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let s=e[u];void 0===s&&(s=new Dv(u,o),s.setVisibility(Ww[r]),e[u]=s,l.push(s)),a=this.getNodeUniform(i,t),s.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){let s=`var ${t} : `;return s+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),s}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];for(let i=0;ir.value.itemSize;return s&&!i}getUniforms(e){const t=this.uniforms[e],r=[],s=[],i=[],n={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let s;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture)s="texture_cube";else if(!0===t.isDepthTexture)s=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)s="texture_2d_array";else if(!0===t.isVideoTexture)s="texture_external";else if(!0===t.isData3DTexture)s="texture_3d";else if(!0===i.node.isStorageTextureNode){s=`texture_storage_2d<${Dw(t)}, ${this.getStorageAccess(i.node,e)}>`}else{s=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${s};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,r=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===i.type?", "+n:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${u}> ${i.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${o} >`;s.push(this._getWGSLStructBinding(i.name,e,u,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in n){const t=n[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=r.join("\n");return a+=s.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${u}\n`),s+=`${i.code}\n\t`,e===n&&"compute"!==t)if(s+="// result\n\n\t","vertex"===t)s+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)r.returnType=a.getNodeType(this),r.structs+="var output : "+r.returnType+";",s+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar output : OutputStruct;",s+=`output.color = ${i.result};\n\n\treturn output;`}}r.flow=s}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getType(e){return Xw[e]||e}isAvailable(e){let t=jw[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),jw[e]=t),t}_getWGSLMethod(e){return void 0!==Yw[e]&&this._include(e),Qw[e]}_include(e){const t=Yw[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${Zw}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class eA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=ES:e.depth&&(t=SS),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.samples}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}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?xN:e.isLineSegments||e.isMesh&&!0===t.wireframe?TN:e.isLine?_N:e.isMesh?vN:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ce)return lS;if(e===ce)return xS;throw new Error("Unsupported outputType")}}const tA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),rA=new Map([[ze,["float16"]]]),sA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class iA{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;e1&&(s.multisampled=!0,r.texture.isDepthTexture||(s.sampleType=pw)),r.texture.isDepthTexture)t.compatibilityMode&&null===r.texture.compareFunction?s.sampleType=pw:s.sampleType=gw;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const e=r.texture.type;e===_?s.sampleType=mw:e===T?s.sampleType=fw:e===I&&(this.backend.hasFeature("float32-filterable")?s.sampleType=hw:s.sampleType=pw)}r.isSampledCubeTexture?s.viewDimension=_w:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?s.viewDimension=Tw:r.isSampledTexture3D&&(s.viewDimension=vw),e.texture=s}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);s.push(e)}return r.createBindGroupLayout({entries:s})}createBindings(e,t,r,s=0){const{backend:i,bindGroupLayoutCache:n}=this,a=i.get(e);let o,u=n.get(e.bindingsReference);void 0===u&&(u=this.createBindingsLayout(e),n.set(e.bindingsReference,u)),r>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[r]===s&&(o=a.groups[r])),void 0===o&&(o=this.createBindGroup(e,u),r>0&&(a.groups[r]=o,a.versions[r]=s)),a.group=o,a.layout=u}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer;r.queue.writeBuffer(i,0,s,0)}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],n=r.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:s});r.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);if(void 0===e.buffer){const r=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=s.createBuffer({label:"bindingBuffer_"+t.name,size:r,usage:i});e.buffer=n}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t);if(void 0===e.buffer){const s=t.attribute;e.buffer=r.get(s).buffer}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}else if(t.isSampledTexture){const e=r.get(t.texture);let a;if(void 0!==e.externalTexture)a=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount,s=`view-${e.texture.width}-${e.texture.height}-${r}`;if(a=e[s],void 0===a){const i=Nw;let n;n=t.isSampledCubeTexture?_w:t.isSampledTexture3D?vw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Tw:xw,a=e[s]=e.texture.createView({aspect:i,dimension:n,mipLevelCount:r})}}n.push({binding:i,resource:a})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class aA{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:o}=n,u=this.backend,l=u.device,d=u.utils,c=u.get(n),h=[];for(const t of e.getBindings()){const e=u.get(t);h.push(e.layout)}const p=u.attributeUtils.createShaderVertexBuffers(e);let g;s.blending===H||s.blending===k&&!1===s.transparent||(g=this._getBlending(s));let m={};!0===s.stencilWrite&&(m={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const f=this._getColorWriteMask(s),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:l.createPipelineLayout({bindGroupLayouts:h})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=v,E.depthWriteEnabled=s.depthWrite,E.depthCompare=_),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),S.depthStencil=E),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[s.getCurrentColorFormat(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);a.push(t.layout)}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===qe){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:$E},r={srcFactor:i,dstFactor:n,operation:$E}};if(e.premultipliedAlpha)switch(s){case k:i(BE,DE,BE,DE);break;case Bt:i(BE,BE,BE,BE);break;case Pt:i(PE,FE,PE,BE);break;case Mt:i(VE,DE,PE,BE)}else switch(s){case k:i(IE,DE,BE,DE);break;case Bt:i(IE,BE,BE,BE);break;case Pt:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mt:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};console.error("THREE.WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Ke:t=PE;break;case wt:t=BE;break;case Et:t=LE;break;case Tt:t=FE;break;case St:t=IE;break;case xt:t=DE;break;case vt:t=VE;break;case bt:t=UE;break;case _t:t=OE;break;case yt:t=kE;break;case Nt:t=GE;break;case 211:t=zE;break;case 212:t=HE;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case kr:t=SN;break;case Or:t=PN;break;case Ur:t=EN;break;case Vr:t=AN;break;case Dr:t=wN;break;case Ir:t=MN;break;case Fr:t=RN;break;case Lr:t=CN;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case Xr:t=QE;break;case qr:t=ZE;break;case jr:t=JE;break;case Wr:t=ew;break;case $r:t=tw;break;case Hr:t=rw;break;case zr:t=sw;break;case Gr:t=iw;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Xe:t=$E;break;case ft:t=WE;break;case mt:t=jE;break;case Yr:t=qE;break;case Kr:t=XE;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;switch(s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?ON:kN),r.side){case je:s.frontFace=IN,s.cullMode=UN;break;case S:s.frontFace=IN,s.cullMode=VN;break;case E:s.frontFace=IN,s.cullMode=DN;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",r.side)}return s}_getColorWriteMask(e){return!0===e.colorWrite?YE:KE}_getDepthCompare(e){let t;if(!1===e.depthTest)t=PN;else{const r=e.depthFunc;switch(r){case kt:t=SN;break;case Ot:t=PN;break;case Ut:t=EN;break;case Vt:t=AN;break;case Dt:t=wN;break;case It:t=MN;break;case Ft:t=RN;break;case Lt:t=CN;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class oA extends mN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,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));let a=0;for(const[,t]of e){const e=n[t],r=n[t+1];a+=Number(r-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class uA extends Qv{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new eA(this),this.attributeUtils=new iA(this),this.bindingUtils=new nA(this),this.pipelineUtils=new aA(this),this.textureUtils=new Iw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},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(ww),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;r.lost.then((t=>{const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}));const s=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=r,this.context=s;const i=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ww.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i}),this.updateSize()}get coordinateSystem(){return d}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const r=e.colorAttachments[0];this.renderer.samples>0?r.view=this.colorBuffer.createView():r.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;if(void 0===i||s.width!==r.width||s.height!==r.height||s.dimensions!==r.dimensions||s.activeMipmapLevel!==e.activeMipmapLevel||s.activeCubeFace!==e.activeCubeFace||s.samples!==r.samples){i={},s.descriptors=i;const e=()=>{r.removeEventListener("dispose",e),this.delete(r)};!1===r.hasEventListener("dispose",e)&&r.addEventListener("dispose",e)}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:LN}),this.initTimestampQuery(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;ea?(u.x=Math.min(t.dispatchCount,a),u.y=Math.ceil(t.dispatchCount/a)):u.x=t.dispatchCount,i.dispatchWorkgroups(u.x,u.y,u.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:r,material:s,context:i,pipeline:n}=e,a=e.getBindings(),o=this.get(i),u=this.get(n).pipeline,l=e.getIndex(),d=null!==l,c=e.getDrawParameters();if(null===c)return;const h=(t,r)=>{this.pipelineUtils.setPipeline(t,u),r.pipeline=u;const n=r.bindingGroups;for(let e=0,r=a.length;e{if(h(s,i),!0===r.isBatchedMesh){const e=r._multiDrawStarts,i=r._multiDrawCounts,n=r._multiDrawCount,a=r._multiDrawInstances;null!==a&&pt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o1?0:o;!0===d?s.drawIndexed(i[o],n,e[o]/l.array.BYTES_PER_ELEMENT,0,u):s.draw(i[o],n,e[o],u),t.update(r,i[o],n)}}else if(!0===d){const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndexedIndirect(e,0)}else s.drawIndexed(i,n,a,0,0);t.update(r,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndirect(e,0)}else s.draw(i,n,a,0);t.update(r,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),s=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==s.length){const e=this.get(n),r=[],i=new Uint32Array([0,0,0,0]);for(let t=0,n=s.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new bN(e)));super(new t(e),e),this.library=new cA,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class pA extends ds{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class gA{constructor(e,t=nn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new Yh;r.name="PostProcessing",this._quadMesh=new Ay(r)}render(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}dispose(){this._quadMesh.material.dispose()}_update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;this._quadMesh.material.fragmentNode=!0===this.outputColorTransform?Ou(this.outputNode,t,r):this.outputNode.context({toneMapping:t,outputColorSpace:r}),this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,await this._quadMesh.renderAsync(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}}class mA extends x{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Y,this.minFilter=Y,this.isStorageTexture=!0}}class fA extends Iy{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class yA extends cs{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new hs(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):console.error(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]?(console.error("THREE.NodeLoader: Node type not found:",e),ji()):Fi(new this.nodes[e])}}class bA extends ps{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 xA extends gs{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 yA;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 bA;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}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={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 null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};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)}return t}equals(e){const{object:t,material:r,geometry:s}=e,i=this.getRenderObjectData(e);if(!0!==i.worldMatrix.equals(t.matrixWorld))return i.worldMatrix.copy(t.matrixWorld),!1;const n=i.material;for(const e in n){const t=n[e],s=r[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return n[e]=s,!1}if(n.transmission>0){const{width:t,height:r}=e.context;if(i.bufferWidth!==t||i.bufferHeight!==r)return i.bufferWidth=t,i.bufferHeight=r,!1}const a=i.geometry,o=s.attributes,u=a.attributes,l=Object.keys(u),d=Object.keys(o);if(a.id!==s.id)return a.id=s.id,!1;if(l.length!==d.length)return i.geometry.attributes=this.getAttributesData(o),!1;for(const e of l){const t=u[e],r=o[e];if(void 0===r)return delete u[e],!1;if(t.version!==r.version)return t.version=r.version,!1}const c=s.index,h=a.indexVersion,p=c?c.version:null;if(h!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==s.drawRange.start||a.drawRange.count!==s.drawRange.count)return a.drawRange.start=s.drawRange.start,a.drawRange.count=s.drawRange.count,!1;if(i.morphTargetInfluences){let e=!1;for(let r=0;r>>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 bs=e=>ys(e),xs=e=>ys(e),Ts=(...e)=>ys(e);function _s(e,t=!1){const r=[];!0===e.isNode&&(r.push(e.id),e=e.getSelf());for(const{property:s,childNode:i}of vs(e))r.push(ys(s.slice(0,-4)),i.getCacheKey(t));return ys(r)}function*vs(e,t=!1){for(const r in e){if(!0===r.startsWith("_"))continue;const s=e[r];if(!0===Array.isArray(s))for(let e=0;ee.charCodeAt(0))).buffer}var Is=Object.freeze({__proto__:null,arrayBufferToBase64:Ls,base64ToArrayBuffer:Fs,getByteBoundaryFromType:Cs,getCacheKey:_s,getDataFromObject:Bs,getLengthFromType:As,getMemoryLengthFromType:Rs,getNodeChildren:vs,getTypeFromLength:Es,getTypedArrayFromType:ws,getValueFromType:Ps,getValueType:Ms,hash:Ts,hashArray:xs,hashString:bs});const Ds={VERTEX:"vertex",FRAGMENT:"fragment"},Vs={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Us={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Os={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ks=["fragment","vertex"],Gs=["setup","analyze","generate"],zs=[...ks,"compute"],Hs=["x","y","z","w"],$s={analyze:"setup",generate:"analyze"};let Ws=0;class js extends o{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Vs.NONE,this.updateBeforeType=Vs.NONE,this.updateAfterType=Vs.NONE,this.uuid=u.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ws++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Vs.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Vs.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Vs.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of vs(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Ts(_s(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const r=this.getShared(e);if(this!==r)return r.build(e,t);const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const i=$s[e.buildStage];if(i&&!0!==s.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const r of Object.values(t))if(r&&!0===r.isNode){if(!0===r.parents){const t=e.getNodeProperties(r);t.parents=t.parents||[],t.parents.push(this)}r.build(e)}}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const r=this.getNodeType(e),s=e.getDataFromNode(this);n=s.snippet,void 0===n?void 0===s.generated?(s.generated=!0,n=this.generate(e)||"",s.snippet=n):(console.warn("THREE.Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,r,t)}else n=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return vs(this)}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(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}}class qs extends js{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Xs extends js{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(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 Ks extends js{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 Ys extends Ks{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,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 o=0;for(const t of i){if(o>=s){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${r}()' type.`);break}let i,u=t.getNodeType(e),l=e.getTypeLength(u);o+l>s&&(console.error(`THREE.TSL: Length of '${r}()' data exceeds maximum length of output type.`),l=s-o,u=e.getTypeFromLength(l)),o+=l,i=t.build(e,u);const d=e.getComponentType(u);d!==n&&(i=e.format(i,d,n)),a.push(i)}const u=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(u,r,t)}}const Qs=Hs.join("");class Zs extends js{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(Hs.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const 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===Qs.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 Js extends Ks{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}getNodeType(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;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),li=e=>ui(e).split("").sort().join(""),di={setup(e,t){const r=t.shift();return e(Ii(r),...t)},get(e,t,r){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(ni.assign(r,...e),r);if(ai.has(t)){const s=ai.get(t);return e.isStackNode?(...e)=>r.add(s(...e)):(...e)=>s(r,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&ai.has(t.slice(0,t.length-6))){const s=ai.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>r.assign(e[0],s(...e)):(...e)=>r.assign(s(r,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=ui(t),Fi(new Zs(r,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(3).toLowerCase()),r=>Fi(new Js(e,t,Fi(r)));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(4).toLowerCase()),()=>Fi(new ei(Fi(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Fi(new Zs(e,t));if(!0===/^\d+$/.test(t))return Fi(new qs(r,new si(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Fi(new ii(r,e))}return Reflect.get(e,t,r)},set:(e,t,r,s)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,r,s):(s[t].assign(r),!0)},ci=new WeakMap,hi=new WeakMap,pi=function(e,t=null){for(const r in e)e[r]=Fi(e[r],t);return e},gi=function(e,t=null){const r=e.length;for(let s=0;sFi(null!==s?Object.assign(e,s):e);let n,a,o,u=t;function l(t){let r;return r=u?/[a-z]/i.test(u)?u+"()":u:e.type,void 0!==a&&t.lengtho?(console.error(`THREE.TSL: "${r}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?n=(...t)=>i(new e(...Di(l(t)))):null!==r?(r=Fi(r),n=(...s)=>i(new e(t,...Di(l(s)),r))):n=(...r)=>i(new e(t,...Di(l(r)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(u=e,n),n},fi=function(e,...t){return Fi(new e(...Di(t)))};class yi extends js{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let s=hi.get(e.constructor);void 0===s&&(s=new WeakMap,hi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=Fi(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i),o=Fi(i.call(r))}else{const s=t.jsFunc,i=null!==r||s.length>1?s(r||[],e):s(e);o=Fi(i)}return e.subBuildFn=a,t.once&&(s[n]=o),o}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);if("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 r}}class bi extends js{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Ii(e),Fi(new yi(this,e))}setup(){return this.call()}}const xi=[!1,!0],Ti=[0,1,2,3],_i=[-1,-2],vi=[.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],Ni=new Map;for(const e of xi)Ni.set(e,new si(e));const Si=new Map;for(const e of Ti)Si.set(e,new si(e,"uint"));const Ei=new Map([...Si].map((e=>new si(e.value,"int"))));for(const e of _i)Ei.set(e,new si(e,"int"));const wi=new Map([...Ei].map((e=>new si(e.value))));for(const e of vi)wi.set(e,new si(e));for(const e of vi)wi.set(-e,new si(-e));const Ai={bool:Ni,uint:Si,ints:Ei,float:wi},Ri=new Map([...Ni,...wi]),Ci=(e,t)=>Ri.has(e)?Ri.get(e):!0===e.isNode?e:new si(e,t),Mi=function(e,t=null){return(...r)=>{if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every((e=>"object"!=typeof e)))&&(r=[Ps(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return Fi(t.get(r[0]));if(1===r.length){const t=Ci(r[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Fi(t):Fi(new Xs(t,e))}const s=r.map((e=>Ci(e)));return Fi(new Ys(s,e))}},Pi=e=>"object"==typeof e&&null!==e?e.value:e,Bi=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Li(e,t){return new Proxy(new bi(e,t),di)}const Fi=(e,t=null)=>function(e,t=null){const r=Ms(e);if("node"===r){let t=ci.get(e);return void 0===t&&(t=new Proxy(e,di),ci.set(e,t),ci.set(t,t)),t}return null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?Fi(Ci(e,t)):"shader"===r?e.isFn?e:ki(e):e}(e,t),Ii=(e,t=null)=>new pi(e,t),Di=(e,t=null)=>new gi(e,t),Vi=(...e)=>new mi(...e),Ui=(...e)=>new fi(...e);let Oi=0;const ki=(e,t=null)=>{let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:console.error("THREE.TSL: Invalid layout type."),t=null));const s=new Li(e,r),i=(...e)=>{let t;Ii(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];const i=s.call(t);return"void"===r&&i.toStack(),i};if(i.shaderNode=s,i.id=s.id,i.isFn=!0,i.getNodeType=(...e)=>s.getNodeType(...e),i.getCacheKey=(...e)=>s.getCacheKey(...e),i.setLayout=e=>(s.setLayout(e),i),i.once=(e=null)=>(s.once=!0,s.subBuilds=e,i),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+Oi++,type:r,inputs:[]};for(const r in t)"return"!==r&&e.inputs.push({name:r,type:t[r]});t=e}i.setLayout(t)}return i},Gi=e=>{ni=e},zi=()=>ni,Hi=(...e)=>ni.If(...e);function $i(e){return ni&&ni.add(e),e}oi("toStack",$i);const Wi=new Mi("color"),ji=new Mi("float",Ai.float),qi=new Mi("int",Ai.ints),Xi=new Mi("uint",Ai.uint),Ki=new Mi("bool",Ai.bool),Yi=new Mi("vec2"),Qi=new Mi("ivec2"),Zi=new Mi("uvec2"),Ji=new Mi("bvec2"),en=new Mi("vec3"),tn=new Mi("ivec3"),rn=new Mi("uvec3"),sn=new Mi("bvec3"),nn=new Mi("vec4"),an=new Mi("ivec4"),on=new Mi("uvec4"),un=new Mi("bvec4"),ln=new Mi("mat2"),dn=new Mi("mat3"),cn=new Mi("mat4");oi("toColor",Wi),oi("toFloat",ji),oi("toInt",qi),oi("toUint",Xi),oi("toBool",Ki),oi("toVec2",Yi),oi("toIVec2",Qi),oi("toUVec2",Zi),oi("toBVec2",Ji),oi("toVec3",en),oi("toIVec3",tn),oi("toUVec3",rn),oi("toBVec3",sn),oi("toVec4",nn),oi("toIVec4",an),oi("toUVec4",on),oi("toBVec4",un),oi("toMat2",ln),oi("toMat3",dn),oi("toMat4",cn);const hn=Vi(qs).setParameterLength(2),pn=(e,t)=>Fi(new Xs(Fi(e),t));oi("element",hn),oi("convert",pn);oi("append",(e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),$i(e))));class gn extends js{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}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 mn=(e,t)=>Fi(new gn(e,t)),fn=(e,t)=>Fi(new gn(e,t,!0)),yn=Ui(gn,"vec4","DiffuseColor"),bn=Ui(gn,"vec3","EmissiveColor"),xn=Ui(gn,"float","Roughness"),Tn=Ui(gn,"float","Metalness"),_n=Ui(gn,"float","Clearcoat"),vn=Ui(gn,"float","ClearcoatRoughness"),Nn=Ui(gn,"vec3","Sheen"),Sn=Ui(gn,"float","SheenRoughness"),En=Ui(gn,"float","Iridescence"),wn=Ui(gn,"float","IridescenceIOR"),An=Ui(gn,"float","IridescenceThickness"),Rn=Ui(gn,"float","AlphaT"),Cn=Ui(gn,"float","Anisotropy"),Mn=Ui(gn,"vec3","AnisotropyT"),Pn=Ui(gn,"vec3","AnisotropyB"),Bn=Ui(gn,"color","SpecularColor"),Ln=Ui(gn,"float","SpecularF90"),Fn=Ui(gn,"float","Shininess"),In=Ui(gn,"vec4","Output"),Dn=Ui(gn,"float","dashSize"),Vn=Ui(gn,"float","gapSize"),Un=Ui(gn,"float","pointWidth"),On=Ui(gn,"float","IOR"),kn=Ui(gn,"float","Transmission"),Gn=Ui(gn,"float","Thickness"),zn=Ui(gn,"float","AttenuationDistance"),Hn=Ui(gn,"color","AttenuationColor"),$n=Ui(gn,"float","Dispersion");class Wn extends js{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1){super("string"),this.name=e,this.shared=t,this.order=r,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const jn=e=>new Wn(e),qn=(e,t=0)=>new Wn(e,!0,t),Xn=qn("frame"),Kn=qn("render"),Yn=jn("object");class Qn extends ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Yn}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const r=this.getSelf();return e=e.bind(r),super.onUpdate((t=>{const s=e(t,r);void 0!==s&&(this.value=s)}),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.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,r,t)}}const Zn=(e,t)=>{const r=Bi(t||e),s=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Fi(new Qn(s,r))};class Jn extends Ks{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const ea=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Jn(null,r.length,r)}else{const r=e[0],s=e[1];t=new Jn(r,s)}return Fi(t)};oi("toArray",((e,t)=>ea(Array(t).fill(e))));class ta extends Ks{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return Hs.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=e.getNodeProperties(this);s.sourceNode=r,s.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.getNodeType(e),a=r.build(e),o=s.build(e,n),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=a);else if(i){const s=e.getVarFromNode(this,null,n),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)console.error("THREE.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?Di(t):Ii(t[0]),Fi(new sa(Fi(e),t)));oi("call",ia);const na={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class aa extends Ks{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new aa(e,t,r);for(let t=0;t>"===t||"<<"===t)return e.getIntegerType(i);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(i),e.getTypeLength(n));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(i)){if("float"===n)return i;if(e.isVector(n))return e.getVectorFromMatrix(i);if(e.isMatrix(n))return i}else if(e.isMatrix(n)){if("float"===i)return n;if(e.isVector(i))return e.getVectorFromMatrix(n)}return e.getTypeLength(n)>e.getTypeLength(i)?n:i}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e);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),d=i?i.build(e,o):null,c=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===l;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${d} )`,n,t):e.format(`( ${u} ${r} ${d} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${d} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${d} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(c)return e.format(`${c}( ${u}, ${d} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${d} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${d}`,n,t);{let i=`( ${u} ${r} ${d} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return c?e.format(`${c}( ${u}, ${d} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${d} ${r} ${u}`,n,t):e.format(`${u} ${r} ${d}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const oa=Vi(aa,"+").setParameterLength(2,1/0).setName("add"),ua=Vi(aa,"-").setParameterLength(2,1/0).setName("sub"),la=Vi(aa,"*").setParameterLength(2,1/0).setName("mul"),da=Vi(aa,"/").setParameterLength(2,1/0).setName("div"),ca=Vi(aa,"%").setParameterLength(2).setName("mod"),ha=Vi(aa,"==").setParameterLength(2).setName("equal"),pa=Vi(aa,"!=").setParameterLength(2).setName("notEqual"),ga=Vi(aa,"<").setParameterLength(2).setName("lessThan"),ma=Vi(aa,">").setParameterLength(2).setName("greaterThan"),fa=Vi(aa,"<=").setParameterLength(2).setName("lessThanEqual"),ya=Vi(aa,">=").setParameterLength(2).setName("greaterThanEqual"),ba=Vi(aa,"&&").setParameterLength(2,1/0).setName("and"),xa=Vi(aa,"||").setParameterLength(2,1/0).setName("or"),Ta=Vi(aa,"!").setParameterLength(1).setName("not"),_a=Vi(aa,"^^").setParameterLength(2).setName("xor"),va=Vi(aa,"&").setParameterLength(2).setName("bitAnd"),Na=Vi(aa,"~").setParameterLength(2).setName("bitNot"),Sa=Vi(aa,"|").setParameterLength(2).setName("bitOr"),Ea=Vi(aa,"^").setParameterLength(2).setName("bitXor"),wa=Vi(aa,"<<").setParameterLength(2).setName("shiftLeft"),Aa=Vi(aa,">>").setParameterLength(2).setName("shiftRight"),Ra=ki((([e])=>(e.addAssign(1),e))),Ca=ki((([e])=>(e.subAssign(1),e))),Ma=ki((([e])=>{const t=qi(e).toConst();return e.addAssign(1),t})),Pa=ki((([e])=>{const t=qi(e).toConst();return e.subAssign(1),t}));oi("add",oa),oi("sub",ua),oi("mul",la),oi("div",da),oi("mod",ca),oi("equal",ha),oi("notEqual",pa),oi("lessThan",ga),oi("greaterThan",ma),oi("lessThanEqual",fa),oi("greaterThanEqual",ya),oi("and",ba),oi("or",xa),oi("not",Ta),oi("xor",_a),oi("bitAnd",va),oi("bitNot",Na),oi("bitOr",Sa),oi("bitXor",Ea),oi("shiftLeft",wa),oi("shiftRight",Aa),oi("incrementBefore",Ra),oi("decrementBefore",Ca),oi("increment",Ma),oi("decrement",Pa);const Ba=(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),ca(qi(e),qi(t)));oi("modInt",Ba);class La extends Ks{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===La.MAX||e===La.MIN)&&arguments.length>3){let i=new La(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}getNodeType(e){const t=this.method;return t===La.LENGTH||t===La.DISTANCE||t===La.DOT?"float":t===La.CROSS?"vec3":t===La.ALL||t===La.ANY?"bool":t===La.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===La.ONE_MINUS)i=ua(1,t);else if(s===La.RECIPROCAL)i=da(1,t);else if(s===La.DIFFERENCE)i=io(ua(t,r));else if(s===La.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=nn(en(n),0):s=nn(en(s),0);const a=la(s,n).xyz;i=Ya(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===La.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const c=[];return r===La.CROSS?c.push(n.build(e,s),a.build(e,s)):u===l&&r===La.STEP?c.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==l||r!==La.MIN&&r!==La.MAX?r===La.REFRACT?c.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===La.MIX?c.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===d&&r===La.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==La.DFDX&&r!==La.DFDY||(console.warn(`THREE.TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),c.push(n.build(e,i)),null!==a&&c.push(a.build(e,i)),null!==o&&c.push(o.build(e,i))):c.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${c.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}La.ALL="all",La.ANY="any",La.RADIANS="radians",La.DEGREES="degrees",La.EXP="exp",La.EXP2="exp2",La.LOG="log",La.LOG2="log2",La.SQRT="sqrt",La.INVERSE_SQRT="inversesqrt",La.FLOOR="floor",La.CEIL="ceil",La.NORMALIZE="normalize",La.FRACT="fract",La.SIN="sin",La.COS="cos",La.TAN="tan",La.ASIN="asin",La.ACOS="acos",La.ATAN="atan",La.ABS="abs",La.SIGN="sign",La.LENGTH="length",La.NEGATE="negate",La.ONE_MINUS="oneMinus",La.DFDX="dFdx",La.DFDY="dFdy",La.ROUND="round",La.RECIPROCAL="reciprocal",La.TRUNC="trunc",La.FWIDTH="fwidth",La.TRANSPOSE="transpose",La.BITCAST="bitcast",La.EQUALS="equals",La.MIN="min",La.MAX="max",La.STEP="step",La.REFLECT="reflect",La.DISTANCE="distance",La.DIFFERENCE="difference",La.DOT="dot",La.CROSS="cross",La.POW="pow",La.TRANSFORM_DIRECTION="transformDirection",La.MIX="mix",La.CLAMP="clamp",La.REFRACT="refract",La.SMOOTHSTEP="smoothstep",La.FACEFORWARD="faceforward";const Fa=ji(1e-6),Ia=ji(1e6),Da=ji(Math.PI),Va=ji(2*Math.PI),Ua=Vi(La,La.ALL).setParameterLength(1),Oa=Vi(La,La.ANY).setParameterLength(1),ka=Vi(La,La.RADIANS).setParameterLength(1),Ga=Vi(La,La.DEGREES).setParameterLength(1),za=Vi(La,La.EXP).setParameterLength(1),Ha=Vi(La,La.EXP2).setParameterLength(1),$a=Vi(La,La.LOG).setParameterLength(1),Wa=Vi(La,La.LOG2).setParameterLength(1),ja=Vi(La,La.SQRT).setParameterLength(1),qa=Vi(La,La.INVERSE_SQRT).setParameterLength(1),Xa=Vi(La,La.FLOOR).setParameterLength(1),Ka=Vi(La,La.CEIL).setParameterLength(1),Ya=Vi(La,La.NORMALIZE).setParameterLength(1),Qa=Vi(La,La.FRACT).setParameterLength(1),Za=Vi(La,La.SIN).setParameterLength(1),Ja=Vi(La,La.COS).setParameterLength(1),eo=Vi(La,La.TAN).setParameterLength(1),to=Vi(La,La.ASIN).setParameterLength(1),ro=Vi(La,La.ACOS).setParameterLength(1),so=Vi(La,La.ATAN).setParameterLength(1,2),io=Vi(La,La.ABS).setParameterLength(1),no=Vi(La,La.SIGN).setParameterLength(1),ao=Vi(La,La.LENGTH).setParameterLength(1),oo=Vi(La,La.NEGATE).setParameterLength(1),uo=Vi(La,La.ONE_MINUS).setParameterLength(1),lo=Vi(La,La.DFDX).setParameterLength(1),co=Vi(La,La.DFDY).setParameterLength(1),ho=Vi(La,La.ROUND).setParameterLength(1),po=Vi(La,La.RECIPROCAL).setParameterLength(1),go=Vi(La,La.TRUNC).setParameterLength(1),mo=Vi(La,La.FWIDTH).setParameterLength(1),fo=Vi(La,La.TRANSPOSE).setParameterLength(1),yo=Vi(La,La.BITCAST).setParameterLength(2),bo=(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),ha(e,t)),xo=Vi(La,La.MIN).setParameterLength(2,1/0),To=Vi(La,La.MAX).setParameterLength(2,1/0),_o=Vi(La,La.STEP).setParameterLength(2),vo=Vi(La,La.REFLECT).setParameterLength(2),No=Vi(La,La.DISTANCE).setParameterLength(2),So=Vi(La,La.DIFFERENCE).setParameterLength(2),Eo=Vi(La,La.DOT).setParameterLength(2),wo=Vi(La,La.CROSS).setParameterLength(2),Ao=Vi(La,La.POW).setParameterLength(2),Ro=Vi(La,La.POW,2).setParameterLength(1),Co=Vi(La,La.POW,3).setParameterLength(1),Mo=Vi(La,La.POW,4).setParameterLength(1),Po=Vi(La,La.TRANSFORM_DIRECTION).setParameterLength(2),Bo=e=>la(no(e),Ao(io(e),1/3)),Lo=e=>Eo(e,e),Fo=Vi(La,La.MIX).setParameterLength(3),Io=(e,t=0,r=1)=>Fi(new La(La.CLAMP,Fi(e),Fi(t),Fi(r))),Do=e=>Io(e),Vo=Vi(La,La.REFRACT).setParameterLength(3),Uo=Vi(La,La.SMOOTHSTEP).setParameterLength(3),Oo=Vi(La,La.FACEFORWARD).setParameterLength(3),ko=ki((([e])=>{const t=Eo(e.xy,Yi(12.9898,78.233)),r=ca(t,Da);return Qa(Za(r).mul(43758.5453))})),Go=(e,t,r)=>Fo(t,r,e),zo=(e,t,r)=>Uo(t,r,e),Ho=(e,t)=>_o(t,e),$o=(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),so(e,t)),Wo=Oo,jo=qa;oi("all",Ua),oi("any",Oa),oi("equals",bo),oi("radians",ka),oi("degrees",Ga),oi("exp",za),oi("exp2",Ha),oi("log",$a),oi("log2",Wa),oi("sqrt",ja),oi("inverseSqrt",qa),oi("floor",Xa),oi("ceil",Ka),oi("normalize",Ya),oi("fract",Qa),oi("sin",Za),oi("cos",Ja),oi("tan",eo),oi("asin",to),oi("acos",ro),oi("atan",so),oi("abs",io),oi("sign",no),oi("length",ao),oi("lengthSq",Lo),oi("negate",oo),oi("oneMinus",uo),oi("dFdx",lo),oi("dFdy",co),oi("round",ho),oi("reciprocal",po),oi("trunc",go),oi("fwidth",mo),oi("atan2",$o),oi("min",xo),oi("max",To),oi("step",Ho),oi("reflect",vo),oi("distance",No),oi("dot",Eo),oi("cross",wo),oi("pow",Ao),oi("pow2",Ro),oi("pow3",Co),oi("pow4",Mo),oi("transformDirection",Po),oi("mix",Go),oi("clamp",Io),oi("refract",Vo),oi("smoothstep",zo),oi("faceForward",Oo),oi("difference",So),oi("saturate",Do),oi("cbrt",Bo),oi("transpose",fo),oi("rand",ko);class qo extends js{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}getNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),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.cache(),r=this.ifNode.cache(),s=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=r.context({nodeBlock:r}),n.elseNode=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?mn(r).build(e):"";s.nodeProperty=l;const d=i.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${d} ) {\n\n`).addFlowTab();let c=n.build(e,r);if(c&&(u?c=l+" = "+c+";":(c="return "+c+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Xo=Vi(qo).setParameterLength(2,3);oi("select",Xo);class Ko extends js{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const r=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e,t);return e.setContext(r),s}}const Yo=Vi(Ko).setParameterLength(1,2),Qo=(e,t)=>Yo(e,{label:t});oi("context",Yo),oi("label",Qo);class Zo extends js{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;s&&(a=e.isDeterministic(t),o=n?s:a);const u=e.getVectorType(this.getNodeType(e)),l=t.build(e,u),d=e.getVarFromNode(this,r,u,void 0,o),c=e.getPropertyName(d);let h=c;if(o)if(n)h=a?`const ${c}`:`let ${c}`;else{const r=e.getArrayCount(t);h=`const ${e.getVar(d.type,c,r)}`}return e.addLineFlowCode(`${h} = ${l}`,this),c}}const Jo=Vi(Zo),eu=(e,t=null)=>Jo(e,t).toStack(),tu=(e,t=null)=>Jo(e,t,!0).toStack();oi("toVar",eu),oi("toConst",tu);const ru=e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Jo(e));oi("temp",ru);class su extends js{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(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 iu=(e,t,r=null)=>Fi(new su(Fi(e),t,r));class nu extends js{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let 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=iu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.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,Ds.VERTEX);e.flowNodeFromShaderStage(Ds.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const au=Vi(nu).setParameterLength(1,2),ou=e=>au(e);oi("toVarying",au),oi("toVertexStage",ou),oi("varying",((...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),au(...e)))),oi("vertexStage",((...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),au(...e))));const uu=ki((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return Fo(t,r,s)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lu=ki((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return Fo(t,r,s)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),du="WorkingColorSpace";class cu extends Ks{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===du?c.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!==c.enabled&&r!==s&&r&&s?(c.getTransfer(r)===h&&(i=nn(uu(i.rgb),i.a)),c.getPrimaries(r)!==c.getPrimaries(s)&&(i=nn(dn(c._getMatrix(new n,r,s)).mul(i.rgb),i.a)),c.getTransfer(s)===h&&(i=nn(lu(i.rgb),i.a)),i):i}}const hu=(e,t)=>Fi(new cu(Fi(e),du,t)),pu=(e,t)=>Fi(new cu(Fi(e),t,du));oi("workingToColorSpace",hu),oi("colorSpaceToWorking",pu);let gu=class extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class mu extends js{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=Vs.OBJECT}setGroup(e){return this.group=e,this}element(e){return Fi(new gu(this,Fi(e)))}setNodeType(e){const t=Zn(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new fu(e,t,r));class bu extends Ks{static get type(){return"ToneMappingNode"}constructor(e,t=Tu,r=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Ts(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,r=this.toneMapping;if(r===p)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=nn(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const xu=(e,t,r)=>Fi(new bu(e,Fi(t),Fi(r))),Tu=yu("toneMappingExposure","float");oi("toneMapping",((e,t,r)=>xu(t,r,e)));class _u 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=g,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=this.value,s=e.getTypeLength(t),i=this.bufferStride||s,n=this.bufferOffset,a=!0===r.isInterleavedBuffer?r:new m(r,i),o=new f(a,s,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=au(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}}const vu=(e,t=null,r=0,s=0)=>Fi(new _u(e,t,r,s)),Nu=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setUsage(y),Su=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setInstanced(!0),Eu=(e,t=null,r=0,s=0)=>Nu(e,t,r,s).setInstanced(!0);oi("toAttribute",(e=>vu(e.value)));class wu extends js{static get type(){return"ComputeNode"}constructor(e,t,r=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=r,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Vs.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let r=t[0];for(let e=1;eFi(new wu(Fi(e),t,r));oi("compute",Au);class Ru extends js{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),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}}const Cu=(e,t)=>Fi(new Ru(Fi(e),t));oi("cache",Cu);class Mu extends js{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Pu=Vi(Mu).setParameterLength(2);oi("bypass",Pu);class Bu extends js{static get type(){return"RemapNode"}constructor(e,t,r,s=ji(0),i=ji(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=r,this.outLowNode=s,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:r,outLowNode:s,outHighNode:i,doClamp:n}=this;let a=e.sub(t).div(r.sub(t));return!0===n&&(a=a.clamp()),a.mul(i.sub(s)).add(s)}}const Lu=Vi(Bu,null,null,{doClamp:!1}).setParameterLength(3,5),Fu=Vi(Bu).setParameterLength(3,5);oi("remap",Lu),oi("remapClamp",Fu);class Iu extends js{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 Du=Vi(Iu).setParameterLength(1,2),Vu=e=>(e?Xo(e,Du("discard")):Du("discard")).toStack();oi("discard",Vu);class Uu extends Ks{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||p,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||b;return r!==p&&(t=t.toneMapping(r)),s!==b&&s!==c.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Ou=(e,t=null,r=null)=>Fi(new Uu(Fi(e),t,r));oi("renderOutput",Ou);class ku extends Ks{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e),s="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(s.length);let n="";return n+="// #"+s+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+r+" /* ... */\n",n+="// #"+i+"#\n",null!==t?t(e,n):console.log(n),r}}const Gu=(e,t=null)=>Fi(new ku(Fi(e),t));oi("debug",Gu);class zu extends js{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const 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 au(this).build(e,r)}return console.warn(`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 Hu=(e,t=null)=>Fi(new zu(e,t)),$u=(e=0)=>Hu("uv"+(e>0?e:""),"vec2");class Wu extends js{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 ju=Vi(Wu).setParameterLength(1,2);class qu extends Qn{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vs.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 Xu=Vi(qu).setParameterLength(1),Ku=new x;class Yu extends Qn{static get type(){return"TextureNode"}constructor(e=Ku,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.sampler=!0,this.updateMatrix=!1,this.updateType=Vs.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===T?"uvec4":this.value.type===_?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return $u(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Zn(this.value.matrix)),this._matrixUniform.mul(en(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Vs.OBJECT:Vs.NONE,this}setupUV(e,t){const r=this.value;return e.isFlipY()&&(r.image instanceof ImageBitmap&&!0===r.flipY||!0===r.isRenderTargetTexture||!0===r.isFramebufferTexture||!0===r.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this,e)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,r,s,i,n,a,o){const u=this.value;let l;return l=s?e.generateTextureLevel(u,t,r,s,n):i?e.generateTextureBias(u,t,r,i,n):o?e.generateTextureGrad(u,t,r,o,n):a?e.generateTextureCompare(u,t,r,a,n):!1===this.sampler?e.generateTextureLoad(u,t,r,n):e.generateTexture(u,t,r,n),l}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);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:r,biasNode:o,compareNode:u,depthNode:l,gradNode:d}=s,c=this.generateUV(e,t),h=r?r.build(e,"float"):null,p=o?o.build(e,"float"):null,g=l?l.build(e,"int"):null,m=u?u.build(e,"float"):null,f=d?[d[0].build(e,"vec2"),d[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);a=e.getPropertyName(y);const b=this.generateSnippet(e,i,c,h,p,g,m,f);e.addLineFlowCode(`${a} = ${b}`,this),n.snippet=b,n.propertyName=a}let o=a;const u=this.getNodeType(e);return e.needsToWorkingColorSpace(r)&&(o=pu(Du(o,u),r.colorSpace).setup(e).build(e,u)),e.format(o,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}blur(e){const t=this.clone();t.biasNode=Fi(e).mul(Xu(t)),t.referenceNode=this.getSelf();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===v||r.magFilter===v)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Fi(t)}level(e){const t=this.clone();return t.levelNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}size(e){return ju(this,e)}bias(e){const t=this.clone();return t.biasNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}compare(e){const t=this.clone();return t.compareNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}grad(e,t){const r=this.clone();return r.gradNode=[Fi(e),Fi(t)],r.referenceNode=this.getSelf(),Fi(r)}depth(e){const t=this.clone();return t.depthNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}const Qu=Vi(Yu).setParameterLength(1,4).setName("texture"),Zu=(e=Ku,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=Qu(e,t,r,s),i},Ju=(...e)=>Zu(...e).setSampler(!1);class el extends Qn{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const tl=(e,t,r)=>Fi(new el(e,t,r));class rl extends qs{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(),s=this.node.getPaddedType();return e.format(t,s,r)}}class sl extends el{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ms(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Vs.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rFi(new sl(e,t));const nl=Vi(class extends js{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),al=Zn(0,"uint").label("u_cameraIndex").setGroup(qn("cameraIndex")).toVarying("v_cameraIndex"),ol=Zn("float").label("cameraNear").setGroup(Kn).onRenderUpdate((({camera:e})=>e.near)),ul=Zn("float").label("cameraFar").setGroup(Kn).onRenderUpdate((({camera:e})=>e.far)),ll=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);t=il(r).setGroup(Kn).label("cameraProjectionMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrix")}else t=Zn("mat4").label("cameraProjectionMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),dl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);t=il(r).setGroup(Kn).label("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrixInverse")}else t=Zn("mat4").label("cameraProjectionMatrixInverse").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse));return t})).once()(),cl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);t=il(r).setGroup(Kn).label("cameraViewMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraViewMatrix")}else t=Zn("mat4").label("cameraViewMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),hl=Zn("mat4").label("cameraWorldMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorld)),pl=Zn("mat3").label("cameraNormalMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.normalMatrix)),gl=Zn(new r).label("cameraPosition").setGroup(Kn).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),ml=new N;class fl extends js{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Vs.OBJECT,this.uniformNode=new Qn(null)}getNodeType(){const e=this.scope;return e===fl.WORLD_MATRIX?"mat4":e===fl.POSITION||e===fl.VIEW_POSITION||e===fl.DIRECTION||e===fl.SCALE?"vec3":e===fl.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===fl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===fl.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===fl.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===fl.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===fl.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===fl.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),ml.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=ml.radius}}generate(e){const t=this.scope;return t===fl.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===fl.POSITION||t===fl.VIEW_POSITION||t===fl.DIRECTION||t===fl.SCALE?this.uniformNode.nodeType="vec3":t===fl.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}}fl.WORLD_MATRIX="worldMatrix",fl.POSITION="position",fl.SCALE="scale",fl.VIEW_POSITION="viewPosition",fl.DIRECTION="direction",fl.RADIUS="radius";const yl=Vi(fl,fl.DIRECTION).setParameterLength(1),bl=Vi(fl,fl.WORLD_MATRIX).setParameterLength(1),xl=Vi(fl,fl.POSITION).setParameterLength(1),Tl=Vi(fl,fl.SCALE).setParameterLength(1),_l=Vi(fl,fl.VIEW_POSITION).setParameterLength(1),vl=Vi(fl,fl.RADIUS).setParameterLength(1);class Nl extends fl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Sl=Ui(Nl,Nl.DIRECTION),El=Ui(Nl,Nl.WORLD_MATRIX),wl=Ui(Nl,Nl.POSITION),Al=Ui(Nl,Nl.SCALE),Rl=Ui(Nl,Nl.VIEW_POSITION),Cl=Ui(Nl,Nl.RADIUS),Ml=Zn(new n).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),Pl=Zn(new a).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),Bl=ki((e=>e.renderer.overrideNodes.modelViewMatrix||Ll)).once()().toVar("modelViewMatrix"),Ll=cl.mul(El),Fl=ki((e=>(e.context.isHighPrecisionModelViewMatrix=!0,Zn("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highpModelViewMatrix"),Il=ki((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Zn("mat3").onObjectUpdate((({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highpModelNormalViewMatrix"),Dl=Hu("position","vec3"),Vl=Dl.toVarying("positionLocal"),Ul=Dl.toVarying("positionPrevious"),Ol=ki((e=>El.mul(Vl).xyz.toVarying(e.getSubBuildProperty("v_positionWorld"))),"vec3").once(["POSITION"])(),kl=ki((()=>Vl.transformDirection(El).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection")),"vec3").once(["POSITION"])(),Gl=ki((e=>e.context.setupPositionView().toVarying("v_positionView")),"vec3").once(["POSITION"])(),zl=Gl.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Hl extends js{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{renderer:t,material:r}=e;return t.coordinateSystem===l&&r.side===S?"false":e.getFrontFacing()}}const $l=Ui(Hl),Wl=ji($l).mul(2).sub(1),jl=ki((([e],{material:t})=>{const r=t.side;return r===S?e=e.mul(-1):r===E&&(e=e.mul(Wl)),e})),ql=Hu("normal","vec3"),Xl=ki((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),en(0,1,0)):ql),"vec3").once()().toVar("normalLocal"),Kl=Gl.dFdx().cross(Gl.dFdy()).normalize().toVar("normalFlat"),Yl=ki((e=>{let t;return t=!0===e.material.flatShading?Kl:rd(Xl).toVarying("v_normalViewGeometry").normalize(),t}),"vec3").once()().toVar("normalViewGeometry"),Ql=ki((e=>{let t=Yl.transformDirection(cl);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")}),"vec3").once()(),Zl=ki((({subBuildFn:e,material:t,context:r})=>{let s;return"NORMAL"===e||"VERTEX"===e?(s=Yl,!0!==t.flatShading&&(s=jl(s))):s=r.setupNormal().context({getUV:null}),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Jl=Zl.transformDirection(cl).toVar("normalWorld"),ed=ki((({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Zl:t.setupClearcoatNormal().context({getUV:null}),r}),"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),td=ki((([e,t=El])=>{const r=dn(t),s=e.div(en(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz})),rd=ki((([e],t)=>{const r=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==r)return r.transformDirection(e);const s=Ml.mul(e);return cl.transformDirection(s)})),sd=ki((()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Zl))).once(["NORMAL","VERTEX"])(),id=ki((()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Jl))).once(["NORMAL","VERTEX"])(),nd=ki((()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),ed))).once(["NORMAL","VERTEX"])(),ad=new w,od=new a,ud=Zn(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),ld=Zn(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),dd=Zn(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?(ad.copy(r),od.makeRotationFromEuler(ad)):od.identity(),od})),cd=zl.negate().reflect(Zl),hd=zl.negate().refract(Zl,ud),pd=cd.transformDirection(cl).toVar("reflectVector"),gd=hd.transformDirection(cl).toVar("reflectVector"),md=new A;class fd extends Yu{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===R?pd:e.mapping===C?gd:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),en(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return e.renderer.coordinateSystem!==d&&r.isRenderTargetTexture||(t=en(t.x.negate(),t.yz)),dd.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const yd=Vi(fd).setParameterLength(1,4).setName("cubeTexture"),bd=(e=md,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=yd(e,t,r,s),i};class xd extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}}class Td extends js{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=Vs.OBJECT}element(e){return Fi(new xd(this,Fi(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?tl(null,e,this.count):Array.isArray(this.getValueFromReference())?il(null,e):"texture"===e?Zu(null):"cubeTexture"===e?bd(null):Zn(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new Td(e,t,r)),vd=(e,t,r,s)=>Fi(new Td(e,t,s,r));class Nd extends Td{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 Sd=(e,t,r=null)=>Fi(new Nd(e,t,r)),Ed=$u(),wd=Gl.dFdx(),Ad=Gl.dFdy(),Rd=Ed.dFdx(),Cd=Ed.dFdy(),Md=Zl,Pd=Ad.cross(Md),Bd=Md.cross(wd),Ld=Pd.mul(Rd.x).add(Bd.mul(Cd.x)),Fd=Pd.mul(Rd.y).add(Bd.mul(Cd.y)),Id=Ld.dot(Ld).max(Fd.dot(Fd)),Dd=Id.equal(0).select(0,Id.inverseSqrt()),Vd=Ld.mul(Dd).toVar("tangentViewFrame"),Ud=Fd.mul(Dd).toVar("bitangentViewFrame"),Od=ki((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Hu("tangent","vec4"))))(),kd=Od.xyz.toVar("tangentLocal"),Gd=ki((({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?Bl.mul(nn(kd,0)).xyz.toVarying("v_tangentView").normalize():Vd,!0!==r.flatShading&&(s=jl(s)),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),zd=Gd.transformDirection(cl).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),Hd=ki((([e,t],{subBuildFn:r,material:s})=>{let i=e.mul(Od.w).xyz;return"NORMAL"===r&&!0!==s.flatShading&&(i=i.toVarying(t)),i})).once(["NORMAL"]),$d=Hd(ql.cross(Od),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Wd=Hd(Xl.cross(kd),"v_bitangentLocal").normalize().toVar("bitangentLocal"),jd=ki((({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?Hd(Zl.cross(Gd),"v_bitangentView").normalize():Ud,!0!==r.flatShading&&(s=jl(s)),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),qd=Hd(Jl.cross(zd),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Xd=dn(Gd,jd,Zl).toVar("TBNViewMatrix"),Kd=zl.mul(Xd),Yd=ki((()=>{let e=Pn.cross(zl);return e=e.cross(Pn).normalize(),e=Fo(e,Zl,Cn.mul(xn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})).once()();class Qd extends Ks{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=M}setup({material:e}){const{normalMapType:t,scaleNode:r}=this;let s=this.node.mul(2).sub(1);if(null!==r){let t=r;!0===e.flatShading&&(t=jl(t)),s=en(s.xy.mul(t),s.z)}let i=null;return t===P?i=rd(s):t===M?i=Xd.mul(s).normalize():(console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=Zl),i}}const Zd=Vi(Qd).setParameterLength(1,2),Jd=ki((({textureNode:e,bumpScale:t})=>{const r=t=>e.cache().context({getUV:e=>t(e.uvNode||$u()),forceUVContext:!0}),s=ji(r((e=>e)));return Yi(ji(r((e=>e.add(e.dFdx())))).sub(s),ji(r((e=>e.add(e.dFdy())))).sub(s)).mul(t)})),ec=ki((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(Wl),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()}));class tc extends Ks{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=Jd({textureNode:this.textureNode,bumpScale:e});return ec({surf_pos:Gl,surf_norm:Zl,dHdxy:t})}}const rc=Vi(tc).setParameterLength(1,2),sc=new Map;class ic extends js{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=sc.get(e);return void 0===r&&(r=Sd(e,t),sc.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===ic.COLOR){const e=void 0!==t.color?this.getColor(r):en();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===ic.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===ic.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ji(1);else if(r===ic.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===ic.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===ic.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===ic.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===ic.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===ic.NORMAL)t.normalMap?(s=Zd(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType):s=t.bumpMap?rc(this.getTexture("bump").r,this.getFloat("bumpScale")):Zl;else if(r===ic.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===ic.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===ic.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Zd(this.getTexture(r),this.getCache(r+"Scale","vec2")):Zl;else if(r===ic.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===ic.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(.07,1)}else if(r===ic.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=ln(zc.x,zc.y,zc.y.negate(),zc.x).mul(e.rg.mul(2).sub(Yi(1)).normalize().mul(e.b))}else s=zc;else if(r===ic.IRIDESCENCE_THICKNESS){const e=_d("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=_d("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===ic.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===ic.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===ic.IOR)s=this.getFloat(r);else if(r===ic.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===ic.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===ic.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):ji(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}ic.ALPHA_TEST="alphaTest",ic.COLOR="color",ic.OPACITY="opacity",ic.SHININESS="shininess",ic.SPECULAR="specular",ic.SPECULAR_STRENGTH="specularStrength",ic.SPECULAR_INTENSITY="specularIntensity",ic.SPECULAR_COLOR="specularColor",ic.REFLECTIVITY="reflectivity",ic.ROUGHNESS="roughness",ic.METALNESS="metalness",ic.NORMAL="normal",ic.CLEARCOAT="clearcoat",ic.CLEARCOAT_ROUGHNESS="clearcoatRoughness",ic.CLEARCOAT_NORMAL="clearcoatNormal",ic.EMISSIVE="emissive",ic.ROTATION="rotation",ic.SHEEN="sheen",ic.SHEEN_ROUGHNESS="sheenRoughness",ic.ANISOTROPY="anisotropy",ic.IRIDESCENCE="iridescence",ic.IRIDESCENCE_IOR="iridescenceIOR",ic.IRIDESCENCE_THICKNESS="iridescenceThickness",ic.IOR="ior",ic.TRANSMISSION="transmission",ic.THICKNESS="thickness",ic.ATTENUATION_DISTANCE="attenuationDistance",ic.ATTENUATION_COLOR="attenuationColor",ic.LINE_SCALE="scale",ic.LINE_DASH_SIZE="dashSize",ic.LINE_GAP_SIZE="gapSize",ic.LINE_WIDTH="linewidth",ic.LINE_DASH_OFFSET="dashOffset",ic.POINT_SIZE="size",ic.DISPERSION="dispersion",ic.LIGHT_MAP="light",ic.AO="ao";const nc=Ui(ic,ic.ALPHA_TEST),ac=Ui(ic,ic.COLOR),oc=Ui(ic,ic.SHININESS),uc=Ui(ic,ic.EMISSIVE),lc=Ui(ic,ic.OPACITY),dc=Ui(ic,ic.SPECULAR),cc=Ui(ic,ic.SPECULAR_INTENSITY),hc=Ui(ic,ic.SPECULAR_COLOR),pc=Ui(ic,ic.SPECULAR_STRENGTH),gc=Ui(ic,ic.REFLECTIVITY),mc=Ui(ic,ic.ROUGHNESS),fc=Ui(ic,ic.METALNESS),yc=Ui(ic,ic.NORMAL),bc=Ui(ic,ic.CLEARCOAT),xc=Ui(ic,ic.CLEARCOAT_ROUGHNESS),Tc=Ui(ic,ic.CLEARCOAT_NORMAL),_c=Ui(ic,ic.ROTATION),vc=Ui(ic,ic.SHEEN),Nc=Ui(ic,ic.SHEEN_ROUGHNESS),Sc=Ui(ic,ic.ANISOTROPY),Ec=Ui(ic,ic.IRIDESCENCE),wc=Ui(ic,ic.IRIDESCENCE_IOR),Ac=Ui(ic,ic.IRIDESCENCE_THICKNESS),Rc=Ui(ic,ic.TRANSMISSION),Cc=Ui(ic,ic.THICKNESS),Mc=Ui(ic,ic.IOR),Pc=Ui(ic,ic.ATTENUATION_DISTANCE),Bc=Ui(ic,ic.ATTENUATION_COLOR),Lc=Ui(ic,ic.LINE_SCALE),Fc=Ui(ic,ic.LINE_DASH_SIZE),Ic=Ui(ic,ic.LINE_GAP_SIZE),Dc=Ui(ic,ic.LINE_WIDTH),Vc=Ui(ic,ic.LINE_DASH_OFFSET),Uc=Ui(ic,ic.POINT_SIZE),Oc=Ui(ic,ic.DISPERSION),kc=Ui(ic,ic.LIGHT_MAP),Gc=Ui(ic,ic.AO),zc=Zn(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))})),Hc=ki((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class $c extends js{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===$c.VERTEX)s=e.getVertexIndex();else if(r===$c.INSTANCE)s=e.getInstanceIndex();else if(r===$c.DRAW)s=e.getDrawIndex();else if(r===$c.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===$c.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==$c.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=au(this).build(e,t)}return i}}$c.VERTEX="vertex",$c.INSTANCE="instance",$c.SUBGROUP="subgroup",$c.INVOCATION_LOCAL="invocationLocal",$c.INVOCATION_SUBGROUP="invocationSubgroup",$c.DRAW="draw";const Wc=Ui($c,$c.VERTEX),jc=Ui($c,$c.INSTANCE),qc=Ui($c,$c.SUBGROUP),Xc=Ui($c,$c.INVOCATION_SUBGROUP),Kc=Ui($c,$c.INVOCATION_LOCAL),Yc=Ui($c,$c.DRAW);class Qc extends js{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=Vs.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:r,instanceColor:s}=this;let{instanceMatrixNode:i,instanceColorNode:n}=this;if(null===i){if(t<=1e3)i=tl(r.array,"mat4",Math.max(t,1)).element(jc);else{const e=new B(r.array,16,1);this.buffer=e;const t=r.usage===y?Eu:Su,s=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];i=cn(...s)}this.instanceMatrixNode=i}if(s&&null===n){const e=new L(s.array,3),t=s.usage===y?Eu:Su;this.bufferColor=e,n=en(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=i.mul(Vl).xyz;if(Vl.assign(a),e.hasGeometryAttribute("normal")){const e=td(Xl,i);Xl.assign(e)}null!==this.instanceColorNode&&fn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==y&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==y&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}const Zc=Vi(Qc).setParameterLength(2,3);class Jc extends Qc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const eh=Vi(Jc).setParameterLength(1);class th extends js{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=jc:this.batchingIdNode=Yc);const t=ki((([e])=>{const t=qi(ju(Ju(this.batchMesh._indirectTexture),0).x),r=qi(e).mod(t),s=qi(e).div(t);return Ju(this.batchMesh._indirectTexture,Qi(r,s)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(qi(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=qi(ju(Ju(s),0).x),n=ji(r).mul(4).toInt().toVar(),a=n.mod(i),o=n.div(i),u=cn(Ju(s,Qi(a,o)),Ju(s,Qi(a.add(1),o)),Ju(s,Qi(a.add(2),o)),Ju(s,Qi(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=ki((([e])=>{const t=qi(ju(Ju(l),0).x),r=e,s=r.mod(t),i=r.div(t);return Ju(l,Qi(s,i)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);fn("vec3","vBatchColor").assign(t)}const d=dn(u);Vl.assign(u.mul(Vl));const c=Xl.div(en(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Xl.assign(h),e.hasGeometryAttribute("tangent")&&kd.mulAssign(d)}}const rh=Vi(th).setParameterLength(1);class sh extends qs{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 ih=Vi(sh).setParameterLength(2);class nh extends el{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=Es(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=Os.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){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return ih(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Os.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=vu(this.value),this._varying=au(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(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 ah=(e,t=null,r=0)=>Fi(new nh(e,t,r)),oh=new WeakMap;class uh extends js{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Vs.OBJECT,this.skinIndexNode=Hu("skinIndex","uvec4"),this.skinWeightNode=Hu("skinWeight","vec4"),this.bindMatrixNode=_d("bindMatrix","mat4"),this.bindMatrixInverseNode=_d("bindMatrixInverse","mat4"),this.boneMatricesNode=vd("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Vl,this.toPositionNode=Vl,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=oa(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}getSkinnedNormal(e=this.boneMatricesNode,t=Xl){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);let d=oa(s.x.mul(a),s.y.mul(o),s.z.mul(u),s.w.mul(l));return d=n.mul(d).mul(i),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=vd("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Ul)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Bs(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Ul.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Xl.assign(t),e.hasGeometryAttribute("tangent")&&kd.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;oh.get(t)!==e.frameId&&(oh.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const lh=e=>Fi(new uh(e));class dh extends js{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;eNumber(u)?">=":"<")),a)n=`while ( ${u} )`;else{const r={start:o,end:u},s=r.start,i=r.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=h)switch(typeof h){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(d,h);break;case"string":a=l+" "+h;break;default:h.isNode?a=l+" "+p()+" "+h.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else h="int"===d||"uint"===d?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+h;n=`for ( ${e.getVar(d,l)+" = "+s}; ${l+" "+c+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tFi(new dh(Di(e,"int"))).toStack(),hh=()=>Du("break").toStack(),ph=new WeakMap,gh=new s,mh=ki((({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=qi(Wc).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ju(e,Qi(u,o)).depth(i).xyz.mul(t)}));class fh extends js{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Zn(1),this.updateType=Vs.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=ph.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 F(m,h,p,a);f.type=I,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=ji(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ju(this.mesh.morphTexture,Qi(qi(e).add(1),qi(jc))).r):t.assign(_d("morphTargetInfluences","float").element(e).toVar()),Hi(t.notEqual(0),(()=>{!0===s&&Vl.addAssign(mh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(0)})),!0===i&&Xl.addAssign(mh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(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 yh=Vi(fh).setParameterLength(1);class bh extends js{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class xh extends bh{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Th extends Ko{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:en().toVar("directDiffuse"),directSpecular:en().toVar("directSpecular"),indirectDiffuse:en().toVar("indirectDiffuse"),indirectSpecular:en().toVar("indirectSpecular")};return{radiance:en().toVar("radiance"),irradiance:en().toVar("irradiance"),iblIrradiance:en().toVar("iblIrradiance"),ambientOcclusion:ji(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 _h=Vi(Th);class vh extends bh{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Nh,Sh;class Eh extends js{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Eh.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Vs.NONE;return this.scope!==Eh.SIZE&&this.scope!==Eh.VIEWPORT||(e=Vs.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Eh.VIEWPORT?null!==t?Sh.copy(t.viewport):(e.getViewport(Sh),Sh.multiplyScalar(e.getPixelRatio())):null!==t?(Nh.width=t.width,Nh.height=t.height):e.getDrawingBufferSize(Nh)}setup(){const e=this.scope;let r=null;return r=e===Eh.SIZE?Zn(Nh||(Nh=new t)):e===Eh.VIEWPORT?Zn(Sh||(Sh=new s)):Yi(Rh.div(Ah)),r}generate(e){if(this.scope===Eh.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(Ah).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}Eh.COORDINATE="coordinate",Eh.VIEWPORT="viewport",Eh.SIZE="size",Eh.UV="uv";const wh=Ui(Eh,Eh.UV),Ah=Ui(Eh,Eh.SIZE),Rh=Ui(Eh,Eh.COORDINATE),Ch=Ui(Eh,Eh.VIEWPORT),Mh=Ch.zw,Ph=Rh.sub(Ch.xy),Bh=Ph.div(Mh),Lh=ki((()=>(console.warn('THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),Ah)),"vec2").once()(),Fh=new t;class Ih extends Yu{static get type(){return"ViewportTextureNode"}constructor(e=wh,t=null,r=null){null===r&&((r=new D).minFilter=V),super(r,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Vs.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Fh);const r=this.value;r.image.width===Fh.width&&r.image.height===Fh.height||(r.image.width=Fh.width,r.image.height=Fh.height,r.needsUpdate=!0);const s=r.generateMipmaps;r.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(r),r.generateMipmaps=s}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Dh=Vi(Ih).setParameterLength(0,3),Vh=Vi(Ih,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Uh=null;class Oh extends Ih{static get type(){return"ViewportDepthTextureNode"}constructor(e=wh,t=null){null===Uh&&(Uh=new U),super(e,t,Uh)}}const kh=Vi(Oh).setParameterLength(0,2);class Gh extends js{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===Gh.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Gh.DEPTH_BASE)null!==r&&(s=jh().assign(r));else if(t===Gh.DEPTH)s=e.isPerspectiveCamera?Hh(Gl.z,ol,ul):zh(Gl.z,ol,ul);else if(t===Gh.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=$h(r,ol,ul);s=zh(e,ol,ul)}else s=r;else s=zh(Gl.z,ol,ul);return s}}Gh.DEPTH_BASE="depthBase",Gh.DEPTH="depth",Gh.LINEAR_DEPTH="linearDepth";const zh=(e,t,r)=>e.add(t).div(t.sub(r)),Hh=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),$h=(e,t,r)=>t.mul(r).div(r.sub(t).mul(e).sub(r)),Wh=(e,t,r)=>{t=t.max(1e-6).toVar();const s=Wa(e.negate().div(t)),i=Wa(r.div(t));return s.div(i)},jh=Vi(Gh,Gh.DEPTH_BASE),qh=Ui(Gh,Gh.DEPTH),Xh=Vi(Gh,Gh.LINEAR_DEPTH).setParameterLength(0,1),Kh=Xh(kh());qh.assign=e=>jh(e);class Yh extends js{static get type(){return"ClippingNode"}constructor(e=Yh.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===Yh.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===Yh.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return ki((()=>{const r=ji().toVar("distanceToPlane"),s=ji().toVar("distanceToGradient"),i=ji(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=il(t);ch(n,(({i:t})=>{const n=e.element(t);r.assign(Gl.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Uo(s.negate(),s,r))}))}const a=e.length;if(a>0){const t=il(e),n=ji(1).toVar("intersectionClipOpacity");ch(a,(({i:e})=>{const i=t.element(e);r.assign(Gl.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Uo(s.negate(),s,r).oneMinus())})),i.mulAssign(n.oneMinus())}yn.a.mulAssign(i),yn.a.equal(0).discard()}))()}setupDefault(e,t){return ki((()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=il(t);ch(r,(({i:t})=>{const r=e.element(t);Gl.dot(r.xyz).greaterThan(r.w).discard()}))}const s=e.length;if(s>0){const t=il(e),r=Ki(!0).toVar("clipped");ch(s,(({i:e})=>{const s=t.element(e);r.assign(Gl.dot(s.xyz).greaterThan(s.w).and(r))})),r.discard()}}))()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),ki((()=>{const s=il(e),i=nl(t.getClipDistance());ch(r,(({i:e})=>{const t=s.element(e),r=Gl.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)}))}))()}}Yh.ALPHA_TO_COVERAGE="alphaToCoverage",Yh.DEFAULT="default",Yh.HARDWARE="hardware";const Qh=ki((([e])=>Qa(la(1e4,Za(la(17,e.x).add(la(.1,e.y)))).mul(oa(.1,io(Za(la(13,e.y).add(e.x)))))))),Zh=ki((([e])=>Qh(Yi(Qh(e.xy),e.z)))),Jh=ki((([e])=>{const t=To(ao(lo(e.xyz)),ao(co(e.xyz))),r=ji(1).div(ji(.05).mul(t)).toVar("pixScale"),s=Yi(Ha(Xa(Wa(r))),Ha(Ka(Wa(r)))),i=Yi(Zh(Xa(s.x.mul(e.xyz))),Zh(Xa(s.y.mul(e.xyz)))),n=Qa(Wa(r)),a=oa(la(n.oneMinus(),i.x),la(n,i.y)),o=xo(n,n.oneMinus()),u=en(a.mul(a).div(la(2,o).mul(ua(1,o))),a.sub(la(.5,o)).div(ua(1,o)),ua(1,ua(1,a).mul(ua(1,a)).div(la(2,o).mul(ua(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Io(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class ep extends zu{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 tp=(e=0)=>Fi(new ep(e)),rp=ki((([e,t])=>xo(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),sp=ki((([e,t])=>xo(e.div(t.oneMinus()),1))).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),ip=ki((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),np=ki((([e,t])=>Fo(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),_o(.5,e)))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),ap=ki((([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return nn(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"}]}),op=ki((([e])=>nn(e.rgb.mul(e.a),e.a)),{color:"vec4",return:"vec4"}),up=ki((([e])=>(Hi(e.a.equal(0),(()=>nn(0))),nn(e.rgb.div(e.a),e.a))),{color:"vec4",return:"vec4"});class lp extends O{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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+_s(this)}build(e){this.setup(e)}setupObserver(e){return new fs(e)}setup(e){e.context.setupNormal=()=>iu(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=iu(this.setupVertex(e),"VERTEX"),i=this.vertexNode||s;let n;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.add(a);const i=nn(s,yn.a).max(0);n=this.setupOutput(e,i),In.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&In.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=nn(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.samples;this.alphaToCoverage&&t>1?s=Fi(new Yh(Yh.ALPHA_TO_COVERAGE)):e.stack.add(Fi(new Yh))}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.add(Fi(new Yh(Yh.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?Wh(Gl.z,ol,ul):zh(Gl.z,ol,ul))}null!==s&&qh.assign(s).toStack()}setupPositionView(){return Bl.mul(Vl).xyz}setupModelViewProjection(){return ll.mul(Gl)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Hc}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&yh(t).toStack(),!0===t.isSkinnedMesh&&lh(t).toStack(),this.displacementMap){const e=Sd("displacementMap","texture"),t=Sd("displacementScale","float"),r=Sd("displacementBias","float");Vl.addAssign(Xl.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&rh(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&eh(t).toStack(),null!==this.positionNode&&Vl.assign(iu(this.positionNode,"POSITION","vec3")),Vl}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&Ki(this.maskNode).not().discard();let r=this.colorNode?nn(this.colorNode):ac;if(!0===this.vertexColors&&t.hasAttribute("color")&&(r=r.mul(tp())),e.instanceColor){r=fn("vec3","vInstanceColor").mul(r)}if(e.isBatchedMesh&&e._colorsTexture){r=fn("vec3","vBatchColor").mul(r)}yn.assign(r);const s=this.opacityNode?ji(this.opacityNode):lc;yn.a.assign(yn.a.mul(s));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?ji(this.alphaTestNode):nc,yn.a.lessThanEqual(i).discard()),!0===this.alphaHash&&yn.a.lessThan(Jh(Vl)).discard();!1===this.transparent&&this.blending===k&&!1===this.alphaToCoverage?yn.a.assign(1):null===i&&yn.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?en(0):yn.rgb}setupNormal(){return this.normalNode?en(this.normalNode):yc}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Sd("envMap","cubeTexture"):Sd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new vh(kc)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);if(s&&s.isLightingNode&&t.push(s),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Gc;t.push(new xh(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}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=_h(n,t,r,s)}else null!==r&&(a=en(null!==s?Fo(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(bn.assign(en(i||uc)),a=a.add(bn)),a}setupFog(e,t){const r=e.fogNode;return r&&(In.assign(t),t=nn(r)),t}setupPremultipliedAlpha(e,t){return op(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=O.prototype.toJSON.call(this,e),s=vs(this);r.inputNodes={};for(const{property:t,childNode:i}of s)r.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=i(e.textures),s=i(e.images),n=i(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const dp=new G;class cp extends lp{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(dp),this.setValues(e)}}const hp=new z;class pp extends lp{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(hp),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ji(this.offsetNode):Vc,t=this.dashScaleNode?ji(this.dashScaleNode):Lc,r=this.dashSizeNode?ji(this.dashSizeNode):Fc,s=this.gapSizeNode?ji(this.gapSizeNode):Ic;Dn.assign(r),Vn.assign(s);const i=au(Hu("lineDistance").mul(t));(e?i.add(e):i).mod(Dn.add(Vn)).greaterThan(Dn).discard()}}let gp=null;class mp extends Ih{static get type(){return"ViewportSharedTextureNode"}constructor(e=wh,t=null){null===gp&&(gp=new D),super(e,t,gp)}updateReference(){return this}}const fp=Vi(mp).setParameterLength(0,2),yp=new z;class bp extends lp{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(yp),this.useColor=e.vertexColors,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=H,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.useColor,i=this._useDash,n=this._useWorldUnits,a=ki((({start:e,end:t})=>{const r=ll.element(2).element(2),s=ll.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return nn(Fo(e.xyz,t.xyz,s),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=ki((()=>{const e=Hu("instanceStart"),t=Hu("instanceEnd"),r=nn(Bl.mul(nn(e,1))).toVar("start"),s=nn(Bl.mul(nn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?ji(this.dashScaleNode):Lc,t=this.offsetNode?ji(this.offsetNode):Vc,r=Hu("instanceDistanceStart"),s=Hu("instanceDistanceEnd");let i=Dl.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),fn("float","lineDistance").assign(i)}n&&(fn("vec3","worldStart").assign(r.xyz),fn("vec3","worldEnd").assign(s.xyz));const o=Ch.z.div(Ch.w),u=ll.element(2).element(3).equal(-1);Hi(u,(()=>{Hi(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=ll.mul(r),d=ll.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=nn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=Fo(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=fn("vec4","worldPos");o.assign(Dl.y.lessThan(.5).select(r,s));const u=Dc.mul(.5);o.addAssign(nn(Dl.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(nn(Dl.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(nn(a.mul(u),0)),Hi(Dl.y.greaterThan(1).or(Dl.y.lessThan(0)),(()=>{o.subAssign(nn(a.mul(2).mul(u),0))}))),g.assign(ll.mul(o));const l=en().toVar();l.assign(Dl.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=Yi(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(Dl.x.lessThan(0).select(e.negate(),e)),Hi(Dl.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(Dl.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(Dc)),e.assign(e.div(Ch.w)),g.assign(Dl.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(nn(e,0,0)))}return g}))();const o=ki((({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 Yi(h,p)}));if(this.colorNode=ki((()=>{const e=$u();if(i){const t=this.dashSizeNode?ji(this.dashSizeNode):Fc,r=this.gapSizeNode?ji(this.gapSizeNode):Ic;Dn.assign(t),Vn.assign(r);const s=fn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(Dn.add(Vn)).greaterThan(Dn).discard()}const a=ji(1).toVar("alpha");if(n){const e=fn("vec3","worldStart"),s=fn("vec3","worldEnd"),n=fn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:en(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(Dc);if(!i)if(r&&t.samples>1){const e=h.fwidth();a.assign(Uo(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.samples>1){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=ji(s.fwidth()).toVar("dlen");Hi(e.y.abs().greaterThan(1),(()=>{a.assign(Uo(i.oneMinus(),i.add(1),s).oneMinus())}))}else Hi(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=Hu("instanceColorStart"),t=Hu("instanceColorEnd");u=Dl.y.lessThan(.5).select(e,t).mul(ac)}else u=ac;return nn(u,a)}))(),this.transparent){const e=this.opacityNode?ji(this.opacityNode):lc;this.outputNode=nn(this.colorNode.rgb.mul(e).add(fp().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)}}const xp=e=>Fi(e).mul(.5).add(.5),Tp=new $;class _p extends lp{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Tp),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ji(this.opacityNode):lc;yn.assign(pu(nn(xp(Zl),e),W))}}const vp=ki((([e=kl])=>{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 Yi(t,r)}));class Np extends j{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 q(5,5,5),n=vp(kl),a=new lp;a.colorNode=Zu(t,n,0),a.side=S,a.blending=H;const o=new X(i,a),u=new K;u.add(o),t.minFilter===V&&(t.minFilter=Y);const l=new Q(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.currentGenerateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}}const Sp=new WeakMap;class Ep extends Ks{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=bd(null);const t=new A;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Vs.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===Z||r===J){if(Sp.has(e)){const t=Sp.get(e);Ap(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Np(r.height);s.fromEquirectangularTexture(t,e),Ap(s.texture,e.mapping),this._cubeTexture=s.texture,Sp.set(e,s.texture),e.addEventListener("dispose",wp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function wp(e){const t=e.target;t.removeEventListener("dispose",wp);const r=Sp.get(t);void 0!==r&&(Sp.delete(t),r.dispose())}function Ap(e,t){t===Z?e.mapping=R:t===J&&(e.mapping=C)}const Rp=Vi(Ep).setParameterLength(1);class Cp extends bh{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Rp(this.envNode)}}class Mp extends bh{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ji(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Pp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Bp extends Pp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(nn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(nn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(yn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case re:s.rgb.assign(Fo(s.rgb,s.rgb.mul(i.rgb),pc.mul(gc)));break;case te:s.rgb.assign(Fo(s.rgb,i.rgb,pc.mul(gc)));break;case ee:s.rgb.addAssign(i.rgb.mul(pc.mul(gc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Lp=new se;class Fp extends lp{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Lp),this.setValues(e)}setupNormal(){return jl(Yl)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Cp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Mp(kc)),t}setupOutgoingLight(){return yn.rgb}setupLightingModel(){return new Bp}}const Ip=ki((({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))})),Dp=ki((e=>e.diffuseColor.mul(1/Math.PI))),Vp=ki((({dotNH:e})=>Fn.mul(ji(.5)).add(1).mul(ji(1/Math.PI)).mul(e.pow(Fn)))),Up=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(t).clamp(),s=zl.dot(t).clamp(),i=Ip({f0:Bn,f90:1,dotVH:s}),n=ji(.25),a=Vp({dotNH:r});return i.mul(n).mul(a)}));class Op extends Bp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Dp({diffuseColor:yn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(Up({lightDirection:e})).mul(pc))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Dp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const kp=new ie;class Gp extends lp{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(kp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Cp(t):null}setupLightingModel(){return new Op(!1)}}const zp=new ne;class Hp extends lp{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(zp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Cp(t):null}setupLightingModel(){return new Op}setupVariants(){const e=(this.shininessNode?ji(this.shininessNode):oc).max(1e-4);Fn.assign(e);const t=this.specularNode||dc;Bn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const $p=ki((e=>{if(!1===e.geometry.hasAttribute("normal"))return ji(0);const t=Yl.dFdx().abs().max(Yl.dFdy().abs());return t.x.max(t.y).max(t.z)})),Wp=ki((e=>{const{roughness:t}=e,r=$p();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s})),jp=ki((({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(Fa))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),qp=ki((({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(en(e.mul(r),t.mul(s),a).length()),l=a.mul(en(e.mul(i),t.mul(n),o).length());return da(.5,u.add(l)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Xp=ki((({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"}]}),Kp=ji(1/Math.PI),Yp=ki((({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=en(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return Kp.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"}]}),Qp=ki((({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Zl,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(zl).normalize(),d=n.dot(e).clamp(),c=n.dot(zl).clamp(),h=n.dot(l).clamp(),p=zl.dot(l).clamp();let g,m,f=Ip({f0:t,f90:r,dotVH:p});if(Pi(a)&&(f=En.mix(f,i)),Pi(o)){const t=Mn.dot(e),r=Mn.dot(zl),s=Mn.dot(l),i=Pn.dot(e),n=Pn.dot(zl),a=Pn.dot(l);g=qp({alphaT:Rn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=Yp({alphaT:Rn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=jp({alpha:u,dotNL:d,dotNV:c}),m=Xp({alpha:u,dotNH:h});return f.mul(g).mul(m)})),Zp=ki((({roughness:e,dotNV:t})=>{const r=nn(-1,-.0275,-.572,.022),s=nn(1,.0425,1.04,-.04),i=e.mul(r).add(s),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return Yi(-1.04,1.04).mul(n).add(i.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),Jp=ki((e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=Zp({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))})),eg=ki((({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(en(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"}]}),tg=ki((({roughness:e,dotNH:t})=>{const r=e.pow2(),s=ji(1).div(r),i=t.pow2().oneMinus().max(.0078125);return ji(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"}]}),rg=ki((({dotNV:e,dotNL:t})=>ji(1).div(ji(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),sg=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(e).clamp(),s=Zl.dot(zl).clamp(),i=Zl.dot(t).clamp(),n=tg({roughness:Sn,dotNH:i}),a=rg({dotNV:s,dotNL:r});return Nn.mul(n).mul(a)})),ig=ki((({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=Yi(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"}]}),ng=ki((({f:e})=>{const t=e.length();return To(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),ag=ki((({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,To(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"}]}),og=ki((({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=en().toVar();return Hi(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(dn(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=en(0).toVar();f.addAssign(ag({v1:h,v2:p})),f.addAssign(ag({v1:p,v2:g})),f.addAssign(ag({v1:g,v2:m})),f.addAssign(ag({v1:m,v2:h})),c.assign(en(ng({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"}]}),ug=ki((({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=en().toVar();return Hi(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=en(0).toVar();d.addAssign(ag({v1:n,v2:a})),d.addAssign(ag({v1:a,v2:o})),d.addAssign(ag({v1:o,v2:l})),d.addAssign(ag({v1:l,v2:n})),u.assign(en(ng({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"}]}),lg=1/6,dg=e=>la(lg,la(e,la(e,e.negate().add(3)).sub(3)).add(1)),cg=e=>la(lg,la(e,la(e,la(3,e).sub(6))).add(4)),hg=e=>la(lg,la(e,la(e,la(-3,e).add(3)).add(3)).add(1)),pg=e=>la(lg,Ao(e,3)),gg=e=>dg(e).add(cg(e)),mg=e=>hg(e).add(pg(e)),fg=e=>oa(-1,cg(e).div(dg(e).add(cg(e)))),yg=e=>oa(1,pg(e).div(hg(e).add(pg(e)))),bg=(e,t,r)=>{const s=e.uvNode,i=la(s,t.zw).add(.5),n=Xa(i),a=Qa(i),o=gg(a.x),u=mg(a.x),l=fg(a.x),d=yg(a.x),c=fg(a.y),h=yg(a.y),p=Yi(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Yi(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=Yi(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Yi(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=gg(a.y).mul(oa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=mg(a.y).mul(oa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},xg=ki((([e,t])=>{const r=Yi(e.size(qi(t))),s=Yi(e.size(qi(t.add(1)))),i=da(1,r),n=da(1,s),a=bg(e,nn(i,r),Xa(t)),o=bg(e,nn(n,s),Ka(t));return Qa(t).mix(a,o)})),Tg=ki((([e,t])=>{const r=t.mul(Xu(e));return xg(e,r)})),_g=ki((([e,t,r,s,i])=>{const n=en(Vo(t.negate(),Ya(e),da(1,s))),a=en(ao(i[0].xyz),ao(i[1].xyz),ao(i[2].xyz));return Ya(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"}]}),vg=ki((([e,t])=>e.mul(Io(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Ng=Vh(),Sg=Vh(),Eg=ki((([e,t,r],{material:s})=>{const i=(s.side===S?Ng:Sg).sample(e),n=Wa(Ah.x).mul(vg(t,r));return xg(i,n)})),wg=ki((([e,t,r])=>(Hi(r.notEqual(0),(()=>{const s=$a(t).negate().div(r);return za(s.negate().mul(e))})),en(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Ag=ki((([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=nn().toVar(),f=en().toVar();const i=d.sub(1).mul(g.mul(.025)),n=en(d.sub(i),d,d.add(i));ch({start:0,end:3},(({i:i})=>{const d=n.element(i),g=_g(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(nn(y,1))),x=Yi(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Yi(x.x,x.y.oneMinus()));const T=Eg(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(wg(ao(g),h,p).element(i)))})),m.a.divAssign(3)}else{const i=_g(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(nn(n,1))),y=Yi(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Yi(y.x,y.y.oneMinus())),m=Eg(y,r,d),f=s.mul(wg(ao(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=en(Jp({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return nn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())})),Rg=dn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Cg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Mg=ki((({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=Fo(e,t,Uo(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();Hi(a.lessThan(0),(()=>en(1)));const o=a.sqrt(),u=Cg(n,e),l=Ip({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=ji(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return en(1).add(t).div(en(1).sub(t))})(i.clamp(0,.9999)),g=Cg(p,n.toVec3()),m=Ip({f0:g,f90:1,dotVH:o}),f=en(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=en(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(en(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return ch({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=en(54856e-17,44201e-17,52481e-17),i=en(1681e3,1795300,2208400),n=en(43278e5,93046e5,66121e5),a=ji(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=en(o.x.add(a),o.y,o.z).div(1.0685e-7),Rg.mul(o)})(ji(e).mul(y),ji(e).mul(b)).mul(2);v.addAssign(N.mul(t))})),v.max(en(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"}]}),Pg=ki((({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.pow2(),n=Xo(r.lessThan(.25),ji(-339.2).mul(i).add(ji(161.4).mul(r)).sub(25.9),ji(-8.48).mul(i).add(ji(14.3).mul(r)).sub(9.95)),a=Xo(r.lessThan(.25),ji(44).mul(i).sub(ji(23.7).mul(r)).add(3.26),ji(1.97).mul(i).sub(ji(3.27).mul(r)).add(.72));return Xo(r.lessThan(.25),0,ji(.1).mul(r).sub(.025)).add(n.mul(s).add(a).exp()).mul(1/Math.PI).saturate()})),Bg=en(.04),Lg=ji(1);class Fg extends Pp{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}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=en().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=en().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=en().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=en().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=en().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Zl.dot(zl).clamp();this.iridescenceFresnel=Mg({outsideIOR:ji(1),eta2:wn,cosTheta1:e,thinFilmThickness:An,baseF0:Bn}),this.iridescenceF0=eg({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Ol,r=gl.sub(Ol).normalize(),s=Jl,i=e.context;i.backdrop=Ag(s,r,xn,yn,Bn,Ln,t,El,cl,ll,On,Gn,Hn,zn,this.dispersion?$n:null),i.backdropAlpha=kn,yn.a.mulAssign(Fo(1,i.backdrop.a,kn))}super.start(e)}computeMultiscattering(e,t,r){const s=Zl.dot(zl).clamp(),i=Zp({roughness:xn,dotNV:s}),n=(this.iridescenceF0?En.mix(Bn,this.iridescenceF0):Bn).mul(i.x).add(r.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=Bn.add(Bn.oneMinus().mul(.047619)),u=n.mul(o).div(a.mul(o).oneMinus());e.addAssign(n),t.addAssign(u.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(s.mul(sg({lightDirection:e}))),!0===this.clearcoat){const r=ed.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(Qp({lightDirection:e,f0:Bg,f90:Lg,roughness:vn,normalView:ed})))}r.directDiffuse.addAssign(s.mul(Dp({diffuseColor:yn.rgb}))),r.directSpecular.addAssign(s.mul(Qp({lightDirection:e,f0:Bn,f90:1,roughness:xn,iridescence:this.iridescence,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=Zl,h=zl,p=Gl.toVar(),g=ig({N:c,V:h,roughness:xn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=dn(en(m.x,0,m.y),en(0,1,0),en(m.z,0,m.w)).toVar(),b=Bn.mul(f.x).add(Bn.oneMinus().mul(f.y)).toVar();i.directSpecular.addAssign(e.mul(b).mul(og({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(yn).mul(og({N:c,V:h,P:p,mInv:dn(1,0,0,0,1,0,0,0,1),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;r.indirectDiffuse.addAssign(t.mul(Dp({diffuseColor:yn})))}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Nn,Pg({normal:Zl,viewDir:zl,roughness:Sn}))),!0===this.clearcoat){const e=ed.dot(zl).clamp(),t=Jp({dotNV:e,specularColor:Bg,specularF90:Lg,roughness:vn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=en().toVar("singleScattering"),n=en().toVar("multiScattering"),a=r.mul(1/Math.PI);this.computeMultiscattering(i,n,Ln);const o=i.add(n),u=yn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(t.mul(i)),s.indirectSpecular.addAssign(n.mul(a)),s.indirectDiffuse.addAssign(u.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Zl.dot(zl).clamp().add(t),i=xn.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=ed.dot(zl).clamp(),r=Ip({dotVH:e,f0:Bg,f90:Lg}),s=t.mul(_n.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(_n));t.assign(s)}if(!0===this.sheen){const e=Nn.r.max(Nn.g).max(Nn.b).mul(.157).oneMinus(),r=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(r)}}}const Ig=ji(1),Dg=ji(-2),Vg=ji(.8),Ug=ji(-1),Og=ji(.4),kg=ji(2),Gg=ji(.305),zg=ji(3),Hg=ji(.21),$g=ji(4),Wg=ji(4),jg=ji(16),qg=ki((([e])=>{const t=en(io(e)).toVar(),r=ji(-1).toVar();return Hi(t.x.greaterThan(t.z),(()=>{Hi(t.x.greaterThan(t.y),(()=>{r.assign(Xo(e.x.greaterThan(0),0,3))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})).Else((()=>{Hi(t.z.greaterThan(t.y),(()=>{r.assign(Xo(e.z.greaterThan(0),2,5))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})),r})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Xg=ki((([e,t])=>{const r=Yi().toVar();return Hi(t.equal(0),(()=>{r.assign(Yi(e.z,e.y).div(io(e.x)))})).ElseIf(t.equal(1),(()=>{r.assign(Yi(e.x.negate(),e.z.negate()).div(io(e.y)))})).ElseIf(t.equal(2),(()=>{r.assign(Yi(e.x.negate(),e.y).div(io(e.z)))})).ElseIf(t.equal(3),(()=>{r.assign(Yi(e.z.negate(),e.y).div(io(e.x)))})).ElseIf(t.equal(4),(()=>{r.assign(Yi(e.x.negate(),e.z).div(io(e.y)))})).Else((()=>{r.assign(Yi(e.x,e.y).div(io(e.z)))})),la(.5,r.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Kg=ki((([e])=>{const t=ji(0).toVar();return Hi(e.greaterThanEqual(Vg),(()=>{t.assign(Ig.sub(e).mul(Ug.sub(Dg)).div(Ig.sub(Vg)).add(Dg))})).ElseIf(e.greaterThanEqual(Og),(()=>{t.assign(Vg.sub(e).mul(kg.sub(Ug)).div(Vg.sub(Og)).add(Ug))})).ElseIf(e.greaterThanEqual(Gg),(()=>{t.assign(Og.sub(e).mul(zg.sub(kg)).div(Og.sub(Gg)).add(kg))})).ElseIf(e.greaterThanEqual(Hg),(()=>{t.assign(Gg.sub(e).mul($g.sub(zg)).div(Gg.sub(Hg)).add(zg))})).Else((()=>{t.assign(ji(-2).mul(Wa(la(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Yg=ki((([e,t])=>{const r=e.toVar();r.assign(la(2,r).sub(1));const s=en(r,1).toVar();return Hi(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"}]}),Qg=ki((([e,t,r,s,i,n])=>{const a=ji(r),o=en(t),u=Io(Kg(a),Dg,n),l=Qa(u),d=Xa(u),c=en(Zg(e,o,d,s,i,n)).toVar();return Hi(l.notEqual(0),(()=>{const t=en(Zg(e,o,d.add(1),s,i,n)).toVar();c.assign(Fo(c,t,l))})),c})),Zg=ki((([e,t,r,s,i,n])=>{const a=ji(r).toVar(),o=en(t),u=ji(qg(o)).toVar(),l=ji(To(Wg.sub(a),0)).toVar();a.assign(To(a,Wg));const d=ji(Ha(a)).toVar(),c=Yi(Xg(o,u).mul(d.sub(2)).add(1)).toVar();return Hi(u.greaterThan(2),(()=>{c.y.addAssign(d),u.subAssign(3)})),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(la(3,jg))),c.y.addAssign(la(4,Ha(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(Yi(),Yi())})),Jg=ki((({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Ja(s),l=r.mul(u).add(i.cross(r).mul(Za(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return Zg(e,l,t,n,a,o)})),em=ki((({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=en(Xo(t,r,wo(r,s))).toVar();Hi(h.equal(en(0)),(()=>{h.assign(en(s.z,0,s.x.negate()))})),h.assign(Ya(h));const p=en().toVar();return p.addAssign(i.element(0).mul(Jg({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),ch({start:qi(1),end:e},(({i:e})=>{Hi(e.greaterThanEqual(n),(()=>{hh()}));const t=ji(a.mul(ji(e))).toVar();p.addAssign(i.element(e).mul(Jg({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(Jg({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))})),nn(p,1)})),tm=[.125,.215,.35,.446,.526,.582],rm=20,sm=new ae(-1,1,1,-1,0,1),im=new oe(90,1),nm=new e;let am=null,om=0,um=0;const lm=(1+Math.sqrt(5))/2,dm=1/lm,cm=[new r(-lm,dm,0),new r(lm,dm,0),new r(-dm,0,lm),new r(dm,0,lm),new r(0,lm,-dm),new r(0,lm,dm),new r(-1,1,-1),new r(1,1,-1),new r(-1,1,1),new r(1,1,1)],hm=new r,pm=new WeakMap,gm=[3,1,5,0,4,2],mm=Yg($u(),Hu("faceIndex")).normalize(),fm=en(mm.x,mm.y,mm.z);class ym{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=hm,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}am=this._renderer.getRenderTarget(),om=this._renderer.getActiveCubeFace(),um=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!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=_m(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=vm(),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===R||e.mapping===C?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?u=tm[o-e+4-1]:0===o&&(u=0),s.push(u);const l=1/(a-2),d=-l,c=1+l,h=[d,d,c,d,c,c,d,d,c,c,d,c],p=6,g=6,m=3,f=2,y=1,b=new Float32Array(m*g*p),x=new Float32Array(f*g*p),T=new Float32Array(y*g*p);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=gm[e];b.set(s,m*g*i),x.set(h,f*g*i);const n=[i,i,i,i,i,i];T.set(n,y*g*i)}const _=new pe;_.setAttribute("position",new ge(b,m)),_.setAttribute("uv",new ge(x,f)),_.setAttribute("faceIndex",new ge(T,y)),t.push(_),i.push(new X(_,null)),n>4&&n--}return{lodPlanes:t,sizeLods:r,sigmas:s,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,s){const i=il(new Array(rm).fill(0)),n=Zn(new r(0,1,0)),a=Zn(0),o=ji(rm),u=Zn(0),l=Zn(1),d=Zu(null),c=Zn(0),h=ji(1/t),p=ji(1/s),g=ji(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:fm,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Tm("blur");return f.fragmentNode=em({...m,latitudinal:u.equal(1)}),pm.set(f,m),f}(t,e.width,e.height)}}async _compileMaterial(e){const t=new X(this._lodPlanes[0],e);await this._renderer.compile(t,sm)}_sceneToCubeUV(e,t,r,s,i){const n=im;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(nm),u.autoClear=!1;let d=this._backgroundBox;if(null===d){const e=new se({name:"PMREM.Background",side:S,depthWrite:!1,depthTest:!1});d=new X(new q,e)}let c=!1;const h=e.background;h?h.isColor&&(d.material.color.copy(h),e.background=null,c=!0):(d.material.color.copy(nm),c=!0),u.setRenderTarget(s),u.clear(),c&&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;xm(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=h}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===R||e.mapping===C;s?null===this._cubemapMaterial&&(this._cubemapMaterial=_m(e)):null===this._equirectMaterial&&(this._equirectMaterial=vm(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;xm(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,sm)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let t=1;trm&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${g} samples when the maximum is set to 20`);const m=[];let f=0;for(let e=0;ey-4?s-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(l,sm)}}function bm(e,t){const r=new ue(e,t,{magFilter:Y,minFilter:Y,generateMipmaps:!1,type:ce,format:de,colorSpace:le});return r.texture.mapping=he,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function xm(e,t,r,s,i){e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i)}function Tm(e){const t=new lp;return t.depthTest=!1,t.depthWrite=!1,t.blending=H,t.name=`PMREM_${e}`,t}function _m(e){const t=Tm("cubemap");return t.fragmentNode=bd(e,fm),t}function vm(e){const t=Tm("equirect");return t.fragmentNode=Zu(e,vp(fm),0),t}const Nm=new WeakMap;function Sm(e,t,r){const s=function(e){let t=Nm.get(e);void 0===t&&(t=new WeakMap,Nm.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 Em extends Ks{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 x;s.isRenderTargetTexture=!0,this._texture=Zu(s),this._width=Zn(0),this._height=Zn(0),this._maxMip=Zn(0),this.updateBeforeType=Vs.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:Sm(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ym(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=dd.mul(en(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),Qg(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const wm=Vi(Em).setParameterLength(1,3),Am=new WeakMap;class Rm extends bh{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 e=r.isTextureNode?r.value:t[r.property];let s=Am.get(e);void 0===s&&(s=wm(e),Am.set(e,s)),r=s}const s=!0===t.useAnisotropy||t.anisotropy>0?Yd:Zl,i=r.context(Cm(xn,s)).mul(ld),n=r.context(Mm(Jl)).mul(Math.PI).mul(ld),a=Cu(i),o=Cu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(Cm(vn,ed)).mul(ld),t=Cu(e);u.addAssign(t)}}}const Cm=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=zl.negate().reflect(t),r=e.mul(e).mix(r,t).normalize(),r=r.transformDirection(cl)),r),getTextureLevel:()=>e}},Mm=e=>({getUV:()=>e,getTextureLevel:()=>ji(1)}),Pm=new me;class Bm extends lp{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(Pm),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Rm(t):null}setupLightingModel(){return new Fg}setupSpecular(){const e=Fo(en(.04),yn.rgb,Tn);Bn.assign(e),Ln.assign(1)}setupVariants(){const e=this.metalnessNode?ji(this.metalnessNode):fc;Tn.assign(e);let t=this.roughnessNode?ji(this.roughnessNode):mc;t=Wp({roughness:t}),xn.assign(t),this.setupSpecular(),yn.assign(nn(yn.rgb.mul(e.oneMinus()),yn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Lm=new fe;class Fm extends Bm{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(Lm),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?ji(this.iorNode):Mc;On.assign(e),Bn.assign(Fo(xo(Ro(On.sub(1).div(On.add(1))).mul(hc),en(1)).mul(cc),yn.rgb,Tn)),Ln.assign(Fo(cc,1,Tn))}setupLightingModel(){return new Fg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ji(this.clearcoatNode):bc,t=this.clearcoatRoughnessNode?ji(this.clearcoatRoughnessNode):xc;_n.assign(e),vn.assign(Wp({roughness:t}))}if(this.useSheen){const e=this.sheenNode?en(this.sheenNode):vc,t=this.sheenRoughnessNode?ji(this.sheenRoughnessNode):Nc;Nn.assign(e),Sn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ji(this.iridescenceNode):Ec,t=this.iridescenceIORNode?ji(this.iridescenceIORNode):wc,r=this.iridescenceThicknessNode?ji(this.iridescenceThicknessNode):Ac;En.assign(e),wn.assign(t),An.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?Yi(this.anisotropyNode):Sc).toVar();Cn.assign(e.length()),Hi(Cn.equal(0),(()=>{e.assign(Yi(1,0))})).Else((()=>{e.divAssign(Yi(Cn)),Cn.assign(Cn.saturate())})),Rn.assign(Cn.pow2().mix(xn.pow2(),1)),Mn.assign(Xd[0].mul(e.x).add(Xd[1].mul(e.y))),Pn.assign(Xd[1].mul(e.x).sub(Xd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ji(this.transmissionNode):Rc,t=this.thicknessNode?ji(this.thicknessNode):Cc,r=this.attenuationDistanceNode?ji(this.attenuationDistanceNode):Pc,s=this.attenuationColorNode?en(this.attenuationColorNode):Bc;if(kn.assign(e),Gn.assign(t),zn.assign(r),Hn.assign(s),this.useDispersion){const e=this.dispersionNode?ji(this.dispersionNode):Oc;$n.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?en(this.clearcoatNormalNode):Tc}setup(e){e.context.setupClearcoatNormal=()=>iu(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.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 Im extends Fg{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(Zl.mul(a)).normalize(),h=ji(zl.dot(c.negate()).saturate().pow(l).mul(d)),p=en(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Dm extends Fm{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=ji(.1),this.thicknessAmbientNode=ji(0),this.thicknessAttenuationNode=ji(.1),this.thicknessPowerNode=ji(2),this.thicknessScaleNode=ji(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Im(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 Vm=ki((({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=Yi(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Sd("gradientMap","texture").context({getUV:()=>i});return en(e.r)}{const e=i.fwidth().mul(.5);return Fo(en(.7),en(1),Uo(ji(.7).sub(e.x),ji(.7).add(e.x),i.x))}}));class Um extends Pp{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Vm({normal:ql,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Dp({diffuseColor:yn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Dp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const Om=new ye;class km extends lp{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Om),this.setValues(e)}setupLightingModel(){return new Um}}const Gm=ki((()=>{const e=en(zl.z,0,zl.x.negate()).normalize(),t=zl.cross(e);return Yi(e.dot(Zl),t.dot(Zl)).mul(.495).add(.5)})).once(["NORMAL","VERTEX"])().toVar("matcapUV"),zm=new be;class Hm extends lp{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(zm),this.setValues(e)}setupVariants(e){const t=Gm;let r;r=e.material.matcap?Sd("matcap","texture").context({getUV:()=>t}):en(Fo(.2,.8,t.y)),yn.rgb.mulAssign(r.rgb)}}class $m extends Ks{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode: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=cn(nn(1,0,0,0),nn(0,Ja(e.x),Za(e.x).negate(),0),nn(0,Za(e.x),Ja(e.x),0),nn(0,0,0,1)),i=cn(nn(Ja(e.y),0,Za(e.y),0),nn(0,1,0,0),nn(Za(e.y).negate(),0,Ja(e.y),0),nn(0,0,0,1)),n=cn(nn(Ja(e.z),Za(e.z).negate(),0,0),nn(Za(e.z),Ja(e.z),0,0),nn(0,0,1,0),nn(0,0,0,1));return s.mul(i).mul(n).mul(nn(r,1)).xyz}}}const Wm=Vi($m).setParameterLength(2),jm=new xe;class qm extends lp{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(jm),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,s=this.sizeAttenuation,{positionNode:i,rotationNode:n,scaleNode:a}=this,o=Bl.mul(en(i||0));let u=Yi(El[0].xyz.length(),El[1].xyz.length());if(null!==a&&(u=u.mul(Yi(a))),!1===s)if(r.isPerspectiveCamera)u=u.mul(o.z.negate());else{const e=ji(2).div(ll.element(1).element(1));u=u.mul(e.mul(2))}let l=Dl.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>Fi(new mu(e,t,r)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=ji(n||_c),c=Wm(l,d);return nn(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 Xm=new Te;class Km extends qm{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(Xm),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Bl.mul(en(e||Vl)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:r,scaleNode:s,sizeNode:i}=this,n=Dl.xy.toVar(),a=Ch.z.div(Ch.w);if(r&&r.isNode){const e=ji(r);n.assign(Wm(n,e))}let o=null!==i?Yi(i):Uc;return!0===this.sizeAttenuation&&(o=o.mul(o.div(Gl.z.negate()))),s&&s.isNode&&(o=o.mul(Yi(s))),n.mulAssign(o.mul(2)),n.assign(n.div(Ch.z)),n.y.assign(n.y.mul(a)),n.assign(n.mul(t.w)),t.addAssign(nn(n,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class Ym extends Pp{constructor(){super(),this.shadowNode=ji(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){yn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(yn.rgb)}}const Qm=new _e;class Zm extends lp{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Qm),this.setValues(e)}setupLightingModel(){return new Ym}}const Jm=mn("vec3"),ef=mn("vec3"),tf=mn("vec3");class rf extends Pp{constructor(){super()}start(e){const{material:t,context:r}=e,s=mn("vec3"),i=mn("vec3");Hi(gl.sub(Ol).length().greaterThan(Cl.mul(2)),(()=>{s.assign(gl),i.assign(Ol)})).Else((()=>{s.assign(Ol),i.assign(gl)}));const n=i.sub(s),a=Zn("int").onRenderUpdate((({material:e})=>e.steps)),o=n.length().div(a).toVar(),u=n.normalize().toVar(),l=ji(0).toVar(),d=en(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(o)),ch(a,(()=>{const i=s.add(u.mul(l)),n=cl.mul(nn(i,1)).xyz;let a;null!==t.depthNode&&(ef.assign(Xh(Hh(n.z,ol,ul))),r.sceneDepthNode=Xh(t.depthNode).toVar()),r.positionWorld=i,r.shadowPositionWorld=i,r.positionView=n,Jm.assign(0),t.scatteringNode&&(a=t.scatteringNode({positionRay:i})),super.start(e),a&&Jm.mulAssign(a);const c=Jm.mul(.01).negate().mul(o).exp();d.mulAssign(c),l.addAssign(o)})),tf.addAssign(d.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?Hi(r.greaterThanEqual(ef),(()=>{Jm.addAssign(e)})):Jm.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(ug({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(tf)}}class sf extends lp{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=S,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new rf}}class nf{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,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,null!==this._animationLoop&&this._animationLoop(t,r)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class af{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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)}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.version),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&&(r+=e.uuid+","),r+=e.receiveShadow+",",bs(r)}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=Ts(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ts(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const lf=[];class df{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);lf[0]=e,lf[1]=t,lf[2]=n,lf[3]=i;let l=u.get(lf);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(lf,l)):(l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),lf.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new af)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new uf(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class cf{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 hf=1,pf=2,gf=3,mf=4,ff=16;class yf extends cf{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===hf?this.backend.createAttribute(e):t===pf?this.backend.createIndexAttribute(e):t===gf?this.backend.createStorageAttribute(e):t===mf&&this.backend.createIndirectStorageAttribute(e),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version{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)};t.addEventListener("dispose",r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,gf):this.updateAttribute(e,hf);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,pf);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,mf)}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}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=xf(t),e.set(t,r)):r.version!==bf(t)&&(this.attributes.delete(r),r=xf(t),e.set(t,r)),s=r}return s}}class _f{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,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):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class vf{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Nf extends vf{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Sf extends vf{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Ef=0;class wf{constructor(e,t,r,s=null,i=null){this.id=Ef++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class Af extends cf{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend: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 wf(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.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 wf(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new wf(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.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}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 Sf(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 Nf(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)}_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 Rf extends cf{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))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?mf:gf;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(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?mf:gf;this.attributes.update(e,r)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(s=!0);const o=t.update(),u=t.texture;o&&this.textures.updateTexture(u);const l=r.get(u);if(void 0!==l.externalTexture||e.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===r.isWebGPUBackend&&void 0===l.texture&&void 0===l.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,u,t.textureNode.value,s),this.textures.updateTexture(u),s=!0),!0===u.isStorageTexture){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)}}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function Cf(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 Mf(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 Pf(e){return(e.transmission>0||e.transmissionNode)&&e.side===E&&!1===e.forceSinglePass}class Bf{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?(Pf(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?(Pf(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||Cf),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Mf),this.transparent.length>1&&this.transparent.sort(t||Mf)}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 U,l.format=e.stencilBuffer?we:Ae,l.type=e.stencilBuffer?Re:T,l.image.width=o,l.image.height=u,l.image.depth=a.depth,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{e.removeEventListener("dispose",t);for(let e=0;e0){const s=e.image;if(void 0===s)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)console.warn("THREE.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),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version}if(!0!==r.initialized){r.initialized=!0,r.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}r.version=e.version}getSize(e,t=zf){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),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.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class $f extends e{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Wf extends gn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class jf extends js{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const r=new Li(t);return this._currentCond=Xo(e,r),this.add(this._currentCond)}ElseIf(e,t){const r=new Li(t),s=Xo(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Li(e),this}Switch(e){return this._expressionNode=Fi(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let r=0;r"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=0;for(const r of this.membersLayout){const s=r.type,i=Rs(s)*e,n=t%8,a=n%Cs(s),o=n+a;t+=a,0!==o&&8-oe.name===t));return r?r.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.addInclude(this)}generate(e){return this.getNodeType(e)}}class Kf extends js{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structLayoutNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structLayoutNode.getNodeType(e)}getMemberType(e,t){return this.structLayoutNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structLayoutNode.membersLayout,this.values)}`,this),t.name}}class Yf extends js{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t{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)})),ry=(e,t)=>Ao(la(4,e.mul(ua(1,e))),t),sy=ki((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),iy=ki((([e])=>en(sy(e.z.add(sy(e.y.mul(1)))),sy(e.z.add(sy(e.x.mul(1)))),sy(e.y.add(sy(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ny=ki((([e,t,r])=>{const s=en(e).toVar(),i=ji(1.4).toVar(),n=ji(0).toVar(),a=en(s).toVar();return ch({start:ji(0),end:ji(3),type:"float",condition:"<="},(()=>{const e=en(iy(a.mul(2))).toVar();s.addAssign(e.add(r.mul(ji(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=ji(sy(s.z.add(sy(s.x.add(sy(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 ay extends js{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null,this.global=!0}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let r=this._candidateFnCall;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._candidateFnCall=r=s(...t)}return r}}const oy=Vi(ay),uy=e=>(...t)=>oy(e,...t),ly=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.time)),dy=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.deltaTime)),cy=Zn(0,"uint").setGroup(Kn).onRenderUpdate((e=>e.frameId)),hy=ki((([e,t,r=Yi(.5)])=>Wm(e.sub(r),t).add(r))),py=ki((([e,t,r=Yi(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))})),gy=ki((({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=El.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=El;const i=cl.mul(s);return Pi(t)&&(i[0][0]=El[0].length(),i[0][1]=0,i[0][2]=0),Pi(r)&&(i[1][0]=0,i[1][1]=El[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,ll.mul(i).mul(Vl)})),my=ki((([e=null])=>{const t=Xh();return Xh(kh(e)).sub(t).lessThan(0).select(wh,e)}));class fy extends js{static get type(){return"SpriteSheetUVNode"}constructor(e,t=$u(),r=ji(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=r}setup(){const{frameNode:e,uvNode:t,countNode:r}=this,{width:s,height:i}=r,n=e.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=r.reciprocal(),l=Yi(a,o);return t.add(l).mul(u)}}const yy=Vi(fy).setParameterLength(3),by=ki((([e,t=null,r=null,s=ji(1),i=Vl,n=Xl])=>{let a=n.abs().normalize();a=a.div(a.dot(en(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=Zu(d,o).mul(a.x),g=Zu(c,u).mul(a.y),m=Zu(h,l).mul(a.z);return oa(p,g,m)})),xy=new Me,Ty=new r,_y=new r,vy=new r,Ny=new a,Sy=new r(0,0,-1),Ey=new s,wy=new r,Ay=new r,Ry=new s,Cy=new t,My=new ue,Py=wh.flipX();My.depthTexture=new U(1,1);let By=!1;class Ly extends Yu{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||My.texture,Py),this._reflectorBaseNode=e.reflector||new Fy(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=Fi(new Ly({defaultTexture:My.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._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class Fy extends js{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new Pe,resolution:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1}=t;this.textureNode=e,this.target=r,this.resolution=s,this.generateMipmaps=i,this.bounces=n,this.depth=a,this.updateBeforeType=n?Vs.RENDER:Vs.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolution;t.getDrawingBufferSize(Cy),e.setSize(Math.round(Cy.width*r),Math.round(Cy.height*r))}setup(e){return this._updateResolution(My,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 ue(0,0,{type:ce}),!0===this.generateMipmaps&&(t.texture.minFilter=Be,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new U),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&By)return!1;By=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(Cy),this._updateResolution(o,s),_y.setFromMatrixPosition(n.matrixWorld),vy.setFromMatrixPosition(r.matrixWorld),Ny.extractRotation(n.matrixWorld),Ty.set(0,0,1),Ty.applyMatrix4(Ny),wy.subVectors(_y,vy);let u=!1;if(!0===wy.dot(Ty)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(By=!1);u=!0}wy.reflect(Ty).negate(),wy.add(_y),Ny.extractRotation(r.matrixWorld),Sy.set(0,0,-1),Sy.applyMatrix4(Ny),Sy.add(vy),Ay.subVectors(_y,Sy),Ay.reflect(Ty).negate(),Ay.add(_y),a.coordinateSystem=r.coordinateSystem,a.position.copy(wy),a.up.set(0,1,0),a.up.applyMatrix4(Ny),a.up.reflect(Ty),a.lookAt(Ay),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),xy.setFromNormalAndCoplanarPoint(Ty,_y),xy.applyMatrix4(a.matrixWorldInverse),Ey.set(xy.normal.x,xy.normal.y,xy.normal.z,xy.constant);const l=a.projectionMatrix;Ry.x=(Math.sign(Ey.x)+l.elements[8])/l.elements[0],Ry.y=(Math.sign(Ey.y)+l.elements[9])/l.elements[5],Ry.z=-1,Ry.w=(1+l.elements[10])/l.elements[14],Ey.multiplyScalar(1/Ey.dot(Ry));l.elements[2]=Ey.x,l.elements[6]=Ey.y,l.elements[10]=s.coordinateSystem===d?Ey.z-0:Ey.z+1-0,l.elements[14]=Ey.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const c=s.getRenderTarget(),h=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0,u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),s.setMRT(h),s.setRenderTarget(c),s.autoClear=p,i.visible=!0,By=!1,this.forceUpdate=!1}}const Iy=new ae(-1,1,1,-1,0,1);class Dy extends pe{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Le([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Le(t,2))}}const Vy=new Dy;class Uy extends X{constructor(e=null){super(Vy,e),this.camera=Iy,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,Iy)}render(e){e.render(this,Iy)}}const Oy=new t;class ky extends Yu{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:ce}){const i=new ue(t,r,s);super(i.texture,$u()),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 Uy(new lp),this.updateBeforeType=Vs.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(Oy),s=r.width*t,i=r.height*t;s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}this._quadMesh.material.fragmentNode=this._rttNode;const t=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){const e=new Yu(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const Gy=(e,...t)=>Fi(new ky(Fi(e),...t)),zy=ki((([e,t,r],s)=>{let i;s.renderer.coordinateSystem===d?(e=Yi(e.x,e.y.oneMinus()).mul(2).sub(1),i=nn(en(e,t),1)):i=nn(en(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=nn(r.mul(i));return n.xyz.div(n.w)})),Hy=ki((([e,t])=>{const r=t.mul(nn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return Yi(s.x,s.y.oneMinus())})),$y=ki((([e,t,r])=>{const s=ju(Ju(t)),i=Qi(e.mul(s)).toVar(),n=Ju(t,i).toVar(),a=Ju(t,i.sub(Qi(2,0))).toVar(),o=Ju(t,i.sub(Qi(1,0))).toVar(),u=Ju(t,i.add(Qi(1,0))).toVar(),l=Ju(t,i.add(Qi(2,0))).toVar(),d=Ju(t,i.add(Qi(0,2))).toVar(),c=Ju(t,i.add(Qi(0,1))).toVar(),h=Ju(t,i.sub(Qi(0,1))).toVar(),p=Ju(t,i.sub(Qi(0,2))).toVar(),g=io(ua(ji(2).mul(o).sub(a),n)).toVar(),m=io(ua(ji(2).mul(u).sub(l),n)).toVar(),f=io(ua(ji(2).mul(c).sub(d),n)).toVar(),y=io(ua(ji(2).mul(h).sub(p),n)).toVar(),b=zy(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(zy(e.sub(Yi(ji(1).div(s.x),0)),o,r)),b.negate().add(zy(e.add(Yi(ji(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(zy(e.add(Yi(0,ji(1).div(s.y))),c,r)),b.negate().add(zy(e.sub(Yi(0,ji(1).div(s.y))),h,r)));return Ya(wo(x,T))}));class Wy extends js{static get type(){return"SampleNode"}constructor(e){super(),this.callback=e,this.isSampleNode=!0}setup(){return this.sample($u())}sample(e){return this.callback(e)}}class jy extends L{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class qy extends ge{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class Xy extends js{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Ky=Ui(Xy),Yy=new w,Qy=new a;class Zy extends js{static get type(){return"SceneNode"}constructor(e=Zy.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,r=null!==this.scene?this.scene:e.scene;let s;return t===Zy.BACKGROUND_BLURRINESS?s=_d("backgroundBlurriness","float",r):t===Zy.BACKGROUND_INTENSITY?s=_d("backgroundIntensity","float",r):t===Zy.BACKGROUND_ROTATION?s=Zn("mat4").label("backgroundRotation").setGroup(Kn).onRenderUpdate((()=>{const e=r.background;return null!==e&&e.isTexture&&e.mapping!==Fe?(Yy.copy(r.backgroundRotation),Yy.x*=-1,Yy.y*=-1,Yy.z*=-1,Qy.makeRotationFromEuler(Yy)):Qy.identity(),Qy})):console.error("THREE.SceneNode: Unknown scope:",t),s}}Zy.BACKGROUND_BLURRINESS="backgroundBlurriness",Zy.BACKGROUND_INTENSITY="backgroundIntensity",Zy.BACKGROUND_ROTATION="backgroundRotation";const Jy=Ui(Zy,Zy.BACKGROUND_BLURRINESS),eb=Ui(Zy,Zy.BACKGROUND_INTENSITY),tb=Ui(Zy,Zy.BACKGROUND_ROTATION);class rb extends Yu{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.isStorageTextureNode=!0,this.access=Os.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}generate(e,t){let r;return r=null!==this.storeNode?this.generateStore(e):super.generate(e,t),r}toReadWrite(){return this.setAccess(Os.READ_WRITE)}toReadOnly(){return this.setAccess(Os.READ_ONLY)}toWriteOnly(){return this.setAccess(Os.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,"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(e,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e}}const sb=Vi(rb).setParameterLength(1,3),ib=ki((({texture:e,uv:t})=>{const r=1e-4,s=en().toVar();return Hi(t.x.lessThan(r),(()=>{s.assign(en(1,0,0))})).ElseIf(t.y.lessThan(r),(()=>{s.assign(en(0,1,0))})).ElseIf(t.z.lessThan(r),(()=>{s.assign(en(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{s.assign(en(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{s.assign(en(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{s.assign(en(0,0,-1))})).Else((()=>{const r=.01,i=e.sample(t.add(en(-.01,0,0))).r.sub(e.sample(t.add(en(r,0,0))).r),n=e.sample(t.add(en(0,-.01,0))).r.sub(e.sample(t.add(en(0,r,0))).r),a=e.sample(t.add(en(0,0,-.01))).r.sub(e.sample(t.add(en(0,0,r))).r);s.assign(en(i,n,a))})),s.normalize()}));class nb extends Yu{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return en(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!e.isFlipY()||!0!==r.isRenderTargetTexture&&!0!==r.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return ib({texture:this,uv:e})}}const ab=Vi(nb).setParameterLength(1,3);class ob extends Td{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 ub=new WeakMap;class lb extends Ks{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=Vs.OBJECT,this.updateAfterType=Vs.OBJECT,this.previousModelWorldMatrix=Zn(new a),this.previousProjectionMatrix=Zn(new a).setGroup(Kn),this.previousCameraViewMatrix=Zn(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=cb(r);this.previousModelWorldMatrix.value.copy(s);const i=db(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}){cb(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?ll:Zn(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(Bl).mul(Vl),s=this.previousProjectionMatrix.mul(t).mul(Ul),i=r.xy.div(r.w),n=s.xy.div(s.w);return ua(i,n)}}function db(e){let t=ub.get(e);return void 0===t&&(t={},ub.set(e,t)),t}function cb(e,t=0){const r=db(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const hb=Ui(lb),pb=ki((([e])=>yb(e.rgb))),gb=ki((([e,t=ji(1)])=>t.mix(yb(e.rgb),e.rgb))),mb=ki((([e,t=ji(1)])=>{const r=oa(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 Fo(e.rgb,s,i)})),fb=ki((([e,t=ji(1)])=>{const r=en(.57735,.57735,.57735),s=t.cos();return en(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(Eo(r,e.rgb).mul(s.oneMinus())))))})),yb=(e,t=en(c.getLuminanceCoefficients(new r)))=>Eo(e,t),bb=ki((([e,t=en(1),s=en(0),i=en(1),n=ji(1),a=en(c.getLuminanceCoefficients(new r,le))])=>{const o=e.rgb.dot(en(a)),u=To(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return Hi(u.r.greaterThan(0),(()=>{u.r.assign(l.r)})),Hi(u.g.greaterThan(0),(()=>{u.g.assign(l.g)})),Hi(u.b.greaterThan(0),(()=>{u.b.assign(l.b)})),u.assign(o.add(u.sub(o).mul(n))),nn(u.rgb,e.a)}));class xb extends Ks{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const Tb=Vi(xb).setParameterLength(2),_b=new t;class vb extends Yu{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Nb extends vb{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r}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}}class Sb extends Ks{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 U;i.isRenderTargetTexture=!0,i.name="depth";const n=new ue(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Zn(0),this._cameraFar=Zn(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=Vs.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}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=Fi(new Nb(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=Fi(new Nb(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=$h(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=zh(i,r,s)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Sb.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),_b.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(_b)),this._pixelRatio=i,this.setSize(_b.width,_b.height);const a=t.getRenderTarget(),o=t.getMRT(),u=s.layers.mask;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);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(r,s),t.setRenderTarget(a),t.setMRT(o),s.layers.mask=u}setSize(e,t){this._width=e,this._height=t;const r=this._width*this._pixelRatio*this._resolution,s=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(r,s)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Sb.COLOR="color",Sb.DEPTH="depth";class Eb extends Sb{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(Sb.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap}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 lp;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=S;const t=Xl.negate(),r=ll.mul(Bl),s=ji(1),i=r.mul(nn(Vl,1)),n=r.mul(nn(Vl.add(t),1)),a=Ya(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=nn(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 wb=ki((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ab=ki((([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"}]}),Rb=ki((([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"}]}),Cb=ki((([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)})),Mb=ki((([e,t])=>{const r=dn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=dn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=Cb(e),(e=s.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Pb=dn(en(1.6605,-.1246,-.0182),en(-.5876,1.1329,-.1006),en(-.0728,-.0083,1.1187)),Bb=dn(en(.6274,.0691,.0164),en(.3293,.9195,.088),en(.0433,.0113,.8956)),Lb=ki((([e])=>{const t=en(e).toVar(),r=en(t.mul(t)).toVar(),s=en(r.mul(r)).toVar();return ji(15.5).mul(s.mul(r)).sub(la(40.14,s.mul(t))).add(la(31.96,s).sub(la(6.868,r.mul(t))).add(la(.4298,r).add(la(.1191,t).sub(.00232))))})),Fb=ki((([e,t])=>{const r=en(e).toVar(),s=dn(en(.856627153315983,.137318972929847,.11189821299995),en(.0951212405381588,.761241990602591,.0767994186031903),en(.0482516061458583,.101439036467562,.811302368396859)),i=dn(en(1.1271005818144368,-.1413297634984383,-.14132976349843826),en(-.11060664309660323,1.157823702216272,-.11060664309660294),en(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ji(-12.47393),a=ji(4.026069);return r.mulAssign(t),r.assign(Bb.mul(r)),r.assign(s.mul(r)),r.assign(To(r,1e-10)),r.assign(Wa(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Io(r,0,1)),r.assign(Lb(r)),r.assign(i.mul(r)),r.assign(Ao(To(en(0),r),en(2.2))),r.assign(Pb.mul(r)),r.assign(Io(r,0,1)),r})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ib=ki((([e,t])=>{const r=ji(.76),s=ji(.15);e=e.mul(t);const i=xo(e.r,xo(e.g,e.b)),n=Xo(i.lessThan(.08),i.sub(la(6.25,i.mul(i))),.04);e.subAssign(n);const a=To(e.r,To(e.g,e.b));Hi(a.lessThan(r),(()=>e));const o=ua(1,r),u=ua(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=ua(1,da(1,s.mul(a.sub(u)).add(1)));return Fo(e,en(u),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Db extends js{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 Vb=Vi(Db).setParameterLength(1,3);class Ub extends Db{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}getNodeType(e){return this.getNodeFunction(e).type}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 Ob=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};class kb extends js{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new o,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:ji()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ls(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?Fs(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const Gb=Vi(kb).setParameterLength(1);class zb extends Map{get(e,t=null,...r){if(this.has(e))return super.get(e);if(null!==t){const s=t(...r);return this.set(e,s),s}}}class Hb{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const $b=new zb;class Wb extends js{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new zb,this._output=Gb(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const r=this._outputs;return void 0===r[e]?r[e]=Gb(t):r[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const r=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),r[e]=t,r[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),r[e]=t,r[e].events.addEventListener("refresh",this.onRefresh)):void 0===r[e]?(r[e]=Gb(t),r[e].events.addEventListener("refresh",this.onRefresh)):r[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const r=this.getObject()[e];if("function"==typeof r)return r(...t)}async callAsync(e,...t){const r=this.getObject()[e];if("function"==typeof r)return"AsyncFunction"===r.constructor.name?await r(...t):r(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new Hb(this),t=$b.get("THREE"),r=$b.get("TSL"),s=this.getMethod(),i=[e,this._local,$b,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,r];this._object=s(...i);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:ji()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",r="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],r),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[bs(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const r in this.parameters)t.push(this.parameters[r].getCacheKey(e));return xs(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const jb=Vi(Wb).setParameterLength(1,2);function qb(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||Gl.z).negate()}const Xb=ki((([e,t],r)=>{const s=qb(r);return Uo(e,t,s)})),Kb=ki((([e],t)=>{const r=qb(t);return e.mul(e,r,r).negate().exp().oneMinus()})),Yb=ki((([e,t])=>nn(t.toFloat().mix(In.rgb,e.toVec3()),In.a)));let Qb=null,Zb=null;class Jb extends js{static get type(){return"RangeNode"}constructor(e=ji(),t=ji()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Ms(this.minNode.value)),r=e.getTypeLength(Ms(this.maxNode.value));return t>r?t:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.minNode.value,n=this.maxNode.value,a=e.getTypeLength(Ms(i)),o=e.getTypeLength(Ms(n));Qb=Qb||new s,Zb=Zb||new s,Qb.setScalar(0),Zb.setScalar(0),1===a?Qb.setScalar(i):i.isColor?Qb.set(i.r,i.g,i.b,1):Qb.set(i.x,i.y,i.z||0,i.w||0),1===o?Zb.setScalar(n):n.isColor?Zb.set(n.r,n.g,n.b,1):Zb.set(n.x,n.y,n.z||0,n.w||0);const l=4,d=l*t.count,c=new Float32Array(d);for(let e=0;eFi(new tx(e,t)),sx=rx("numWorkgroups","uvec3"),ix=rx("workgroupId","uvec3"),nx=rx("globalId","uvec3"),ax=rx("localId","uvec3"),ox=rx("subgroupSize","uint");const ux=Vi(class extends js{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class lx extends qs{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 dx extends js{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e}label(e){return this.name=e,this}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return Fi(new lx(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class cx extends js{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)}getNodeType(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(!(1===r.length&&!0===r[0].isStackNode))return void 0===t.constNode&&(t.constNode=Du(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}cx.ATOMIC_LOAD="atomicLoad",cx.ATOMIC_STORE="atomicStore",cx.ATOMIC_ADD="atomicAdd",cx.ATOMIC_SUB="atomicSub",cx.ATOMIC_MAX="atomicMax",cx.ATOMIC_MIN="atomicMin",cx.ATOMIC_AND="atomicAnd",cx.ATOMIC_OR="atomicOr",cx.ATOMIC_XOR="atomicXor";const hx=Vi(cx),px=(e,t,r)=>hx(e,t,r).toStack();let gx;function mx(e){gx=gx||new WeakMap;let t=gx.get(e);return void 0===t&&gx.set(e,t={}),t}function fx(e){const t=mx(e);return t.shadowMatrix||(t.shadowMatrix=Zn("mat4").setGroup(Kn).onRenderUpdate((t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix))))}function yx(e,t=Ol){const r=fx(e).mul(t);return r.xyz.div(r.w)}function bx(e){const t=mx(e);return t.position||(t.position=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld))))}function xx(e){const t=mx(e);return t.targetPosition||(t.targetPosition=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld))))}function Tx(e){const t=mx(e);return t.viewPosition||(t.viewPosition=Zn(new r).setGroup(Kn).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const _x=e=>cl.transformDirection(bx(e).sub(xx(e))),vx=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},Nx=new WeakMap,Sx=[];class Ex extends js{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=mn("vec3","totalDiffuse"),this.totalSpecularNode=mn("vec3","totalSpecular"),this.outgoingLightNode=mn("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(Fi(e));else{let s=null;if(null!==r&&(s=vx(e.id,r)),null===s){const r=i.getLightNodeClass(e.constructor);if(null===r){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let s=null;Nx.has(e)?s=Nx.get(e):(s=Fi(new r(e)),Nx.set(e,s)),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=en(null!==l?l.mix(g,u):u),s.material.transparent=!0),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 wx extends js{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Vs.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Ax.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ol)}}const Ax=mn("vec3","shadowPositionWorld");function Rx(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 Cx(e,t){return t=Rx(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function Mx(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 Px(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function Bx(e,t){return t=Px(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function Lx(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function Fx(e,t,r){return r=Bx(t,r=Cx(e,r))}function Ix(e,t,r){Mx(e,r),Lx(t,r)}var Dx=Object.freeze({__proto__:null,resetRendererAndSceneState:Fx,resetRendererState:Cx,resetSceneState:Bx,restoreRendererAndSceneState:Ix,restoreRendererState:Mx,restoreSceneState:Lx,saveRendererAndSceneState:function(e,t,r={}){return r=Px(t,r=Rx(e,r))},saveRendererState:Rx,saveSceneState:Px});const Vx=new WeakMap,Ux=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Zu(e,t.xy).label("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)})),Ox=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=_d("radius","float",r).setGroup(Kn),o=Yi(1).div(n),u=o.x.negate().mul(a),l=o.y.negate().mul(a),d=o.x.mul(a),c=o.y.mul(a),h=u.div(2),p=l.div(2),g=d.div(2),m=c.div(2);return oa(i(t.xy.add(Yi(u,l)),t.z),i(t.xy.add(Yi(0,l)),t.z),i(t.xy.add(Yi(d,l)),t.z),i(t.xy.add(Yi(h,p)),t.z),i(t.xy.add(Yi(0,p)),t.z),i(t.xy.add(Yi(g,p)),t.z),i(t.xy.add(Yi(u,0)),t.z),i(t.xy.add(Yi(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(Yi(g,0)),t.z),i(t.xy.add(Yi(d,0)),t.z),i(t.xy.add(Yi(h,m)),t.z),i(t.xy.add(Yi(0,m)),t.z),i(t.xy.add(Yi(g,m)),t.z),i(t.xy.add(Yi(u,c)),t.z),i(t.xy.add(Yi(0,c)),t.z),i(t.xy.add(Yi(d,c)),t.z)).mul(1/17)})),kx=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=Yi(1).div(n),o=a.x,u=a.y,l=t.xy,d=Qa(l.mul(n).add(.5));return l.subAssign(d.mul(a)),oa(i(l,t.z),i(l.add(Yi(o,0)),t.z),i(l.add(Yi(0,u)),t.z),i(l.add(a),t.z),Fo(i(l.add(Yi(o.negate(),0)),t.z),i(l.add(Yi(o.mul(2),0)),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u)),t.z),i(l.add(Yi(o.mul(2),u)),t.z),d.x),Fo(i(l.add(Yi(0,u.negate())),t.z),i(l.add(Yi(0,u.mul(2))),t.z),d.y),Fo(i(l.add(Yi(o,u.negate())),t.z),i(l.add(Yi(o,u.mul(2))),t.z),d.y),Fo(Fo(i(l.add(Yi(o.negate(),u.negate())),t.z),i(l.add(Yi(o.mul(2),u.negate())),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u.mul(2))),t.z),i(l.add(Yi(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)})),Gx=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{const s=ji(1).toVar();let i=Zu(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=_o(t.z,i.x);return Hi(n.notEqual(ji(1)),(()=>{const e=t.z.sub(i.x),r=To(0,i.y.mul(i.y));let a=r.div(r.add(e.mul(e)));a=Io(ua(a,.3).div(.95-.3)),s.assign(Io(To(n,a)))})),s})),zx=ki((([e,t,r])=>{let s=Ol.sub(e).length();return s=s.sub(t).div(r.sub(t)),s=s.saturate(),s})),Hx=e=>{let t=Vx.get(e);if(void 0===t){const r=e.isPointLight?(e=>{const t=e.shadow.camera,r=_d("near","float",t).setGroup(Kn),s=_d("far","float",t).setGroup(Kn),i=xl(e);return zx(i,r,s)})(e):null;t=new lp,t.colorNode=nn(0,0,0,1),t.depthNode=r,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,Vx.set(e,t)}return t},$x=new af,Wx=[],jx=(e,t,r,s)=>{Wx[0]=e,Wx[1]=t;let i=$x.get(Wx);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===Ie)&&(s&&(Bs(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,$x.set(Wx,i)),Wx[0]=null,Wx[1]=null,i},qx=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanVertical"),a=ji(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));ch({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(Rh.xy,Yi(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=ja(a.sub(n.mul(n)));return Yi(n,l)})),Xx=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanHorizontal"),a=ji(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));ch({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(Rh.xy,Yi(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(oa(d.y.mul(d.y),d.x.mul(d.x)))})),n.divAssign(e),a.divAssign(e);const l=ja(a.sub(n.mul(n)));return Yi(n,l)})),Kx=[Ux,Ox,kx,Gx];let Yx;const Qx=new Uy;class Zx extends wx{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture: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,ji(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=_d("bias","float",r).setGroup(Kn);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,s.coordinateSystem===d&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=_d("near","float",r.camera).setGroup(Kn),s=_d("far","float",r.camera).setGroup(Kn);n=Wh(e.negate(),t,s)}return a=en(a.x,a.y.oneMinus(),n.add(i)),a}getShadowFilterFn(e){return Kx[e]}setupRenderTarget(e,t){const r=new U(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=De;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}=e,{light:r,shadow:s}=this,i=t.shadowMap.type,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(s,e);if(s.camera.updateProjectionMatrix(),i===Ie&&!0!==s.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}));let t=Zu(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Zu(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const i=_d("blurSamples","float",s).setGroup(Kn),o=_d("radius","float",s).setGroup(Kn),u=_d("mapSize","vec2",s).setGroup(Kn);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new lp);l.fragmentNode=qx({samples:i,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new lp),l.fragmentNode=Xx({samples:i,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=_d("intensity","float",s).setGroup(Kn),u=_d("normalBias","float",s).setGroup(Kn),l=fx(r).mul(Ax.add(Jl.mul(u))),d=this.setupShadowCoord(e,l),c=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const h=i===Ie&&!0!==s.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:a.texture,depthTexture:h,shadowCoord:d,shadow:s,depthLayer:this.depthLayer});let g=Zu(a.texture,d);n.isArrayTexture&&(g=g.depth(this.depthLayer));const m=Fo(1,p.rgb.mix(g,1),o.mul(g.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return ki((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth),i.render(n,t.camera)}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");Yx=Fx(i,n,Yx),n.overrideMaterial=Hx(r),i.setRenderObjectFunction(jx(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===Ie&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,Ix(i,n,Yx)}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),Qx.material=this.vsmMaterialVertical,Qx.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Qx.material=this.vsmMaterialHorizontal,Qx.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let 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 Jx=(e,t)=>Fi(new Zx(e,t)),eT=new e,tT=ki((([e,t])=>{const r=e.toVar(),s=io(r),i=da(1,To(s.x,To(s.y,s.z)));s.mulAssign(i),r.mulAssign(i.mul(t.mul(2).oneMinus()));const n=Yi(r.xy).toVar(),a=t.mul(1.5).oneMinus();return Hi(s.z.greaterThanEqual(a),(()=>{Hi(r.z.greaterThan(0),(()=>{n.x.assign(ua(4,r.x))}))})).ElseIf(s.x.greaterThanEqual(a),(()=>{const e=no(r.x);n.x.assign(r.z.mul(e).add(e.mul(2)))})).ElseIf(s.y.greaterThanEqual(a),(()=>{const e=no(r.y);n.x.assign(r.x.add(e.mul(2)).add(2)),n.y.assign(r.z.mul(e).sub(2))})),Yi(.125,.25).mul(n).add(Yi(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),rT=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s})=>Zu(e,tT(t,s.y)).compare(r))),sT=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s,shadow:i})=>{const n=_d("radius","float",i).setGroup(Kn),a=Yi(-1,1).mul(n).mul(s.y);return Zu(e,tT(t.add(a.xyy),s.y)).compare(r).add(Zu(e,tT(t.add(a.yyy),s.y)).compare(r)).add(Zu(e,tT(t.add(a.xyx),s.y)).compare(r)).add(Zu(e,tT(t.add(a.yyx),s.y)).compare(r)).add(Zu(e,tT(t,s.y)).compare(r)).add(Zu(e,tT(t.add(a.xxy),s.y)).compare(r)).add(Zu(e,tT(t.add(a.yxy),s.y)).compare(r)).add(Zu(e,tT(t.add(a.xxx),s.y)).compare(r)).add(Zu(e,tT(t.add(a.yxx),s.y)).compare(r)).mul(1/9)})),iT=ki((({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s})=>{const i=r.xyz.toVar(),n=i.length(),a=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.near)),o=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.far)),u=_d("bias","float",s).setGroup(Kn),l=Zn(s.mapSize).setGroup(Kn),d=ji(1).toVar();return Hi(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),(()=>{const r=n.sub(a).div(o.sub(a)).toVar();r.addAssign(u);const c=i.normalize(),h=Yi(1).div(l.mul(Yi(4,2)));d.assign(e({depthTexture:t,bd3D:c,dp:r,texelSize:h,shadow:s}))})),d})),nT=new s,aT=new t,oT=new t;class uT extends Zx{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Ue?rT:sT}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n}){return iT({filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.getFrameExtents();oT.copy(t.mapSize),oT.multiply(a),r.setSize(oT.width,oT.height),aT.copy(t.mapSize);const o=i.autoClear,u=i.getClearColor(eT),l=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const d=t.getViewportCount();for(let e=0;eFi(new uT(e,t));class dT extends bh{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Zn(this.color).setGroup(Kn),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vs.FRAME}getHash(){return this.light.uuid}getLightVector(e){return Tx(this.light).sub(e.context.positionView||Gl)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return Jx(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?Fi(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}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 cT=ki((({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)})),hT=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=cT({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class pT extends dT{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(2).setGroup(Kn)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return lT(this.light)}setupDirect(e){return hT({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const gT=ki((([e=$u()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()})),mT=ki((([e=$u()],{renderer:t,material:r})=>{const s=Lo(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.samples>1){const e=ji(s.fwidth()).toVar();i=Uo(e.oneMinus(),e.add(1),s).oneMinus()}else i=Xo(s.greaterThan(1),0,1);return i})),fT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Ki(e).toVar();return Xo(n,i,s)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),yT=ki((([e,t])=>{const r=Ki(t).toVar(),s=ji(e).toVar();return Xo(r,s.negate(),s)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),bT=ki((([e])=>{const t=ji(e).toVar();return qi(Xa(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),xT=ki((([e,t])=>{const r=ji(e).toVar();return t.assign(bT(r)),r.sub(ji(t))})),TT=uy([ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=ji(s).toVar(),l=ji(r).toVar(),d=ji(t).toVar(),c=ji(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]}),ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=en(s).toVar(),l=en(r).toVar(),d=en(t).toVar(),c=en(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]})]),_T=uy([ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=ji(o).toVar(),m=ji(a).toVar(),f=ji(n).toVar(),y=ji(i).toVar(),b=ji(s).toVar(),x=ji(r).toVar(),T=ji(t).toVar(),_=ji(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]}),ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=en(o).toVar(),m=en(a).toVar(),f=en(n).toVar(),y=en(i).toVar(),b=en(s).toVar(),x=en(r).toVar(),T=en(t).toVar(),_=en(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]})]),vT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Xi(e).toVar(),a=Xi(n.bitAnd(Xi(7))).toVar(),o=ji(fT(a.lessThan(Xi(4)),i,s)).toVar(),u=ji(la(2,fT(a.lessThan(Xi(4)),s,i))).toVar();return yT(o,Ki(a.bitAnd(Xi(1)))).add(yT(u,Ki(a.bitAnd(Xi(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),NT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=Xi(e).toVar(),u=Xi(o.bitAnd(Xi(15))).toVar(),l=ji(fT(u.lessThan(Xi(8)),a,n)).toVar(),d=ji(fT(u.lessThan(Xi(4)),n,fT(u.equal(Xi(12)).or(u.equal(Xi(14))),a,i))).toVar();return yT(l,Ki(u.bitAnd(Xi(1)))).add(yT(d,Ki(u.bitAnd(Xi(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"}]}),ST=uy([vT,NT]),ET=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=rn(e).toVar();return en(ST(n.x,i,s),ST(n.y,i,s),ST(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"}]}),wT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=rn(e).toVar();return en(ST(o.x,a,n,i),ST(o.y,a,n,i),ST(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"}]}),AT=uy([ET,wT]),RT=ki((([e])=>{const t=ji(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),CT=ki((([e])=>{const t=ji(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),MT=uy([RT,ki((([e])=>{const t=en(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),PT=uy([CT,ki((([e])=>{const t=en(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),BT=ki((([e,t])=>{const r=qi(t).toVar(),s=Xi(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(qi(32).sub(r)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),LT=ki((([e,t,r])=>{e.subAssign(r),e.bitXorAssign(BT(r,qi(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(BT(e,qi(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(BT(t,qi(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(BT(r,qi(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(BT(e,qi(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(BT(t,qi(4))),t.addAssign(e)})),FT=ki((([e,t,r])=>{const s=Xi(r).toVar(),i=Xi(t).toVar(),n=Xi(e).toVar();return s.bitXorAssign(i),s.subAssign(BT(i,qi(14))),n.bitXorAssign(s),n.subAssign(BT(s,qi(11))),i.bitXorAssign(n),i.subAssign(BT(n,qi(25))),s.bitXorAssign(i),s.subAssign(BT(i,qi(16))),n.bitXorAssign(s),n.subAssign(BT(s,qi(4))),i.bitXorAssign(n),i.subAssign(BT(n,qi(14))),s.bitXorAssign(i),s.subAssign(BT(i,qi(24))),s})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),IT=ki((([e])=>{const t=Xi(e).toVar();return ji(t).div(ji(Xi(qi(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),DT=ki((([e])=>{const t=ji(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"}]}),VT=uy([ki((([e])=>{const t=qi(e).toVar(),r=Xi(Xi(1)).toVar(),s=Xi(Xi(qi(3735928559)).add(r.shiftLeft(Xi(2))).add(Xi(13))).toVar();return FT(s.add(Xi(t)),s,s)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(Xi(2)).toVar(),n=Xi().toVar(),a=Xi().toVar(),o=Xi().toVar();return n.assign(a.assign(o.assign(Xi(qi(3735928559)).add(i.shiftLeft(Xi(2))).add(Xi(13))))),n.addAssign(Xi(s)),a.addAssign(Xi(r)),FT(n,a,o)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(Xi(3)).toVar(),o=Xi().toVar(),u=Xi().toVar(),l=Xi().toVar();return o.assign(u.assign(l.assign(Xi(qi(3735928559)).add(a.shiftLeft(Xi(2))).add(Xi(13))))),o.addAssign(Xi(n)),u.addAssign(Xi(i)),l.addAssign(Xi(s)),FT(o,u,l)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),ki((([e,t,r,s])=>{const i=qi(s).toVar(),n=qi(r).toVar(),a=qi(t).toVar(),o=qi(e).toVar(),u=Xi(Xi(4)).toVar(),l=Xi().toVar(),d=Xi().toVar(),c=Xi().toVar();return l.assign(d.assign(c.assign(Xi(qi(3735928559)).add(u.shiftLeft(Xi(2))).add(Xi(13))))),l.addAssign(Xi(o)),d.addAssign(Xi(a)),c.addAssign(Xi(n)),LT(l,d,c),l.addAssign(Xi(i)),FT(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"}]}),ki((([e,t,r,s,i])=>{const n=qi(i).toVar(),a=qi(s).toVar(),o=qi(r).toVar(),u=qi(t).toVar(),l=qi(e).toVar(),d=Xi(Xi(5)).toVar(),c=Xi().toVar(),h=Xi().toVar(),p=Xi().toVar();return c.assign(h.assign(p.assign(Xi(qi(3735928559)).add(d.shiftLeft(Xi(2))).add(Xi(13))))),c.addAssign(Xi(l)),h.addAssign(Xi(u)),p.addAssign(Xi(o)),LT(c,h,p),c.addAssign(Xi(a)),h.addAssign(Xi(n)),FT(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"}]})]),UT=uy([ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(VT(s,r)).toVar(),n=rn().toVar();return n.x.assign(i.bitAnd(qi(255))),n.y.assign(i.shiftRight(qi(8)).bitAnd(qi(255))),n.z.assign(i.shiftRight(qi(16)).bitAnd(qi(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(VT(n,i,s)).toVar(),o=rn().toVar();return o.x.assign(a.bitAnd(qi(255))),o.y.assign(a.shiftRight(qi(8)).bitAnd(qi(255))),o.z.assign(a.shiftRight(qi(16)).bitAnd(qi(255))),o})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),OT=uy([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(xT(t.x,r)).toVar(),n=ji(xT(t.y,s)).toVar(),a=ji(DT(i)).toVar(),o=ji(DT(n)).toVar(),u=ji(TT(ST(VT(r,s),i,n),ST(VT(r.add(qi(1)),s),i.sub(1),n),ST(VT(r,s.add(qi(1))),i,n.sub(1)),ST(VT(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return MT(u)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(xT(t.x,r)).toVar(),a=ji(xT(t.y,s)).toVar(),o=ji(xT(t.z,i)).toVar(),u=ji(DT(n)).toVar(),l=ji(DT(a)).toVar(),d=ji(DT(o)).toVar(),c=ji(_T(ST(VT(r,s,i),n,a,o),ST(VT(r.add(qi(1)),s,i),n.sub(1),a,o),ST(VT(r,s.add(qi(1)),i),n,a.sub(1),o),ST(VT(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),ST(VT(r,s,i.add(qi(1))),n,a,o.sub(1)),ST(VT(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),ST(VT(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),ST(VT(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return PT(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),kT=uy([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(xT(t.x,r)).toVar(),n=ji(xT(t.y,s)).toVar(),a=ji(DT(i)).toVar(),o=ji(DT(n)).toVar(),u=en(TT(AT(UT(r,s),i,n),AT(UT(r.add(qi(1)),s),i.sub(1),n),AT(UT(r,s.add(qi(1))),i,n.sub(1)),AT(UT(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return MT(u)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(xT(t.x,r)).toVar(),a=ji(xT(t.y,s)).toVar(),o=ji(xT(t.z,i)).toVar(),u=ji(DT(n)).toVar(),l=ji(DT(a)).toVar(),d=ji(DT(o)).toVar(),c=en(_T(AT(UT(r,s,i),n,a,o),AT(UT(r.add(qi(1)),s,i),n.sub(1),a,o),AT(UT(r,s.add(qi(1)),i),n,a.sub(1),o),AT(UT(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),AT(UT(r,s,i.add(qi(1))),n,a,o.sub(1)),AT(UT(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),AT(UT(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),AT(UT(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return PT(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),GT=uy([ki((([e])=>{const t=ji(e).toVar(),r=qi(bT(t)).toVar();return IT(VT(r))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar();return IT(VT(r,s))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar();return IT(VT(r,s,i))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar(),n=qi(bT(t.w)).toVar();return IT(VT(r,s,i,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),zT=uy([ki((([e])=>{const t=ji(e).toVar(),r=qi(bT(t)).toVar();return en(IT(VT(r,qi(0))),IT(VT(r,qi(1))),IT(VT(r,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar();return en(IT(VT(r,s,qi(0))),IT(VT(r,s,qi(1))),IT(VT(r,s,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar();return en(IT(VT(r,s,i,qi(0))),IT(VT(r,s,i,qi(1))),IT(VT(r,s,i,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar(),n=qi(bT(t.w)).toVar();return en(IT(VT(r,s,i,n,qi(0))),IT(VT(r,s,i,n,qi(1))),IT(VT(r,s,i,n,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),HT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=ji(0).toVar(),l=ji(1).toVar();return ch(a,(()=>{u.addAssign(l.mul(OT(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"}]}),$T=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en(0).toVar(),l=ji(1).toVar();return ch(a,(()=>{u.addAssign(l.mul(kT(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"}]}),WT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar();return Yi(HT(o,a,n,i),HT(o.add(en(qi(19),qi(193),qi(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"}]}),jT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en($T(o,a,n,i)).toVar(),l=ji(HT(o.add(en(qi(19),qi(193),qi(17))),a,n,i)).toVar();return nn(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"}]}),qT=uy([ki((([e,t,r,s,i,n,a])=>{const o=qi(a).toVar(),u=ji(n).toVar(),l=qi(i).toVar(),d=qi(s).toVar(),c=qi(r).toVar(),h=qi(t).toVar(),p=Yi(e).toVar(),g=en(zT(Yi(h.add(d),c.add(l)))).toVar(),m=Yi(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Yi(Yi(ji(h),ji(c)).add(m)).toVar(),y=Yi(f.sub(p)).toVar();return Hi(o.equal(qi(2)),(()=>io(y.x).add(io(y.y)))),Hi(o.equal(qi(3)),(()=>To(io(y.x),io(y.y)))),Eo(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"}]}),ki((([e,t,r,s,i,n,a,o,u])=>{const l=qi(u).toVar(),d=ji(o).toVar(),c=qi(a).toVar(),h=qi(n).toVar(),p=qi(i).toVar(),g=qi(s).toVar(),m=qi(r).toVar(),f=qi(t).toVar(),y=en(e).toVar(),b=en(zT(en(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=en(en(ji(f),ji(m),ji(g)).add(b)).toVar(),T=en(x.sub(y)).toVar();return Hi(l.equal(qi(2)),(()=>io(T.x).add(io(T.y)).add(io(T.z)))),Hi(l.equal(qi(3)),(()=>To(io(T.x),io(T.y),io(T.z)))),Eo(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"}]})]),XT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(xT(n.x,a),xT(n.y,o)).toVar(),l=ji(1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(qT(u,e,t,a,o,i,s)).toVar();l.assign(xo(l,r))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),KT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(xT(n.x,a),xT(n.y,o)).toVar(),l=Yi(1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(qT(u,e,t,a,o,i,s)).toVar();Hi(r.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(r)})).ElseIf(r.lessThan(l.y),(()=>{l.y.assign(r)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),YT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(xT(n.x,a),xT(n.y,o)).toVar(),l=en(1e6,1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(qT(u,e,t,a,o,i,s)).toVar();Hi(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)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),QT=uy([XT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(xT(n.x,a),xT(n.y,o),xT(n.z,u)).toVar(),d=ji(1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{ch({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(qT(l,e,t,r,a,o,u,i,s)).toVar();d.assign(xo(d,n))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),ZT=uy([KT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(xT(n.x,a),xT(n.y,o),xT(n.z,u)).toVar(),d=Yi(1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{ch({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(qT(l,e,t,r,a,o,u,i,s)).toVar();Hi(n.lessThan(d.x),(()=>{d.y.assign(d.x),d.x.assign(n)})).ElseIf(n.lessThan(d.y),(()=>{d.y.assign(n)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),JT=uy([YT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(xT(n.x,a),xT(n.y,o),xT(n.z,u)).toVar(),d=en(1e6,1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{ch({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(qT(l,e,t,r,a,o,u,i,s)).toVar();Hi(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)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),e_=ki((([e])=>{const t=e.y,r=e.z,s=en().toVar();return Hi(t.lessThan(1e-4),(()=>{s.assign(en(r,r,r))})).Else((()=>{let i=e.x;i=i.sub(Xa(i)).mul(6).toVar();const n=qi(go(i)),a=i.sub(ji(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());Hi(n.equal(qi(0)),(()=>{s.assign(en(r,l,o))})).ElseIf(n.equal(qi(1)),(()=>{s.assign(en(u,r,o))})).ElseIf(n.equal(qi(2)),(()=>{s.assign(en(o,r,l))})).ElseIf(n.equal(qi(3)),(()=>{s.assign(en(o,u,r))})).ElseIf(n.equal(qi(4)),(()=>{s.assign(en(l,o,r))})).Else((()=>{s.assign(en(r,o,u))}))})),s})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),t_=ki((([e])=>{const t=en(e).toVar(),r=ji(t.x).toVar(),s=ji(t.y).toVar(),i=ji(t.z).toVar(),n=ji(xo(r,xo(s,i))).toVar(),a=ji(To(r,To(s,i))).toVar(),o=ji(a.sub(n)).toVar(),u=ji().toVar(),l=ji().toVar(),d=ji().toVar();return d.assign(a),Hi(a.greaterThan(0),(()=>{l.assign(o.div(a))})).Else((()=>{l.assign(0)})),Hi(l.lessThanEqual(0),(()=>{u.assign(0)})).Else((()=>{Hi(r.greaterThanEqual(a),(()=>{u.assign(s.sub(i).div(o))})).ElseIf(s.greaterThanEqual(a),(()=>{u.assign(oa(2,i.sub(r).div(o)))})).Else((()=>{u.assign(oa(4,r.sub(s).div(o)))})),u.mulAssign(1/6),Hi(u.lessThan(0),(()=>{u.addAssign(1)}))})),en(u,l,d)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),r_=ki((([e])=>{const t=en(e).toVar(),r=sn(ma(t,en(.04045))).toVar(),s=en(t.div(12.92)).toVar(),i=en(Ao(To(t.add(en(.055)),en(0)).div(1.055),en(2.4))).toVar();return Fo(s,i,r)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),s_=(e,t)=>{e=ji(e),t=ji(t);const r=Yi(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Uo(e.sub(r),e.add(r),t)},i_=(e,t,r,s)=>Fo(e,t,r[s].clamp()),n_=(e,t,r,s,i)=>Fo(e,t,s_(r,s[i])),a_=ki((([e,t,r])=>{const s=Ya(e).toVar(),i=ua(ji(.5).mul(t.sub(r)),Ol).div(s).toVar(),n=ua(ji(-.5).mul(t.sub(r)),Ol).div(s).toVar(),a=en().toVar();a.x=s.x.greaterThan(ji(0)).select(i.x,n.x),a.y=s.y.greaterThan(ji(0)).select(i.y,n.y),a.z=s.z.greaterThan(ji(0)).select(i.z,n.z);const o=xo(a.x,a.y,a.z).toVar();return Ol.add(s.mul(o)).toVar().sub(r)})),o_=ki((([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(la(r,r).sub(la(s,s)))),n}));var u_=Object.freeze({__proto__:null,BRDF_GGX:Qp,BRDF_Lambert:Dp,BasicPointShadowFilter:rT,BasicShadowFilter:Ux,Break:hh,Const:tu,Continue:()=>Du("continue").toStack(),DFGApprox:Zp,D_GGX:Xp,Discard:Vu,EPSILON:Fa,F_Schlick:Ip,Fn:ki,INFINITY:Ia,If:Hi,Loop:ch,NodeAccess:Os,NodeShaderStage:Ds,NodeType:Us,NodeUpdateType:Vs,PCFShadowFilter:Ox,PCFSoftShadowFilter:kx,PI:Da,PI2:Va,PointShadowFilter:sT,Return:()=>Du("return").toStack(),Schlick_to_F0:eg,ScriptableNodeResources:$b,ShaderNode:Li,Stack:$i,Switch:(...e)=>ni.Switch(...e),TBNViewMatrix:Xd,VSMShadowFilter:Gx,V_GGX_SmithCorrelated:jp,Var:eu,abs:io,acesFilmicToneMapping:Mb,acos:ro,add:oa,addMethodChaining:oi,addNodeElement:function(e){console.warn("THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:Fb,all:Ua,alphaT:Rn,and:ba,anisotropy:Cn,anisotropyB:Pn,anisotropyT:Mn,any:Oa,append:e=>(console.warn("THREE.TSL: append() has been renamed to Stack()."),$i(e)),array:ea,arrayBuffer:e=>Fi(new si(e,"ArrayBuffer")),asin:to,assign:ra,atan:so,atan2:$o,atomicAdd:(e,t)=>px(cx.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>px(cx.ATOMIC_AND,e,t),atomicFunc:px,atomicLoad:e=>px(cx.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>px(cx.ATOMIC_MAX,e,t),atomicMin:(e,t)=>px(cx.ATOMIC_MIN,e,t),atomicOr:(e,t)=>px(cx.ATOMIC_OR,e,t),atomicStore:(e,t)=>px(cx.ATOMIC_STORE,e,t),atomicSub:(e,t)=>px(cx.ATOMIC_SUB,e,t),atomicXor:(e,t)=>px(cx.ATOMIC_XOR,e,t),attenuationColor:Hn,attenuationDistance:zn,attribute:Hu,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new qy(e,r,s);return ah(i,t,e)},backgroundBlurriness:Jy,backgroundIntensity:eb,backgroundRotation:tb,batch:rh,bentNormalView:Yd,billboarding:gy,bitAnd:va,bitNot:Na,bitOr:Sa,bitXor:Ea,bitangentGeometry:$d,bitangentLocal:Wd,bitangentView:jd,bitangentWorld:qd,bitcast:yo,blendBurn:rp,blendColor:ap,blendDodge:sp,blendOverlay:np,blendScreen:ip,blur:em,bool:Ki,buffer:tl,bufferAttribute:vu,bumpMap:rc,burn:(...e)=>(console.warn('THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.'),rp(e)),bvec2:Ji,bvec3:sn,bvec4:un,bypass:Pu,cache:Cu,call:ia,cameraFar:ul,cameraIndex:al,cameraNear:ol,cameraNormalMatrix:pl,cameraPosition:gl,cameraProjectionMatrix:ll,cameraProjectionMatrixInverse:dl,cameraViewMatrix:cl,cameraWorldMatrix:hl,cbrt:Bo,cdl:bb,ceil:Ka,checker:gT,cineonToneMapping:Rb,clamp:Io,clearcoat:_n,clearcoatNormalView:ed,clearcoatRoughness:vn,code:Vb,color:Wi,colorSpaceToWorking:pu,colorToDirection:e=>Fi(e).mul(2).sub(1),compute:Au,computeSkinning:(e,t=null)=>{const r=new uh(e);return r.positionNode=ah(new L(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(jc).toVar(),r.skinIndexNode=ah(new L(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(jc).toVar(),r.skinWeightNode=ah(new L(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(jc).toVar(),r.bindMatrixNode=Zn(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Zn(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=tl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,Fi(r)},context:Yo,convert:pn,convertColorSpace:(e,t,r)=>Fi(new cu(Fi(e),t,r)),convertToTexture:(e,...t)=>e.isTextureNode?e:e.isPassNode?e.getTextureNode():Gy(e,...t),cos:Ja,cross:wo,cubeTexture:bd,cubeTextureBase:yd,cubeToUV:tT,dFdx:lo,dFdy:co,dashSize:Dn,debug:Gu,decrement:Pa,decrementBefore:Ca,defaultBuildStages:Gs,defaultShaderStages:ks,defined:Pi,degrees:Ga,deltaTime:dy,densityFog:function(e,t){return console.warn('THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),Yb(e,Kb(t))},densityFogFactor:Kb,depth:qh,depthPass:(e,t,r)=>Fi(new Sb(Sb.DEPTH,e,t,r)),difference:So,diffuseColor:yn,directPointLight:hT,directionToColor:xp,directionToFaceDirection:jl,dispersion:$n,distance:No,div:da,dodge:(...e)=>(console.warn('THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.'),sp(e)),dot:Eo,drawIndex:Yc,dynamicBufferAttribute:Nu,element:hn,emissive:bn,equal:ha,equals:bo,equirectUV:vp,exp:za,exp2:Ha,expression:Du,faceDirection:Wl,faceForward:Oo,faceforward:Wo,float:ji,floor:Xa,fog:Yb,fract:Qa,frameGroup:Xn,frameId:cy,frontFacing:$l,fwidth:mo,gain:(e,t)=>e.lessThan(.5)?ry(e.mul(2),t).div(2):ua(1,ry(la(ua(1,e),2),t).div(2)),gapSize:Vn,getConstNodeType:Bi,getCurrentStack:zi,getDirection:Yg,getDistanceAttenuation:cT,getGeometryRoughness:$p,getNormalFromDepth:$y,getParallaxCorrectNormal:a_,getRoughness:Wp,getScreenPosition:Hy,getShIrradianceAt:o_,getShadowMaterial:Hx,getShadowRenderObjectFunction:jx,getTextureIndex:Zf,getViewPosition:zy,globalId:nx,glsl:(e,t)=>Vb(e,t,"glsl"),glslFn:(e,t)=>Ob(e,t,"glsl"),grayscale:pb,greaterThan:ma,greaterThanEqual:ya,hash:ty,highpModelNormalViewMatrix:Il,highpModelViewMatrix:Fl,hue:fb,increment:Ma,incrementBefore:Ra,instance:Zc,instanceIndex:jc,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new jy(e,r,s);return ah(i,t,e)},instancedBufferAttribute:Su,instancedDynamicBufferAttribute:Eu,instancedMesh:eh,int:qi,inverseSqrt:qa,inversesqrt:jo,invocationLocalIndex:Kc,invocationSubgroupIndex:Xc,ior:On,iridescence:En,iridescenceIOR:wn,iridescenceThickness:An,ivec2:Qi,ivec3:tn,ivec4:an,js:(e,t)=>Vb(e,t,"js"),label:Qo,length:ao,lengthSq:Lo,lessThan:ga,lessThanEqual:fa,lightPosition:bx,lightProjectionUV:yx,lightShadowMatrix:fx,lightTargetDirection:_x,lightTargetPosition:xx,lightViewPosition:Tx,lightingContext:_h,lights:(e=[])=>Fi(new Ex).setLights(e),linearDepth:Xh,linearToneMapping:wb,localId:ax,log:$a,log2:Wa,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul($a(r.div(t)));return ji(Math.E).pow(s).mul(t).negate()},luminance:yb,mat2:ln,mat3:dn,mat4:cn,matcapUV:Gm,materialAO:Gc,materialAlphaTest:nc,materialAnisotropy:Sc,materialAnisotropyVector:zc,materialAttenuationColor:Bc,materialAttenuationDistance:Pc,materialClearcoat:bc,materialClearcoatNormal:Tc,materialClearcoatRoughness:xc,materialColor:ac,materialDispersion:Oc,materialEmissive:uc,materialEnvIntensity:ld,materialEnvRotation:dd,materialIOR:Mc,materialIridescence:Ec,materialIridescenceIOR:wc,materialIridescenceThickness:Ac,materialLightMap:kc,materialLineDashOffset:Vc,materialLineDashSize:Fc,materialLineGapSize:Ic,materialLineScale:Lc,materialLineWidth:Dc,materialMetalness:fc,materialNormal:yc,materialOpacity:lc,materialPointSize:Uc,materialReference:Sd,materialReflectivity:gc,materialRefractionRatio:ud,materialRotation:_c,materialRoughness:mc,materialSheen:vc,materialSheenRoughness:Nc,materialShininess:oc,materialSpecular:dc,materialSpecularColor:hc,materialSpecularIntensity:cc,materialSpecularStrength:pc,materialThickness:Cc,materialTransmission:Rc,max:To,maxMipLevel:Xu,mediumpModelViewMatrix:Ll,metalness:Tn,min:xo,mix:Fo,mixElement:Go,mod:ca,modInt:Ba,modelDirection:Sl,modelNormalMatrix:Ml,modelPosition:wl,modelRadius:Cl,modelScale:Al,modelViewMatrix:Bl,modelViewPosition:Rl,modelViewProjection:Hc,modelWorldMatrix:El,modelWorldMatrixInverse:Pl,morphReference:yh,mrt:ey,mul:la,mx_aastep:s_,mx_cell_noise_float:(e=$u())=>GT(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>ji(e).sub(r).mul(t).add(r),mx_fractal_noise_float:(e=$u(),t=3,r=2,s=.5,i=1)=>HT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec2:(e=$u(),t=3,r=2,s=.5,i=1)=>WT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec3:(e=$u(),t=3,r=2,s=.5,i=1)=>$T(e,qi(t),r,s).mul(i),mx_fractal_noise_vec4:(e=$u(),t=3,r=2,s=.5,i=1)=>jT(e,qi(t),r,s).mul(i),mx_hsvtorgb:e_,mx_noise_float:(e=$u(),t=1,r=0)=>OT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=$u(),t=1,r=0)=>kT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=$u(),t=1,r=0)=>{e=e.convert("vec2|vec3");return nn(kT(e),OT(e.add(Yi(19,73)))).mul(t).add(r)},mx_ramplr:(e,t,r=$u())=>i_(e,t,r,"x"),mx_ramptb:(e,t,r=$u())=>i_(e,t,r,"y"),mx_rgbtohsv:t_,mx_safepower:(e,t=1)=>(e=ji(e)).abs().pow(t).mul(e.sign()),mx_splitlr:(e,t,r,s=$u())=>n_(e,t,r,s,"x"),mx_splittb:(e,t,r,s=$u())=>n_(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:r_,mx_transform_uv:(e=1,t=0,r=$u())=>r.mul(e).add(t),mx_worley_noise_float:(e=$u(),t=1)=>QT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec2:(e=$u(),t=1)=>ZT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec3:(e=$u(),t=1)=>JT(e.convert("vec2|vec3"),t,qi(1)),negate:oo,neutralToneMapping:Ib,nodeArray:Di,nodeImmutable:Ui,nodeObject:Fi,nodeObjects:Ii,nodeProxy:Vi,normalFlat:Kl,normalGeometry:ql,normalLocal:Xl,normalMap:Zd,normalView:Zl,normalViewGeometry:Yl,normalWorld:Jl,normalWorldGeometry:Ql,normalize:Ya,not:Ta,notEqual:pa,numWorkgroups:sx,objectDirection:yl,objectGroup:Yn,objectPosition:xl,objectRadius:vl,objectScale:Tl,objectViewPosition:_l,objectWorldMatrix:bl,oneMinus:uo,or:xa,orthographicDepthToViewZ:(e,t,r)=>t.sub(r).mul(e).sub(t),oscSawtooth:(e=ly)=>e.fract(),oscSine:(e=ly)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=ly)=>e.fract().round(),oscTriangle:(e=ly)=>e.add(.5).fract().mul(2).sub(1).abs(),output:In,outputStruct:Qf,overlay:(...e)=>(console.warn('THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),np(e)),overloadingFn:uy,parabola:ry,parallaxDirection:Kd,parallaxUV:(e,t)=>e.sub(Kd.mul(t)),parameter:(e,t)=>Fi(new Wf(e,t)),pass:(e,t,r)=>Fi(new Sb(Sb.COLOR,e,t,r)),passTexture:(e,t)=>Fi(new vb(e,t)),pcurve:(e,t,r)=>Ao(da(Ao(e,t),oa(Ao(e,t),Ao(ua(1,e),r))),1/t),perspectiveDepthToViewZ:$h,pmremTexture:wm,pointShadow:lT,pointUV:Ky,pointWidth:Un,positionGeometry:Dl,positionLocal:Vl,positionPrevious:Ul,positionView:Gl,positionViewDirection:zl,positionWorld:Ol,positionWorldDirection:kl,posterize:Tb,pow:Ao,pow2:Ro,pow3:Co,pow4:Mo,premultiplyAlpha:op,property:mn,radians:ka,rand:ko,range:ex,rangeFog:function(e,t,r){return console.warn('THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),Yb(e,Xb(t,r))},rangeFogFactor:Xb,reciprocal:po,reference:_d,referenceBuffer:vd,reflect:vo,reflectVector:pd,reflectView:cd,reflector:e=>Fi(new Ly(e)),refract:Vo,refractVector:gd,refractView:hd,reinhardToneMapping:Ab,remap:Lu,remapClamp:Fu,renderGroup:Kn,renderOutput:Ou,rendererReference:yu,rotate:Wm,rotateUV:hy,roughness:xn,round:ho,rtt:Gy,sRGBTransferEOTF:uu,sRGBTransferOETF:lu,sample:e=>Fi(new Wy(e)),sampler:e=>(!0===e.isNode?e:Zu(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Zu(e)).convert("samplerComparison"),saturate:Do,saturation:gb,screen:(...e)=>(console.warn('THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.'),ip(e)),screenCoordinate:Rh,screenSize:Ah,screenUV:wh,scriptable:jb,scriptableValue:Gb,select:Xo,setCurrentStack:Gi,shaderStages:zs,shadow:Jx,shadowPositionWorld:Ax,shapeCircle:mT,sharedUniformGroup:qn,sheen:Nn,sheenRoughness:Sn,shiftLeft:wa,shiftRight:Aa,shininess:Fn,sign:no,sin:Za,sinc:(e,t)=>Za(Da.mul(t.mul(e).sub(1))).div(Da.mul(t.mul(e).sub(1))),skinning:lh,smoothstep:Uo,smoothstepElement:zo,specularColor:Bn,specularF90:Ln,spherizeUV:py,split:(e,t)=>Fi(new Zs(Fi(e),t)),spritesheetUV:yy,sqrt:ja,stack:qf,step:_o,stepElement:Ho,storage:ah,storageBarrier:()=>ux("storage").toStack(),storageObject:(e,t,r)=>(console.warn('THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),ah(e,t,r).setPBO(!0)),storageTexture:sb,string:(e="")=>Fi(new si(e,"string")),struct:(e,t=null)=>{const r=new Xf(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;eux("texture").toStack(),textureBicubic:Tg,textureBicubicLevel:xg,textureCubeUV:Qg,textureLoad:Ju,textureSize:ju,textureStore:(e,t,r)=>{const s=sb(e,t,r);return null!==r&&s.toStack(),s},thickness:Gn,time:ly,timerDelta:(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),dy.mul(e)),timerGlobal:(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),ly.mul(e)),timerLocal:(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),ly.mul(e)),toneMapping:xu,toneMappingExposure:Tu,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>Fi(new Eb(t,r,Fi(s),Fi(i),Fi(n))),transformDirection:Po,transformNormal:td,transformNormalToView:rd,transformedClearcoatNormalView:nd,transformedNormalView:sd,transformedNormalWorld:id,transmission:kn,transpose:fo,triNoise3D:ny,triplanarTexture:(...e)=>by(...e),triplanarTextures:by,trunc:go,uint:Xi,uniform:Zn,uniformArray:il,uniformCubeTexture:(e=md)=>yd(e),uniformGroup:jn,uniformTexture:(e=Ku)=>Zu(e),unpremultiplyAlpha:up,userData:(e,t,r)=>Fi(new ob(e,t,r)),uv:$u,uvec2:Zi,uvec3:rn,uvec4:on,varying:au,varyingProperty:fn,vec2:Yi,vec3:en,vec4:nn,vectorComponents:Hs,velocity:hb,vertexColor:tp,vertexIndex:Wc,vertexStage:ou,vibrance:mb,viewZToLogarithmicDepth:Wh,viewZToOrthographicDepth:zh,viewZToPerspectiveDepth:Hh,viewport:Ch,viewportCoordinate:Ph,viewportDepthTexture:kh,viewportLinearDepth:Kh,viewportMipTexture:Vh,viewportResolution:Lh,viewportSafeUV:my,viewportSharedTexture:fp,viewportSize:Mh,viewportTexture:Dh,viewportUV:Bh,wgsl:(e,t)=>Vb(e,t,"wgsl"),wgslFn:(e,t)=>Ob(e,t,"wgsl"),workgroupArray:(e,t)=>Fi(new dx("Workgroup",e,t)),workgroupBarrier:()=>ux("workgroup").toStack(),workgroupId:ix,workingToColorSpace:hu,xor:_a});const l_=new $f;class d_ extends cf{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(l_),l_.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(l_),l_.a=1,n=!0;else if(!0===i.isNode){const o=this.get(e),u=i;l_.copy(s._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=Yo(nn(u).mul(eb),{getUV:()=>tb.mul(Ql),getTextureLevel:()=>Jy});let h=Hc;h=h.setZ(h.w);const p=new lp;function g(){i.removeEventListener("dispose",g),l.material.dispose(),l.geometry.dispose()}p.name="Background.material",p.side=S,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=h,p.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new X(new Oe(1,32,32),p),l.frustumCulled=!1,l.name="Background.mesh",l.onBeforeRender=function(e,t,r){this.matrixWorld.copyPosition(r.matrixWorld)},i.addEventListener("dispose",g)}const d=u.getCacheKey();o.backgroundCacheKey!==d&&(o.backgroundMeshNode.node=nn(u).mul(eb),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=d),t.unshift(l,l.geometry,l.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?l_.set(0,0,0,1):"alpha-blend"===a&&l_.set(0,0,0,0),!0===s.autoClear||!0===n){const m=r.clearColorValue;m.r=l_.r,m.g=l_.g,m.b=l_.b,m.a=l_.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),r.depthClearValue=s._clearDepth,r.stencilClearValue=s._clearStencil,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 c_=0;class h_{constructor(e="",t=[],r=0,s=[]){this.name=e,this.bindings=t,this.index=r,this.bindingsReference=s,this.id=c_++}}class p_{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 h_(t.name,[],t.index,t);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class g_{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class m_{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class f_{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class y_ extends f_{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class b_{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let x_=0;class T_{constructor(e=null){this.id=x_++,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 __{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class v_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class N_ extends v_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class S_ extends v_{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class E_ extends v_{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class w_ extends v_{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class A_ extends v_{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class R_ extends v_{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class C_ extends v_{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class M_ extends v_{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class P_ extends N_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class B_ extends S_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class L_ extends E_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class F_ extends w_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class I_ extends A_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class D_ extends R_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class V_ extends C_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class U_ extends M_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const O_=new WeakMap,k_=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),G_=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class z_{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.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=qf(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new T_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=O_.get(this.renderer);return void 0===e&&(e=new af,O_.set(this.renderer,e)),e}createRenderTarget(e,t,r){return new ue(e,t,r)}createCubeRenderTarget(e,t){return new Np(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=this.getBindGroupsCache(),s=[];let i,n=!0;for(const e of t)s.push(e),n=n&&!0!==e.groupNode.shared;return n?(i=r.get(s),void 0===i&&(i=new h_(e,s,this.bindingsIndexes[e].group,s),r.set(s,i))):i=new h_(e,s,this.bindingsIndexes[e].group,s),i}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 zs)for(const s in r[e]){const i=r[e][s];(t[s]||(t[s]=[])).push(...i)}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")}( ${G_(n.r)}, ${G_(n.g)}, ${G_(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 g_(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===_)return"int";if(t===T)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=Es(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return k_.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 ze||!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")}addStack(){return this.stack=qf(this.stack),this.stacks.push(zi()||this.stack),Gi(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Gi(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);let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new g_("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}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 e=this.structs.index++;null===r&&(r="StructType"+e),n=new __(r,t),this.structs[s].push(n),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 m_(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,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=this.getArrayCount(e);o=new f_(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 y_(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,console.warn(`THREE.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 b_("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 Ub,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 Wf(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,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 T_,this.stack=qf();for(const r of Gs)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(){console.warn("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(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e){let t="";const r=this.vars[e];if(void 0!==r)for(const e of r)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("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(){console.warn("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}build(){const{object:e,material:t,renderer:r}=this;if(null!==t){let e=r.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new lp),e.build(this)}else this.addFlow("compute",e);for(const e of Gs){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of zs){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}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new P_(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new B_(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new L_(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new F_(e);if("color"===t)return new I_(e);if("mat2"===t)return new D_(e);if("mat3"===t)return new V_(e);if("mat4"===t)return new U_(e);throw new Error(`Uniform "${t}" not declared.`)}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${He} - Node System\n`}*[Symbol.iterator](){}}class H_{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.frameId&&!1!==e.update(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.renderId&&!1!==e.update(this)&&t.set(r,this.renderId)}else t===Vs.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 $_{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}$_.isNodeFunctionInput=!0;class W_ extends dT{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:_x(this.light),lightColor:e}}}const j_=new a,q_=new a;let X_=null;class K_ extends dT{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Zn(new r).setGroup(Kn),this.halfWidth=Zn(new r).setGroup(Kn),this.updateType=Vs.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;q_.identity(),j_.copy(t.matrixWorld),j_.premultiply(r),q_.extractRotation(j_),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(q_),this.halfHeight.value.applyMatrix4(q_)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Zu(X_.LTC_FLOAT_1),r=Zu(X_.LTC_FLOAT_2)):(t=Zu(X_.LTC_HALF_1),r=Zu(X_.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:Tx(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){X_=e}}class Y_ extends dT{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Zn(0).setGroup(Kn),this.penumbraCosNode=Zn(0).setGroup(Kn),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(0).setGroup(Kn),this.colorNode=Zn(this.color).setGroup(Kn)}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 Uo(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=yx(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(_x(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=cT({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=Zu(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 Q_ extends Y_{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=Zu(r,Yi(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}const Z_=ki((([e,t])=>{const r=e.abs().sub(t);return ao(To(r,0)).add(xo(To(r.x,r.y),0))}));class J_ extends Y_{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=this.penumbraCosNode,r=this.getLightCoord(e),s=r.xyz.div(r.w),i=Z_(s.xy.sub(Yi(.5)),Yi(.5)),n=da(-1,ua(1,ro(t)).sub(1));return Do(i.mul(-2).mul(n))}}class ev extends dT{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class tv extends dT{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=bx(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Zn(new e).setGroup(Kn)}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=Jl.dot(s).mul(.5).add(.5),n=Fo(r,t,i);e.context.irradiance.addAssign(n)}}class rv extends dT{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=il(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=o_(Jl,this.lightProbe);e.context.irradiance.addAssign(t)}}class sv{parseFunction(){console.warn("Abstract function.")}}class iv{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){console.warn("Abstract function.")}}iv.isNodeFunction=!0;const nv=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,av=/[a-z_0-9]+/gi,ov="#pragma main";class uv extends iv{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(ov),r=-1!==t?e.slice(t+12):e,s=r.match(nv);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=av.exec(i));)n.push(a);const o=[];let u=0;for(;u0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,(()=>{if(!0===r.isCubeTexture||r.mapping===Z||r.mapping===J||r.mapping===he){if(e.backgroundBlurriness>0||r.mapping===he)return wm(r);{let e;return e=!0===r.isCubeTexture?bd(r):Zu(r),Rp(e)}}if(!0===r.isTexture)return Zu(r,wh.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&console.error("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=_d("color","color",r).setGroup(Kn),t=_d("density","float",r).setGroup(Kn);return Yb(e,Kb(t))}if(r.isFog){const e=_d("color","color",r).setGroup(Kn),t=_d("near","float",r).setGroup(Kn),s=_d("far","float",r).setGroup(Kn);return Yb(e,Xb(t,s))}console.error("THREE.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?bd(r):!0===r.isTexture?Zu(r):void console.error("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}hasOutputChange(e){return dv.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,r=this.getOutputCacheKey(),s=e.isArrayTexture?ab(e,en(wh,nl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Zu(e,wh).renderOutput(t.toneMapping,t.currentColorSpace);return dv.set(e,r),s}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 H_,this.nodeBuilderCache=new Map,this.cacheLib={}}}const gv=new Me;class mv{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;i0,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 Nv(i.framebufferWidth,i.framebufferHeight,{format:de,type:Ce,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),n.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,i.layers.mask=n.layers.mask|a.layers.mask;const o=e.parent,u=i.cameras;Av(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 Pv(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 Bv(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(e,t,this._renderTarget),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(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 pv(this,r),this._animation=new nf(this._nodes,this.info),this._attributes=new yf(r),this._background=new d_(this,this._nodes),this._geometries=new Tf(this._attributes,this.info),this._textures=new Hf(this,r,this.info),this._pipelines=new Af(r,this._nodes),this._bindings=new Rf(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new df(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Ff(this.lighting),this._bundles=new bv,this._renderContexts=new Gf,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}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._compilationPromises,u=!0===e.isScene?e:Lv;null===r&&(r=e);const l=this._renderTarget,d=this._renderContexts.get(r,t,l),c=this._activeMipmapLevel,h=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,s.renderId++,s.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new mv),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,d.clippingContext),r!==e&&r.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);d.textures=e.textures,d.depthTexture=e.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(u,p,d);const g=p.opaque,m=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,y),!0===this.transparent&&m.length>0&&this._renderTransparents(m,f,t,u,y),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=Fl,this.overrideNodes.modelNormalViewMatrix=Il):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===Fl&&this.overrideNodes.modelNormalViewMatrix===Il}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i),u=this.backend.get(o);void 0===u.renderContexts&&(u.renderContexts=new Set);const l=s.version!==u.version,d=!1===u.renderContexts.has(a)||l;if(u.renderContexts.add(a),d){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>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=T,p.viewport=!1===p.viewportValue.equals(Iv),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Iv),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new mv),p.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const _=t.isArrayCamera?Vv:Dv;t.isArrayCamera||(Uv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_.setFromProjectionMatrix(Uv,g));const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,p.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=h,p.depth=h.depthBuffer,p.stencil=h.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=d,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._background.update(u,v,p),p.camera=t,this.backend.beginRender(p);const{bundles:N,lightsNode:S,transparentDoublePass:E,transparent:w,opaque:A}=v;return N.length>0&&this._renderBundles(N,u,S),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,S),!0===this.transparent&&w.length>0&&this._renderTransparents(w,E,t,u,S),this.backend.finishRender(p),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==s&&(this.setRenderTarget(l,d,c),this._renderOutput(h)),u.onAfterRender(this,e,t,h),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,r);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.getForClear(s),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,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){!1===this._initialized&&await this.init(),this.clear(e,t,r)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:p}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:le}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,r=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const s=this.backend,i=this._pipelines,n=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(const t of o){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),n.delete(t),a.delete(t)};t.addEventListener("dispose",e);const r=t.onInitFunction;null!==r&&r.call(t,{renderer:this})}a.updateForCompute(t),n.updateForCompute(t);const r=n.getForCompute(t),o=i.getForCompute(t,r);s.compute(e,t,r,o)}s.finishCompute(e),t.renderId=r}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=Ov.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Ov.copy(t).floor()}else t=Ov.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)}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)}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?Vv:Dv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&Ov.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Uv);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,Ov.z,null,i)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?Vv:Dv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Ov.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(Uv)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=S;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=je;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=E}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(c=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(d=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(l=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&i.side===E&&!1===i.forceSinglePass?(i.side=S,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=je,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=E):this._handleObjectFunction(e,i,t,r,a,n,o,u),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==d&&(t.overrideMaterial.colorNode=d),e.onAfterRender(this,t,r,s,i,n)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n;const l=this._nodes.needsRefresh(u);if(l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u)}_createObjectPipeline(e,t,r,s,i,n,a,o){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)}get compile(){return this.compileAsync}}class Gv{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class zv extends Gv{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(ff-e%ff)%ff;var e}get buffer(){return this._buffer}update(){return!0}}class Hv extends zv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let $v=0;class Wv extends Hv{constructor(e,t){super("UniformBuffer_"+$v++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class jv extends Hv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r0?s:"";t=`${e.name} {\n\t${r} ${i.name}[${n}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,n=!0}const a=i.node.precision;if(null!==a&&(t=tN[a]+" "+t),n){t="\t"+t;const e=i.groupNode.name;(s[e]||(s[e]=[])).push(t)}else t="uniform "+t,r.push(t)}let i="";for(const t in s){const r=s[t];i+=this._getGLSLUniformStruct(e+"_"+t,r.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==_){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+=`${sN[s.interpolationType]||s.interpolationType} ${iN[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+=`${sN[e.interpolationType]||e.interpolationType} ${iN[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`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,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=rN[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)}rN[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];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r}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 Qv(i.name,i.node,s),u.push(a);else if("cubeTexture"===t)a=new Zv(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new Jv(i.name,i.node,s),u.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new Wv(e,s);t.name=e.name,u.push(t),a=t}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let n=e[o];void 0===n&&(n=new Xv(r+"_"+o,s),e[o]=n,u.push(n)),a=this.getNodeUniform(i,t),n.addUniform(a)}n.uniformGPU=a}return i}}let oN=null,uN=null;class lN{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void pt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void pt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return oN=oN||new t,this.renderer.getDrawingBufferSize(oN)}setScissorTest(){}getClearColor(){const e=this.renderer;return uN=uN||new $f,e.getClearColor(uN),uN.getRGB(uN),uN}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${He} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let dN,cN,hN=0;class pN{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 gN{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(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===_,id:hN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new pN(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;e1?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 yN,bN,xN,TN=!1;class _N{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===TN&&(this._init(),TN=!0)}_init(){const e=this.gl;yN={[Nr]:e.REPEAT,[vr]:e.CLAMP_TO_EDGE,[_r]:e.MIRRORED_REPEAT},bN={[v]:e.NEAREST,[Sr]:e.NEAREST_MIPMAP_NEAREST,[Ge]:e.NEAREST_MIPMAP_LINEAR,[Y]:e.LINEAR,[ke]:e.LINEAR_MIPMAP_NEAREST,[V]:e.LINEAR_MIPMAP_LINEAR},xN={[Pr]:e.NEVER,[Mr]:e.ALWAYS,[De]:e.LESS,[Cr]:e.LEQUAL,[Rr]:e.EQUAL,[Ar]:e.GEQUAL,[wr]:e.GREATER,[Er]: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=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(r===n.FLOAT&&(o=n.R32F),r===n.HALF_FLOAT&&(o=n.R16F),r===n.UNSIGNED_BYTE&&(o=n.R8),r===n.UNSIGNED_SHORT&&(o=n.R16),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.R8UI),r===n.UNSIGNED_SHORT&&(o=n.R16UI),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RG&&(r===n.FLOAT&&(o=n.RG32F),r===n.HALF_FLOAT&&(o=n.RG16F),r===n.UNSIGNED_BYTE&&(o=n.RG8),r===n.UNSIGNED_SHORT&&(o=n.RG16),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RG8UI),r===n.UNSIGNED_SHORT&&(o=n.RG16UI),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RGB){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGB32F),r===n.HALF_FLOAT&&(o=n.RGB16F),r===n.UNSIGNED_BYTE&&(o=n.RGB8),r===n.UNSIGNED_SHORT&&(o=n.RGB16),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8:n.RGB8),r===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),r===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5)}if(t===n.RGB_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGB8UI),r===n.UNSIGNED_SHORT&&(o=n.RGB16UI),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGBA32F),r===n.HALF_FLOAT&&(o=n.RGBA16F),r===n.UNSIGNED_BYTE&&(o=n.RGBA8),r===n.UNSIGNED_SHORT&&(o=n.RGBA16),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8_ALPHA8:n.RGBA8),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),r===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(r===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),r===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),r===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&r===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,n=c.getPrimaries(c.workingColorSpace),a=t.colorSpace===b?null:c.getPrimaries(t.colorSpace),o=t.colorSpace===b||n===a?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),r.texParameteri(e,r.TEXTURE_WRAP_S,yN[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,yN[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,yN[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,bN[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,l=t.minFilter===Y&&u?V:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,bN[l]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,xN[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===v)return;if(t.minFilter!==Ge&&t.minFilter!==V)return;if(t.type===I&&!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.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,isDefault:!0})}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.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,{textureGPU:i,glTextureType:n,glFormat:a,glType:o}=s.get(t),{width:u,height:l}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(n,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(n,0,0,0,u,l,a,o,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,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();o.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),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}}function vN(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 NN{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 SN{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const EN={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class wN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const 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){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,r]of this.queryStates)if("ended"===r){const r=this.queries[t];e.push(this.resolveQuery(r))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let 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){console.error("Error checking query:",e),t(this.lastValue)}};n()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}const CN=new t;class MN extends lN{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.samples>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 NN(this),this.capabilities=new SN(this),this.attributeUtils=new gN(this),this.textureUtils=new _N(this),this.bufferRenderer=new wN(this),this.state=new mN(this),this.utils=new fN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return l}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,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&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new RN(this.gl,t,2048));const r=this.timestampQueryPool[t];null!==r.allocateQueriesForContext(e)&&r.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize(CN);t.viewport(0,0,e,r)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}this.initTimestampQuery(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;e0&&!1===this._useMultisampledExtension(o)){const i=s.framebuffers[e.getCacheKey()];let n=t.COLOR_BUFFER_BIT;o.resolveDepthBuffer&&(o.depthBuffer&&(n|=t.DEPTH_BUFFER_BIT),o.stencilBuffer&&o.resolveStencilBuffer&&(n|=t.STENCIL_BUFFER_BIT));const a=s.msaaFrameBuffer,u=s.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,a),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),d)for(let e=0;e{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(pt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):pt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?b.renderInstances(_,x,T):b.render(_,x)};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()}));t.push(i)}else 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");console.error("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&&console.warn("THREE.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})}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;eEN[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=Vf(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;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,0)}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&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const PN="point-list",BN="line-list",LN="line-strip",FN="triangle-list",IN="triangle-strip",DN="never",VN="less",UN="equal",ON="less-equal",kN="greater",GN="not-equal",zN="greater-equal",HN="always",$N="store",WN="load",jN="clear",qN="ccw",XN="none",KN="front",YN="back",QN="uint16",ZN="uint32",JN="r8unorm",eS="r8snorm",tS="r8uint",rS="r8sint",sS="r16uint",iS="r16sint",nS="r16float",aS="rg8unorm",oS="rg8snorm",uS="rg8uint",lS="rg8sint",dS="r32uint",cS="r32sint",hS="r32float",pS="rg16uint",gS="rg16sint",mS="rg16float",fS="rgba8unorm",yS="rgba8unorm-srgb",bS="rgba8snorm",xS="rgba8uint",TS="rgba8sint",_S="bgra8unorm",vS="bgra8unorm-srgb",NS="rgb9e5ufloat",SS="rgb10a2unorm",ES="rgb10a2unorm",wS="rg32uint",AS="rg32sint",RS="rg32float",CS="rgba16uint",MS="rgba16sint",PS="rgba16float",BS="rgba32uint",LS="rgba32sint",FS="rgba32float",IS="depth16unorm",DS="depth24plus",VS="depth24plus-stencil8",US="depth32float",OS="depth32float-stencil8",kS="bc1-rgba-unorm",GS="bc1-rgba-unorm-srgb",zS="bc2-rgba-unorm",HS="bc2-rgba-unorm-srgb",$S="bc3-rgba-unorm",WS="bc3-rgba-unorm-srgb",jS="bc4-r-unorm",qS="bc4-r-snorm",XS="bc5-rg-unorm",KS="bc5-rg-snorm",YS="bc6h-rgb-ufloat",QS="bc6h-rgb-float",ZS="bc7-rgba-unorm",JS="bc7-rgba-srgb",eE="etc2-rgb8unorm",tE="etc2-rgb8unorm-srgb",rE="etc2-rgb8a1unorm",sE="etc2-rgb8a1unorm-srgb",iE="etc2-rgba8unorm",nE="etc2-rgba8unorm-srgb",aE="eac-r11unorm",oE="eac-r11snorm",uE="eac-rg11unorm",lE="eac-rg11snorm",dE="astc-4x4-unorm",cE="astc-4x4-unorm-srgb",hE="astc-5x4-unorm",pE="astc-5x4-unorm-srgb",gE="astc-5x5-unorm",mE="astc-5x5-unorm-srgb",fE="astc-6x5-unorm",yE="astc-6x5-unorm-srgb",bE="astc-6x6-unorm",xE="astc-6x6-unorm-srgb",TE="astc-8x5-unorm",_E="astc-8x5-unorm-srgb",vE="astc-8x6-unorm",NE="astc-8x6-unorm-srgb",SE="astc-8x8-unorm",EE="astc-8x8-unorm-srgb",wE="astc-10x5-unorm",AE="astc-10x5-unorm-srgb",RE="astc-10x6-unorm",CE="astc-10x6-unorm-srgb",ME="astc-10x8-unorm",PE="astc-10x8-unorm-srgb",BE="astc-10x10-unorm",LE="astc-10x10-unorm-srgb",FE="astc-12x10-unorm",IE="astc-12x10-unorm-srgb",DE="astc-12x12-unorm",VE="astc-12x12-unorm-srgb",UE="clamp-to-edge",OE="repeat",kE="mirror-repeat",GE="linear",zE="nearest",HE="zero",$E="one",WE="src",jE="one-minus-src",qE="src-alpha",XE="one-minus-src-alpha",KE="dst",YE="one-minus-dst",QE="dst-alpha",ZE="one-minus-dst-alpha",JE="src-alpha-saturated",ew="constant",tw="one-minus-constant",rw="add",sw="subtract",iw="reverse-subtract",nw="min",aw="max",ow=0,uw=15,lw="keep",dw="zero",cw="replace",hw="invert",pw="increment-clamp",gw="decrement-clamp",mw="increment-wrap",fw="decrement-wrap",yw="storage",bw="read-only-storage",xw="write-only",Tw="read-only",_w="read-write",vw="non-filtering",Nw="comparison",Sw="float",Ew="unfilterable-float",ww="depth",Aw="sint",Rw="uint",Cw="2d",Mw="3d",Pw="2d",Bw="2d-array",Lw="cube",Fw="3d",Iw="all",Dw="vertex",Vw="instance",Uw={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class Ow extends Gv{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class kw extends Ow{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){this.texture=this.textureNode.value}}class Gw extends zv{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let zw=0;class Hw extends Gw{constructor(e,t){super("StorageBuffer_"+zw++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Os.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class $w extends cf{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:GE}),this.flipYSampler=e.createSampler({minFilter:zE}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:IN,stripIndexFormat:ZN},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:IN,stripIndexFormat:ZN},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.getTransferPipeline(s),o=this.getFlipYPipeline(s),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:Pw,baseArrayLayer:r}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:Pw,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,r)=>{const s=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:r,loadOp:jN,storeOp:$N,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(a,l,d),h(o,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,r=0){const s=this.get(e);void 0===s.useCount&&(s.useCount=0,s.layers=[]);const i=s.layers[r]||this._mipmapCreateBundles(e,t,r),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,i),this.device.queue.submit([n.finish()]),0!==s.useCount&&(s.layers[r]=i),s.useCount++}_mipmapCreateBundles(e,t,r){const s=this.getTransferPipeline(t.format),i=s.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:Pw,baseArrayLayer:r});const a=[];for(let o=1;o1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,Yw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,Qw={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 Zw extends iv{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(Kw);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=Yw.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 Jw extends sv{parseFunction(e){return new Zw(e)}}const eA="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},tA={[Os.READ_ONLY]:"read",[Os.WRITE_ONLY]:"write",[Os.READ_WRITE]:"read_write"},rA={[Nr]:"repeat",[vr]:"clamp",[_r]:"mirror"},sA={vertex:eA?eA.VERTEX:1,fragment:eA?eA.FRAGMENT:2,compute:eA?eA.COMPUTE:4},iA={instance:!0,swizzleAssign:!1,storageBuffer:!0},nA={"^^":"tsl_xor"},aA={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"},oA={},uA={tsl_xor:new Db("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Db("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Db("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Db("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Db("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Db("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Db("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Db("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 Db("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 Db("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Db("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 Db("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Db("\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")},lA={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"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(uA.pow_float=new Db("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),uA.pow_vec2=new Db("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[uA.pow_float]),uA.pow_vec3=new Db("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[uA.pow_float]),uA.pow_vec4=new Db("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[uA.pow_float]),lA.pow_float="tsl_pow_float",lA.pow_vec2="tsl_pow_vec2",lA.pow_vec3="tsl_pow_vec3",lA.pow_vec4="tsl_pow_vec4");let dA="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(dA+="diagnostic( off, derivative_uniformity );\n");class cA extends z_{constructor(e,t){super(e,t,new Jw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==b}_generateTextureSample(e,t,r,s,i=this.shaderStage){return"fragment"===i?s?`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this._generateTextureSampleLevel(e,t,r,"0",s)}_generateVideoSample(e,t,r=this.shaderStage){if("fragment"===r)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${r} shader.`)}_generateTextureSampleLevel(e,t,r,s,i){return!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,s):this.generateTextureLod(e,t,r,i,s)}generateWrapFunction(e){const t=`tsl_coord_${rA[e.wrapS]}S_${rA[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let r=oA[t];if(void 0===r){const s=[],i=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===Nr?(s.push(uA.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===vr?(s.push(uA.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===_r?(s.push(uA.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",oA[t]=r=new Db(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.globalCache);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.isData3DTexture?"vec3":"vec2",n=u||e.isVideoTexture||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Zo(new Iu(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Zo(new Iu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Zo(new Iu("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${r} ), ${this.generateTextureDimension(e,t,s)}, u32( ${s} ) )`}generateTextureLod(e,t,r,s,i="0u"){const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i),o=e.isData3DTexture?"vec3":"vec2",u=`${o}( ${n}( ${r} ) * ${o}( ${a} ) )`;return this.generateTextureLoad(e,t,u,s,i)}generateTextureLoad(e,t,r,s,i="0u"){let n;return!0===e.isVideoTexture?n=`textureLoad( ${t}, ${r} )`:s?n=`textureLoad( ${t}, ${r}, ${s}, u32( ${i} ) )`:(n=`textureLoad( ${t}, ${r}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(n+=".x")),n}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}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===I||!1===this.isSampleCompare(e)&&e.minFilter===v&&e.magFilter===v||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,r,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,"0",i):this._generateTextureSample(e,t,r,s,i),n}generateTextureGrad(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return!0===e.isDepthTexture&&!0===e.isArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,r,s,i,n=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,r,n):this._generateTextureSampleLevel(e,t,r,s,i),a}generateTextureBias(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===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=nA[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Os.READ_ONLY:e.access}getStorageAccess(e,t){return tA[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||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);if("texture"===t||"storageTexture"===t?s=new Qv(i.name,i.node,o,n):"cubeTexture"===t?s=new Zv(i.name,i.node,o,n):"texture3D"===t&&(s=new Jv(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.setVisibility(sA[r]),!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new kw(`${i.name}_sampler`,i.node,o);e.setVisibility(sA[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?Wv:Hw)(e,o);n.setVisibility(sA[r]),l.push(n),a=n,i.name=s||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let s=e[u];void 0===s&&(s=new Xv(u,o),s.setVisibility(sA[r]),e[u]=s,l.push(s)),a=this.getNodeUniform(i,t),s.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){let s=`var ${t} : `;return s+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),s}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];for(let i=0;ir.value.itemSize;return s&&!i}getUniforms(e){const t=this.uniforms[e],r=[],s=[],i=[],n={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let s;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture)s="texture_cube";else if(!0===t.isDepthTexture)s=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)s="texture_2d_array";else if(!0===t.isVideoTexture)s="texture_external";else if(!0===t.isData3DTexture)s="texture_3d";else if(!0===i.node.isStorageTextureNode){s=`texture_storage_2d<${Xw(t)}, ${this.getStorageAccess(i.node,e)}>`}else{s=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${s};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,r=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===i.type?", "+n:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${u}> ${i.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${o} >`;s.push(this._getWGSLStructBinding(i.name,e,u,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in n){const t=n[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=r.join("\n");return a+=s.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${u}\n`),s+=`${i.code}\n\t`,e===n&&"compute"!==t)if(s+="// result\n\n\t","vertex"===t)s+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)r.returnType=a.getNodeType(this),r.structs+="var output : "+r.returnType+";",s+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar output : OutputStruct;",s+=`output.color = ${i.result};\n\n\treturn output;`}}r.flow=s}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getType(e){return aA[e]||e}isAvailable(e){let t=iA[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),iA[e]=t),t}_getWGSLMethod(e){return void 0!==uA[e]&&this._include(e),lA[e]}_include(e){const t=uA[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${dA}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class hA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=VS:e.depth&&(t=DS),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.samples}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}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?PN:e.isLineSegments||e.isMesh&&!0===t.wireframe?BN:e.isLine?LN:e.isMesh?FN:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ce)return _S;if(e===ce)return PS;throw new Error("Unsupported outputType")}}const pA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),gA=new Map([[ze,["float16"]]]),mA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class fA{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;e1&&(s.multisampled=!0,r.texture.isDepthTexture||(s.sampleType=Ew)),r.texture.isDepthTexture)t.compatibilityMode&&null===r.texture.compareFunction?s.sampleType=Ew:s.sampleType=ww;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const e=r.texture.type;e===_?s.sampleType=Aw:e===T?s.sampleType=Rw:e===I&&(this.backend.hasFeature("float32-filterable")?s.sampleType=Sw:s.sampleType=Ew)}r.isSampledCubeTexture?s.viewDimension=Lw:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?s.viewDimension=Bw:r.isSampledTexture3D&&(s.viewDimension=Fw),e.texture=s}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);s.push(e)}return r.createBindGroupLayout({entries:s})}createBindings(e,t,r,s=0){const{backend:i,bindGroupLayoutCache:n}=this,a=i.get(e);let o,u=n.get(e.bindingsReference);void 0===u&&(u=this.createBindingsLayout(e),n.set(e.bindingsReference,u)),r>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[r]===s&&(o=a.groups[r])),void 0===o&&(o=this.createBindGroup(e,u),r>0&&(a.groups[r]=o,a.versions[r]=s)),a.group=o,a.layout=u}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer;r.queue.writeBuffer(i,0,s,0)}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],n=r.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:s});r.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);if(void 0===e.buffer){const r=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=s.createBuffer({label:"bindingBuffer_"+t.name,size:r,usage:i});e.buffer=n}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t);if(void 0===e.buffer){const s=t.attribute;e.buffer=r.get(s).buffer}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}else if(t.isSampledTexture){const e=r.get(t.texture);let a;if(void 0!==e.externalTexture)a=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount,s=`view-${e.texture.width}-${e.texture.height}-${r}`;if(a=e[s],void 0===a){const i=Iw;let n;n=t.isSampledCubeTexture?Lw:t.isSampledTexture3D?Fw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Bw:Pw,a=e[s]=e.texture.createView({aspect:i,dimension:n,mipLevelCount:r})}}n.push({binding:i,resource:a})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class bA{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:o}=n,u=this.backend,l=u.device,d=u.utils,c=u.get(n),h=[];for(const t of e.getBindings()){const e=u.get(t);h.push(e.layout)}const p=u.attributeUtils.createShaderVertexBuffers(e);let g;s.blending===H||s.blending===k&&!1===s.transparent||(g=this._getBlending(s));let m={};!0===s.stencilWrite&&(m={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const f=this._getColorWriteMask(s),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:l.createPipelineLayout({bindGroupLayouts:h})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=v,E.depthWriteEnabled=s.depthWrite,E.depthCompare=_),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),S.depthStencil=E),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[s.getCurrentColorFormat(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);a.push(t.layout)}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===qe){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:rw},r={srcFactor:i,dstFactor:n,operation:rw}};if(e.premultipliedAlpha)switch(s){case k:i($E,XE,$E,XE);break;case Bt:i($E,$E,$E,$E);break;case Pt:i(HE,jE,HE,$E);break;case Mt:i(KE,XE,HE,$E)}else switch(s){case k:i(qE,XE,$E,XE);break;case Bt:i(qE,$E,$E,$E);break;case Pt:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mt:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};console.error("THREE.WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Ke:t=HE;break;case wt:t=$E;break;case Et:t=WE;break;case Tt:t=jE;break;case St:t=qE;break;case xt:t=XE;break;case vt:t=KE;break;case bt:t=YE;break;case _t:t=QE;break;case yt:t=ZE;break;case Nt:t=JE;break;case 211:t=ew;break;case 212:t=tw;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case kr:t=DN;break;case Or:t=HN;break;case Ur:t=VN;break;case Vr:t=ON;break;case Dr:t=UN;break;case Ir:t=zN;break;case Fr:t=kN;break;case Lr:t=GN;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case Xr:t=lw;break;case qr:t=dw;break;case jr:t=cw;break;case Wr:t=hw;break;case $r:t=pw;break;case Hr:t=gw;break;case zr:t=mw;break;case Gr:t=fw;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Xe:t=rw;break;case ft:t=sw;break;case mt:t=iw;break;case Yr:t=nw;break;case Kr:t=aw;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;switch(s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?QN:ZN),r.side){case je:s.frontFace=qN,s.cullMode=YN;break;case S:s.frontFace=qN,s.cullMode=KN;break;case E:s.frontFace=qN,s.cullMode=XN;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",r.side)}return s}_getColorWriteMask(e){return!0===e.colorWrite?uw:ow}_getDepthCompare(e){let t;if(!1===e.depthTest)t=HN;else{const r=e.depthFunc;switch(r){case kt:t=DN;break;case Ot:t=HN;break;case Ut:t=VN;break;case Vt:t=ON;break;case Dt:t=UN;break;case It:t=zN;break;case Ft:t=kN;break;case Lt:t=GN;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class xA extends AN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,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));let a=0;for(const[,t]of e){const e=n[t],r=n[t+1];a+=Number(r-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class TA extends lN{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new hA(this),this.attributeUtils=new fA(this),this.bindingUtils=new yA(this),this.pipelineUtils=new bA(this),this.textureUtils=new qw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},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(Uw),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;r.lost.then((t=>{const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}));const s=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=r,this.context=s;const i=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(Uw.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i}),this.updateSize()}get coordinateSystem(){return d}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const r=e.colorAttachments[0];this.renderer.samples>0?r.view=this.colorBuffer.createView():r.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;if(void 0===i||s.width!==r.width||s.height!==r.height||s.dimensions!==r.dimensions||s.activeMipmapLevel!==e.activeMipmapLevel||s.activeCubeFace!==e.activeCubeFace||s.samples!==r.samples){i={},s.descriptors=i;const e=()=>{r.removeEventListener("dispose",e),this.delete(r)};!1===r.hasEventListener("dispose",e)&&r.addEventListener("dispose",e)}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:WN}),this.initTimestampQuery(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;ea?(u.x=Math.min(t.dispatchCount,a),u.y=Math.ceil(t.dispatchCount/a)):u.x=t.dispatchCount,i.dispatchWorkgroups(u.x,u.y,u.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:r,material:s,context:i,pipeline:n}=e,a=e.getBindings(),o=this.get(i),u=this.get(n).pipeline,l=e.getIndex(),d=null!==l,c=e.getDrawParameters();if(null===c)return;const h=(t,r)=>{this.pipelineUtils.setPipeline(t,u),r.pipeline=u;const n=r.bindingGroups;for(let e=0,r=a.length;e{if(h(s,i),!0===r.isBatchedMesh){const e=r._multiDrawStarts,i=r._multiDrawCounts,n=r._multiDrawCount,a=r._multiDrawInstances;null!==a&&pt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o1?0:o;!0===d?s.drawIndexed(i[o],n,e[o]/l.array.BYTES_PER_ELEMENT,0,u):s.draw(i[o],n,e[o],u),t.update(r,i[o],n)}}else if(!0===d){const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndexedIndirect(e,0)}else s.drawIndexed(i,n,a,0,0);t.update(r,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndirect(e,0)}else s.draw(i,n,a,0);t.update(r,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),s=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==s.length){const e=this.get(n),r=[],i=new Uint32Array([0,0,0,0]);for(let t=0,n=s.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new MN(e)));super(new t(e),e),this.library=new NA,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class EA extends ds{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class wA{constructor(e,t=nn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new lp;r.name="PostProcessing",this._quadMesh=new Uy(r)}render(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}dispose(){this._quadMesh.material.dispose()}_update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;this._quadMesh.material.fragmentNode=!0===this.outputColorTransform?Ou(this.outputNode,t,r):this.outputNode.context({toneMapping:t,outputColorSpace:r}),this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,await this._quadMesh.renderAsync(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}}class AA extends x{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Y,this.minFilter=Y,this.isStorageTexture=!0}}class RA extends qy{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class CA extends cs{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new hs(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):console.error(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]?(console.error("THREE.NodeLoader: Node type not found:",e),ji()):Fi(new this.nodes[e])}}class MA extends ps{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 PA extends gs{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 CA;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 MA;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t nodeObject( new AttributeNode( na * @param {number} [index=0] - The uv index. * @return {AttributeNode} The uv attribute node. */ -const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' ); +const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' ); /** * A node that represents the dimensions of a texture. The texture size is @@ -10235,7 +10235,7 @@ class TextureNode extends UniformNode { */ getDefaultUV() { - return uv( this.value.channel ); + return uv$1( this.value.channel ); } @@ -13064,6 +13064,49 @@ class MaterialReferenceNode extends ReferenceNode { */ const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); +// Normal Mapping Without Precomputed Tangents +// http://www.thetenthplanet.de/archives/1180 + +const uv = uv$1(); + +const q0 = positionView.dFdx(); +const q1 = positionView.dFdy(); +const st0 = uv.dFdx(); +const st1 = uv.dFdy(); + +const N = normalView; + +const q1perp = q1.cross( N ); +const q0perp = N.cross( q0 ); + +const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) ); +const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) ); + +const det = T.dot( T ).max( B.dot( B ) ); +const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() ); + +/** + * Tangent vector in view space, computed dynamically from geometry and UV derivatives. + * Useful for normal mapping without precomputed tangents. + * + * Reference: http://www.thetenthplanet.de/archives/1180 + * + * @tsl + * @type {Node} + */ +const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' ); + +/** + * Bitangent vector in view space, computed dynamically from geometry and UV derivatives. + * Complements the tangentViewFrame for constructing the tangent space basis. + * + * Reference: http://www.thetenthplanet.de/archives/1180 + * + * @tsl + * @type {Node} + */ +const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' ); + /** * TSL object that represents the tangent attribute of the current rendered object. * @@ -13096,7 +13139,29 @@ const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' ); * @tsl * @type {Node} */ -const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' ); +const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => { + + let node; + + if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) { + + node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize(); + + } else { + + node = tangentViewFrame; + + } + + if ( material.flatShading !== true ) { + + node = directionToFaceDirection( node ); + + } + + return node; + +}, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' ); /** * TSL object that represents the vertex tangent in world space of the current rendered object. @@ -13151,7 +13216,29 @@ const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLoc * @tsl * @type {Node} */ -const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' ); +const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => { + + let node; + + if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) { + + node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize(); + + } else { + + node = bitangentViewFrame; + + } + + if ( material.flatShading !== true ) { + + node = directionToFaceDirection( node ); + + } + + return node; + +}, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' ); /** * TSL object that represents the vertex bitangent in world space of the current rendered object. @@ -13207,33 +13294,6 @@ const bentNormalView = /*@__PURE__*/ ( Fn( () => { } ).once() )(); -// Normal Mapping Without Precomputed Tangents -// http://www.thetenthplanet.de/archives/1180 - -const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => { - - const { eye_pos, surf_norm, mapN, uv } = inputs; - - const q0 = eye_pos.dFdx(); - const q1 = eye_pos.dFdy(); - const st0 = uv.dFdx(); - const st1 = uv.dFdy(); - - const N = surf_norm; // normalized - - const q1perp = q1.cross( N ); - const q0perp = N.cross( q0 ); - - const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) ); - const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) ); - - const det = T.dot( T ).max( B.dot( B ) ); - const scale = faceDirection.mul( det.inverseSqrt() ); - - return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize(); - -} ); - /** * This class can be used for applying normals maps to materials. * @@ -13286,7 +13346,7 @@ class NormalMapNode extends TempNode { } - setup( builder ) { + setup( { material } ) { const { normalMapType, scaleNode } = this; @@ -13294,44 +13354,37 @@ class NormalMapNode extends TempNode { if ( scaleNode !== null ) { - normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z ); + let scale = scaleNode; - } + if ( material.flatShading === true ) { - let outputNode = null; + scale = directionToFaceDirection( scale ); - if ( normalMapType === ObjectSpaceNormalMap ) { + } - outputNode = transformNormalToView( normalMap ); + normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z ); - } else if ( normalMapType === TangentSpaceNormalMap ) { + } - const tangent = builder.hasGeometryAttribute( 'tangent' ); + let output = null; - if ( tangent === true ) { + if ( normalMapType === ObjectSpaceNormalMap ) { - outputNode = TBNViewMatrix.mul( normalMap ).normalize(); + output = transformNormalToView( normalMap ); - } else { + } else if ( normalMapType === TangentSpaceNormalMap ) { - outputNode = perturbNormal2Arb( { - eye_pos: positionView, - surf_norm: normalView, - mapN: normalMap, - uv: uv() - } ); - - } + output = TBNViewMatrix.mul( normalMap ).normalize(); } else { console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` ); - outputNode = normalView; // Fallback to default normal view + output = normalView; // Fallback to default normal view } - return outputNode; + return output; } @@ -13354,7 +13407,7 @@ const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1 const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => { // It's used to preserve the same TextureNode instance - const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } ); + const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } ); const Hll = float( sampleTexture( ( uvNode ) => uvNode ) ); @@ -19676,7 +19729,7 @@ class Line2NodeMaterial extends NodeMaterial { this.colorNode = Fn( () => { - const vUv = uv(); + const vUv = uv$1(); if ( useDash ) { @@ -19950,6 +20003,8 @@ class MeshNormalNodeMaterial extends NodeMaterial { } /** + * TSL function for creating an equirect uv node. + * * Can be used to compute texture coordinates for projecting an * equirectangular texture onto a mesh for using it as the scene's * background. @@ -19958,56 +20013,19 @@ class MeshNormalNodeMaterial extends NodeMaterial { * scene.backgroundNode = texture( equirectTexture, equirectUV() ); * ``` * - * @augments TempNode - */ -class EquirectUVNode extends TempNode { - - static get type() { - - return 'EquirectUVNode'; - - } - - /** - * Constructs a new equirect uv node. - * - * @param {Node} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`. - */ - constructor( dirNode = positionWorldDirection ) { - - super( 'vec2' ); - - /** - * A direction vector for sampling why is by default `positionWorldDirection`. - * - * @type {Node} - */ - this.dirNode = dirNode; - - } - - setup() { - - const dir = this.dirNode; - - const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 ); - const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 ); - - return vec2( u, v ); - - } - -} - -/** - * TSL function for creating an equirect uv node. - * * @tsl * @function * @param {?Node} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`. - * @returns {EquirectUVNode} + * @returns {Node} */ -const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 ); +const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => { + + const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 ); + const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 ); + + return vec2( u, v ); + +} ); // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget @@ -21515,10 +21533,10 @@ const bicubic = ( textureNode, texelSize, lod ) => { * @tsl * @function * @param {TextureNode} textureNode - The texture node that should be filtered. - * @param {Node} [lodNode=float(3)] - Defines the LOD to sample from. + * @param {Node} lodNode - Defines the LOD to sample from. * @return {Node} The filtered texture sample. */ -const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => { +const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => { const fLodSize = vec2( textureNode.size( int( lodNode ) ) ); const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) ); @@ -21531,6 +21549,23 @@ const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] } ); +/** + * Applies mipped bicubic texture filtering to the given texture node. + * + * @tsl + * @function + * @param {TextureNode} textureNode - The texture node that should be filtered. + * @param {Node} [strength] - Defines the strength of the bicubic filtering. + * @return {Node} The filtered texture sample. + */ +const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => { + + const lod = strength.mul( maxMipLevel( textureNode ) ); + + return textureBicubicLevel( textureNode, lod ); + +} ); + // // Transmission // @@ -21589,7 +21624,7 @@ const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) ); - return textureBicubic( transmissionSample, lod ); + return textureBicubicLevel( transmissionSample, lod ); } ); @@ -22635,7 +22670,7 @@ const _faceLib = [ 0, 4, 2 ]; -const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize(); +const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize(); const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z ); /** @@ -24991,47 +25026,23 @@ class MeshToonNodeMaterial extends NodeMaterial { } /** + * TSL function for creating a matcap uv node. + * * Can be used to compute texture coordinates for projecting a * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}. * - * @augments TempNode + * @tsl + * @function + * @returns {Node} The matcap UV coordinates. */ -class MatcapUVNode extends TempNode { - - static get type() { - - return 'MatcapUVNode'; - - } +const matcapUV = /*@__PURE__*/ Fn( () => { - /** - * Constructs a new matcap uv node. - */ - constructor() { - - super( 'vec2' ); - - } - - setup() { + const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize(); + const y = positionViewDirection.cross( x ); - const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize(); - const y = positionViewDirection.cross( x ); + return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks - return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks - - } - -} - -/** - * TSL function for creating a matcap uv node. - * - * @tsl - * @function - * @returns {MatcapUVNode} - */ -const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode ); +} ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' ); const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial(); @@ -31682,7 +31693,7 @@ class SpriteSheetUVNode extends Node { * @param {Node} [uvNode=uv()] - The uv node. * @param {Node} [frameNode=float()] - The node that defines the current frame/sprite. */ - constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { + constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) { super( 'vec2' ); @@ -31742,118 +31753,14 @@ class SpriteSheetUVNode extends Node { const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 ); /** + * TSL function for creating a triplanar textures node. + * * Can be used for triplanar texture mapping. * * ```js * material.colorNode = triplanarTexture( texture( diffuseMap ) ); * ``` * - * @augments Node - */ -class TriplanarTexturesNode extends Node { - - static get type() { - - return 'TriplanarTexturesNode'; - - } - - /** - * Constructs a new triplanar textures node. - * - * @param {Node} textureXNode - First texture node. - * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead. - * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead. - * @param {?Node} [scaleNode=float(1)] - The scale node. - * @param {?Node} [positionNode=positionLocal] - Vertex positions in local space. - * @param {?Node} [normalNode=normalLocal] - Normals in local space. - */ - constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { - - super( 'vec4' ); - - /** - * First texture node. - * - * @type {Node} - */ - this.textureXNode = textureXNode; - - /** - * Second texture node. When not set, the shader will sample from `textureXNode` instead. - * - * @type {?Node} - * @default null - */ - this.textureYNode = textureYNode; - - /** - * Third texture node. When not set, the shader will sample from `textureXNode` instead. - * - * @type {?Node} - * @default null - */ - this.textureZNode = textureZNode; - - /** - * The scale node. - * - * @type {Node} - * @default float(1) - */ - this.scaleNode = scaleNode; - - /** - * Vertex positions in local space. - * - * @type {Node} - * @default positionLocal - */ - this.positionNode = positionNode; - - /** - * Normals in local space. - * - * @type {Node} - * @default normalLocal - */ - this.normalNode = normalNode; - - } - - setup() { - - const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; - - // Ref: https://github.com/keijiro/StandardTriplanar - - // Blending factor of triplanar mapping - let bf = normalNode.abs().normalize(); - bf = bf.div( bf.dot( vec3( 1.0 ) ) ); - - // Triplanar mapping - const tx = positionNode.yz.mul( scaleNode ); - const ty = positionNode.zx.mul( scaleNode ); - const tz = positionNode.xy.mul( scaleNode ); - - // Base color - const textureX = textureXNode.value; - const textureY = textureYNode !== null ? textureYNode.value : textureX; - const textureZ = textureZNode !== null ? textureZNode.value : textureX; - - const cx = texture( textureX, tx ).mul( bf.x ); - const cy = texture( textureY, ty ).mul( bf.y ); - const cz = texture( textureZ, tz ).mul( bf.z ); - - return add( cx, cy, cz ); - - } - -} - -/** - * TSL function for creating a triplanar textures node. - * * @tsl * @function * @param {Node} textureXNode - First texture node. @@ -31862,9 +31769,33 @@ class TriplanarTexturesNode extends Node { * @param {?Node} [scaleNode=float(1)] - The scale node. * @param {?Node} [positionNode=positionLocal] - Vertex positions in local space. * @param {?Node} [normalNode=normalLocal] - Normals in local space. - * @returns {TriplanarTexturesNode} + * @returns {Node} */ -const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 ); +const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => { + + // Reference: https://github.com/keijiro/StandardTriplanar + + // Blending factor of triplanar mapping + let bf = normalNode.abs().normalize(); + bf = bf.div( bf.dot( vec3( 1.0 ) ) ); + + // Triplanar mapping + const tx = positionNode.yz.mul( scaleNode ); + const ty = positionNode.zx.mul( scaleNode ); + const tz = positionNode.xy.mul( scaleNode ); + + // Base color + const textureX = textureXNode.value; + const textureY = textureYNode !== null ? textureYNode.value : textureX; + const textureZ = textureZNode !== null ? textureZNode.value : textureX; + + const cx = texture( textureX, tx ).mul( bf.x ); + const cy = texture( textureY, ty ).mul( bf.y ); + const cz = texture( textureZ, tz ).mul( bf.z ); + + return add( cx, cy, cz ); + +} ); /** * TSL function for creating a triplanar textures node. @@ -31877,7 +31808,7 @@ const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setPa * @param {?Node} [scaleNode=float(1)] - The scale node. * @param {?Node} [positionNode=positionLocal] - Vertex positions in local space. * @param {?Node} [normalNode=normalLocal] - Normals in local space. - * @returns {TriplanarTexturesNode} + * @returns {Node} */ const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); @@ -32021,10 +31952,17 @@ class ReflectorNode extends TextureNode { clone() { - const texture = new this.constructor( this.reflectorNode ); - texture._reflectorBaseNode = this._reflectorBaseNode; + const newNode = new this.constructor( this.reflectorNode ); + newNode.uvNode = this.uvNode; + newNode.levelNode = this.levelNode; + newNode.biasNode = this.biasNode; + newNode.sampler = this.sampler; + newNode.depthNode = this.depthNode; + newNode.compareNode = this.compareNode; + newNode.gradNode = this.gradNode; + newNode._reflectorBaseNode = this._reflectorBaseNode; - return texture; + return newNode; } @@ -32566,7 +32504,7 @@ class RTTNode extends TextureNode { const renderTarget = new RenderTarget( width, height, options ); - super( renderTarget.texture, uv() ); + super( renderTarget.texture, uv$1() ); /** * The node to render a texture with. @@ -32885,6 +32823,82 @@ const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMat } ); +/** + * Class representing a node that samples a value using a provided callback function. + * + * @extends Node + */ +class SampleNode extends Node { + + /** + * Returns the type of the node. + * + * @type {string} + * @readonly + * @static + */ + static get type() { + + return 'SampleNode'; + + } + + /** + * Creates an instance of SampleNode. + * + * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value. + */ + constructor( callback ) { + + super(); + + this.callback = callback; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSampleNode = true; + + } + + /** + * Sets up the node by sampling with the default UV accessor. + * + * @returns {Node} The result of the callback function when called with the UV node. + */ + setup() { + + return this.sample( uv$1() ); + + } + + /** + * Calls the callback function with the provided UV node. + * + * @param {Node} uv - The UV node or value to be passed to the callback. + * @returns {Node} The result of the callback function. + */ + sample( uv ) { + + return this.callback( uv ); + + } + +} + +/** + * Helper function to create a SampleNode wrapped as a node object. + * + * @function + * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value. + * @returns {SampleNode} The created SampleNode instance wrapped as a node object. + */ +const sample = ( callback ) => nodeObject( new SampleNode( 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 @@ -34236,7 +34250,16 @@ class PassMultipleTextureNode extends PassTextureNode { clone() { - return new this.constructor( this.passNode, this.textureName, this.previousTexture ); + const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture ); + newNode.uvNode = this.uvNode; + newNode.levelNode = this.levelNode; + newNode.biasNode = this.biasNode; + newNode.sampler = this.sampler; + newNode.depthNode = this.depthNode; + newNode.compareNode = this.compareNode; + newNode.gradNode = this.gradNode; + + return newNode; } @@ -40114,7 +40137,7 @@ class PointLightNode extends AnalyticLightNode { * @param {Node} coord - The uv coordinates. * @return {Node} The result data. */ -const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { +const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => { const uv = coord.mul( 2.0 ); @@ -40134,7 +40157,7 @@ const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => { * @param {Node} coord - The uv to generate the circle. * @return {Node} The circle shape. */ -const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => { +const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => { const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) ); @@ -41636,14 +41659,14 @@ const mx_aastep = ( threshold, value ) => { }; const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() ); -const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' ); -const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' ); +const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' ); +const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' ); const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) ); -const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' ); -const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' ); +const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' ); +const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' ); -const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset ); +const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset ); const mx_safepower = ( in1, in2 = 1 ) => { @@ -41655,10 +41678,10 @@ const mx_safepower = ( in1, in2 = 1 ) => { const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot ); -const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); -const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { +const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot ); +const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => { texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type @@ -41668,16 +41691,16 @@ const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => { }; -const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); +const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) ); -const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); +const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) ); -const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); -const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); +const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude ); /** * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM). @@ -42170,6 +42193,7 @@ var TSL = /*#__PURE__*/Object.freeze({ rtt: rtt, sRGBTransferEOTF: sRGBTransferEOTF, sRGBTransferOETF: sRGBTransferOETF, + sample: sample, sampler: sampler, samplerComparison: samplerComparison, saturate: saturate, @@ -42227,6 +42251,7 @@ var TSL = /*#__PURE__*/Object.freeze({ texture3D: texture3D, textureBarrier: textureBarrier, textureBicubic: textureBicubic, + textureBicubicLevel: textureBicubicLevel, textureCubeUV: textureCubeUV, textureLoad: textureLoad, textureSize: textureSize, @@ -42259,7 +42284,7 @@ var TSL = /*#__PURE__*/Object.freeze({ uniformTexture: uniformTexture, unpremultiplyAlpha: unpremultiplyAlpha, userData: userData, - uv: uv, + uv: uv$1, uvec2: uvec2, uvec3: uvec3, uvec4: uvec4, @@ -73788,4 +73813,4 @@ class ClippingGroup extends Group { } -export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents }; +export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents }; diff --git a/build/three.webgpu.nodes.min.js b/build/three.webgpu.nodes.min.js index 296564f838c9bf..bae3b43674c5d3 100644 --- a/build/three.webgpu.nodes.min.js +++ b/build/three.webgpu.nodes.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2025 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,EventDispatcher as o,MathUtils as u,WebGLCoordinateSystem as l,WebGPUCoordinateSystem as d,ColorManagement as c,SRGBTransfer as h,NoToneMapping as p,StaticDrawUsage as g,InterleavedBuffer as m,InterleavedBufferAttribute as f,DynamicDrawUsage as y,NoColorSpace as b,Texture as x,UnsignedIntType as T,IntType as _,NearestFilter as v,Sphere as N,BackSide as S,DoubleSide as E,Euler as w,CubeTexture as A,CubeReflectionMapping as R,CubeRefractionMapping as C,TangentSpaceNormalMap as M,ObjectSpaceNormalMap as P,InstancedInterleavedBuffer as B,InstancedBufferAttribute as L,DataArrayTexture as F,FloatType as I,FramebufferTexture as D,LinearMipmapLinearFilter as V,DepthTexture as U,Material as O,NormalBlending as k,LineBasicMaterial as G,LineDashedMaterial as z,NoBlending as H,MeshNormalMaterial as $,SRGBColorSpace as W,WebGLCubeRenderTarget as j,BoxGeometry as q,Mesh as X,Scene as K,LinearFilter as Y,CubeCamera as Q,EquirectangularReflectionMapping as Z,EquirectangularRefractionMapping as J,AddOperation as ee,MixOperation as te,MultiplyOperation as re,MeshBasicMaterial as se,MeshLambertMaterial as ie,MeshPhongMaterial as ne,OrthographicCamera as ae,PerspectiveCamera as oe,RenderTarget as ue,LinearSRGBColorSpace as le,RGBAFormat as de,HalfFloatType as ce,CubeUVReflectionMapping as he,BufferGeometry as pe,BufferAttribute as ge,MeshStandardMaterial as me,MeshPhysicalMaterial as fe,MeshToonMaterial as ye,MeshMatcapMaterial as be,SpriteMaterial as xe,PointsMaterial as Te,ShadowMaterial as _e,Uint32BufferAttribute as ve,Uint16BufferAttribute as Ne,arrayNeedsUint32 as Se,Camera as Ee,DepthStencilFormat as we,DepthFormat as Ae,UnsignedInt248Type as Re,UnsignedByteType as Ce,Plane as Me,Object3D as Pe,LinearMipMapLinearFilter as Be,Float32BufferAttribute as Le,UVMapping as Fe,VSMShadowMap as Ie,LessCompare as De,RGFormat as Ve,BasicShadowMap as Ue,SphereGeometry as Oe,LinearMipmapNearestFilter as ke,NearestMipmapLinearFilter as Ge,Float16BufferAttribute as ze,REVISION as He,ArrayCamera as $e,PlaneGeometry as We,FrontSide as je,CustomBlending as qe,AddEquation as Xe,ZeroFactor as Ke,CylinderGeometry as Ye,Quaternion as Qe,WebXRController as Ze,RAD2DEG as Je,PCFShadowMap as et,FrustumArray as tt,Frustum as rt,DataTexture as st,RedIntegerFormat as it,RedFormat as nt,ShortType as at,ByteType as ot,UnsignedShortType as ut,RGIntegerFormat as lt,RGBIntegerFormat as dt,RGBFormat as ct,RGBAIntegerFormat as ht,warnOnce as pt,createCanvasElement as gt,ReverseSubtractEquation as mt,SubtractEquation as ft,OneMinusDstAlphaFactor as yt,OneMinusDstColorFactor as bt,OneMinusSrcAlphaFactor as xt,OneMinusSrcColorFactor as Tt,DstAlphaFactor as _t,DstColorFactor as vt,SrcAlphaSaturateFactor as Nt,SrcAlphaFactor as St,SrcColorFactor as Et,OneFactor as wt,CullFaceNone as At,CullFaceBack as Rt,CullFaceFront as Ct,MultiplyBlending as Mt,SubtractiveBlending as Pt,AdditiveBlending as Bt,NotEqualDepth as Lt,GreaterDepth as Ft,GreaterEqualDepth as It,EqualDepth as Dt,LessEqualDepth as Vt,LessDepth as Ut,AlwaysDepth as Ot,NeverDepth as kt,UnsignedShort4444Type as Gt,UnsignedShort5551Type as zt,UnsignedInt5999Type as Ht,AlphaFormat as $t,RGB_S3TC_DXT1_Format as Wt,RGBA_S3TC_DXT1_Format as jt,RGBA_S3TC_DXT3_Format as qt,RGBA_S3TC_DXT5_Format as Xt,RGB_PVRTC_4BPPV1_Format as Kt,RGB_PVRTC_2BPPV1_Format as Yt,RGBA_PVRTC_4BPPV1_Format as Qt,RGBA_PVRTC_2BPPV1_Format as Zt,RGB_ETC1_Format as Jt,RGB_ETC2_Format as er,RGBA_ETC2_EAC_Format as tr,RGBA_ASTC_4x4_Format as rr,RGBA_ASTC_5x4_Format as sr,RGBA_ASTC_5x5_Format as ir,RGBA_ASTC_6x5_Format as nr,RGBA_ASTC_6x6_Format as ar,RGBA_ASTC_8x5_Format as or,RGBA_ASTC_8x6_Format as ur,RGBA_ASTC_8x8_Format as lr,RGBA_ASTC_10x5_Format as dr,RGBA_ASTC_10x6_Format as cr,RGBA_ASTC_10x8_Format as hr,RGBA_ASTC_10x10_Format as pr,RGBA_ASTC_12x10_Format as gr,RGBA_ASTC_12x12_Format as mr,RGBA_BPTC_Format as fr,RED_RGTC1_Format as yr,SIGNED_RED_RGTC1_Format as br,RED_GREEN_RGTC2_Format as xr,SIGNED_RED_GREEN_RGTC2_Format as Tr,MirroredRepeatWrapping as _r,ClampToEdgeWrapping as vr,RepeatWrapping as Nr,NearestMipmapNearestFilter as Sr,NotEqualCompare as Er,GreaterCompare as wr,GreaterEqualCompare as Ar,EqualCompare as Rr,LessEqualCompare as Cr,AlwaysCompare as Mr,NeverCompare as Pr,LinearTransfer as Br,NotEqualStencilFunc as Lr,GreaterStencilFunc as Fr,GreaterEqualStencilFunc as Ir,EqualStencilFunc as Dr,LessEqualStencilFunc as Vr,LessStencilFunc as Ur,AlwaysStencilFunc as Or,NeverStencilFunc as kr,DecrementWrapStencilOp as Gr,IncrementWrapStencilOp as zr,DecrementStencilOp as Hr,IncrementStencilOp as $r,InvertStencilOp as Wr,ReplaceStencilOp as jr,ZeroStencilOp as qr,KeepStencilOp as Xr,MaxEquation as Kr,MinEquation as Yr,SpotLight as Qr,PointLight as Zr,DirectionalLight as Jr,RectAreaLight as es,AmbientLight as ts,HemisphereLight as rs,LightProbe as ss,LinearToneMapping as is,ReinhardToneMapping as ns,CineonToneMapping as as,ACESFilmicToneMapping as os,AgXToneMapping as us,NeutralToneMapping as ls,Group as ds,Loader as cs,FileLoader as hs,MaterialLoader as ps,ObjectLoader as gs}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,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,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,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,PCFSoftShadowMap,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,TimestampQuery,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding}from"./three.core.min.js";const ms=["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"];class fs{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=ms,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,material:s,object:i}=e;if(t={material:this.getMaterialData(s),geometry:{id:r.id,attributes:this.getAttributesData(r.attributes),indexVersion:r.index?r.index.version:null,drawRange:{start:r.drawRange.start,count:r.drawRange.count}},worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={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 null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};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)}return t}equals(e){const{object:t,material:r,geometry:s}=e,i=this.getRenderObjectData(e);if(!0!==i.worldMatrix.equals(t.matrixWorld))return i.worldMatrix.copy(t.matrixWorld),!1;const n=i.material;for(const e in n){const t=n[e],s=r[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return n[e]=s,!1}if(n.transmission>0){const{width:t,height:r}=e.context;if(i.bufferWidth!==t||i.bufferHeight!==r)return i.bufferWidth=t,i.bufferHeight=r,!1}const a=i.geometry,o=s.attributes,u=a.attributes,l=Object.keys(u),d=Object.keys(o);if(a.id!==s.id)return a.id=s.id,!1;if(l.length!==d.length)return i.geometry.attributes=this.getAttributesData(o),!1;for(const e of l){const t=u[e],r=o[e];if(void 0===r)return delete u[e],!1;if(t.version!==r.version)return t.version=r.version,!1}const c=s.index,h=a.indexVersion,p=c?c.version:null;if(h!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==s.drawRange.start||a.drawRange.count!==s.drawRange.count)return a.drawRange.start=s.drawRange.start,a.drawRange.count=s.drawRange.count,!1;if(i.morphTargetInfluences){let e=!1;for(let r=0;r>>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 bs=e=>ys(e),xs=e=>ys(e),Ts=(...e)=>ys(e);function _s(e,t=!1){const r=[];!0===e.isNode&&(r.push(e.id),e=e.getSelf());for(const{property:s,childNode:i}of vs(e))r.push(ys(s.slice(0,-4)),i.getCacheKey(t));return ys(r)}function*vs(e,t=!1){for(const r in e){if(!0===r.startsWith("_"))continue;const s=e[r];if(!0===Array.isArray(s))for(let e=0;ee.charCodeAt(0))).buffer}var Is=Object.freeze({__proto__:null,arrayBufferToBase64:Ls,base64ToArrayBuffer:Fs,getByteBoundaryFromType:Cs,getCacheKey:_s,getDataFromObject:Bs,getLengthFromType:As,getMemoryLengthFromType:Rs,getNodeChildren:vs,getTypeFromLength:Es,getTypedArrayFromType:ws,getValueFromType:Ps,getValueType:Ms,hash:Ts,hashArray:xs,hashString:bs});const Ds={VERTEX:"vertex",FRAGMENT:"fragment"},Vs={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Us={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Os={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ks=["fragment","vertex"],Gs=["setup","analyze","generate"],zs=[...ks,"compute"],Hs=["x","y","z","w"],$s={analyze:"setup",generate:"analyze"};let Ws=0;class js extends o{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Vs.NONE,this.updateBeforeType=Vs.NONE,this.updateAfterType=Vs.NONE,this.uuid=u.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ws++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Vs.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Vs.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Vs.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of vs(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Ts(_s(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const r=this.getShared(e);if(this!==r)return r.build(e,t);const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const i=$s[e.buildStage];if(i&&!0!==s.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const r of Object.values(t))if(r&&!0===r.isNode){if(!0===r.parents){const t=e.getNodeProperties(r);t.parents=t.parents||[],t.parents.push(this)}r.build(e)}}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const r=this.getNodeType(e),s=e.getDataFromNode(this);n=s.snippet,void 0===n?void 0===s.generated?(s.generated=!0,n=this.generate(e)||"",s.snippet=n):(console.warn("THREE.Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,r,t)}else n=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return vs(this)}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(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}}class qs extends js{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Xs extends js{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(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 Ks extends js{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 Ys extends Ks{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,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 o=0;for(const t of i){if(o>=s){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${r}()' type.`);break}let i,u=t.getNodeType(e),l=e.getTypeLength(u);o+l>s&&(console.error(`THREE.TSL: Length of '${r}()' data exceeds maximum length of output type.`),l=s-o,u=e.getTypeFromLength(l)),o+=l,i=t.build(e,u);const d=e.getComponentType(u);d!==n&&(i=e.format(i,d,n)),a.push(i)}const u=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(u,r,t)}}const Qs=Hs.join("");class Zs extends js{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(Hs.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const 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===Qs.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 Js extends Ks{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}getNodeType(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;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),li=e=>ui(e).split("").sort().join(""),di={setup(e,t){const r=t.shift();return e(Ii(r),...t)},get(e,t,r){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(ni.assign(r,...e),r);if(ai.has(t)){const s=ai.get(t);return e.isStackNode?(...e)=>r.add(s(...e)):(...e)=>s(r,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&ai.has(t.slice(0,t.length-6))){const s=ai.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>r.assign(e[0],s(...e)):(...e)=>r.assign(s(r,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=ui(t),Fi(new Zs(r,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(3).toLowerCase()),r=>Fi(new Js(e,t,Fi(r)));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(4).toLowerCase()),()=>Fi(new ei(Fi(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Fi(new Zs(e,t));if(!0===/^\d+$/.test(t))return Fi(new qs(r,new si(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Fi(new ii(r,e))}return Reflect.get(e,t,r)},set:(e,t,r,s)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,r,s):(s[t].assign(r),!0)},ci=new WeakMap,hi=new WeakMap,pi=function(e,t=null){for(const r in e)e[r]=Fi(e[r],t);return e},gi=function(e,t=null){const r=e.length;for(let s=0;sFi(null!==s?Object.assign(e,s):e);let n,a,o,u=t;function l(t){let r;return r=u?/[a-z]/i.test(u)?u+"()":u:e.type,void 0!==a&&t.lengtho?(console.error(`THREE.TSL: "${r}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?n=(...t)=>i(new e(...Di(l(t)))):null!==r?(r=Fi(r),n=(...s)=>i(new e(t,...Di(l(s)),r))):n=(...r)=>i(new e(t,...Di(l(r)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(u=e,n),n},fi=function(e,...t){return Fi(new e(...Di(t)))};class yi extends js{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let s=hi.get(e.constructor);void 0===s&&(s=new WeakMap,hi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=Fi(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i),o=Fi(i.call(r))}else{const s=t.jsFunc,i=null!==r||s.length>1?s(r||[],e):s(e);o=Fi(i)}return e.subBuildFn=a,t.once&&(s[n]=o),o}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);if("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 r}}class bi extends js{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Ii(e),Fi(new yi(this,e))}setup(){return this.call()}}const xi=[!1,!0],Ti=[0,1,2,3],_i=[-1,-2],vi=[.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],Ni=new Map;for(const e of xi)Ni.set(e,new si(e));const Si=new Map;for(const e of Ti)Si.set(e,new si(e,"uint"));const Ei=new Map([...Si].map((e=>new si(e.value,"int"))));for(const e of _i)Ei.set(e,new si(e,"int"));const wi=new Map([...Ei].map((e=>new si(e.value))));for(const e of vi)wi.set(e,new si(e));for(const e of vi)wi.set(-e,new si(-e));const Ai={bool:Ni,uint:Si,ints:Ei,float:wi},Ri=new Map([...Ni,...wi]),Ci=(e,t)=>Ri.has(e)?Ri.get(e):!0===e.isNode?e:new si(e,t),Mi=function(e,t=null){return(...r)=>{if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every((e=>"object"!=typeof e)))&&(r=[Ps(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return Fi(t.get(r[0]));if(1===r.length){const t=Ci(r[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Fi(t):Fi(new Xs(t,e))}const s=r.map((e=>Ci(e)));return Fi(new Ys(s,e))}},Pi=e=>"object"==typeof e&&null!==e?e.value:e,Bi=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Li(e,t){return new Proxy(new bi(e,t),di)}const Fi=(e,t=null)=>function(e,t=null){const r=Ms(e);if("node"===r){let t=ci.get(e);return void 0===t&&(t=new Proxy(e,di),ci.set(e,t),ci.set(t,t)),t}return null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?Fi(Ci(e,t)):"shader"===r?e.isFn?e:ki(e):e}(e,t),Ii=(e,t=null)=>new pi(e,t),Di=(e,t=null)=>new gi(e,t),Vi=(...e)=>new mi(...e),Ui=(...e)=>new fi(...e);let Oi=0;const ki=(e,t=null)=>{let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:console.error("THREE.TSL: Invalid layout type."),t=null));const s=new Li(e,r),i=(...e)=>{let t;Ii(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];const i=s.call(t);return"void"===r&&i.toStack(),i};if(i.shaderNode=s,i.id=s.id,i.isFn=!0,i.getNodeType=(...e)=>s.getNodeType(...e),i.getCacheKey=(...e)=>s.getCacheKey(...e),i.setLayout=e=>(s.setLayout(e),i),i.once=(e=null)=>(s.once=!0,s.subBuilds=e,i),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+Oi++,type:r,inputs:[]};for(const r in t)"return"!==r&&e.inputs.push({name:r,type:t[r]});t=e}i.setLayout(t)}return i},Gi=e=>{ni=e},zi=()=>ni,Hi=(...e)=>ni.If(...e);function $i(e){return ni&&ni.add(e),e}oi("toStack",$i);const Wi=new Mi("color"),ji=new Mi("float",Ai.float),qi=new Mi("int",Ai.ints),Xi=new Mi("uint",Ai.uint),Ki=new Mi("bool",Ai.bool),Yi=new Mi("vec2"),Qi=new Mi("ivec2"),Zi=new Mi("uvec2"),Ji=new Mi("bvec2"),en=new Mi("vec3"),tn=new Mi("ivec3"),rn=new Mi("uvec3"),sn=new Mi("bvec3"),nn=new Mi("vec4"),an=new Mi("ivec4"),on=new Mi("uvec4"),un=new Mi("bvec4"),ln=new Mi("mat2"),dn=new Mi("mat3"),cn=new Mi("mat4");oi("toColor",Wi),oi("toFloat",ji),oi("toInt",qi),oi("toUint",Xi),oi("toBool",Ki),oi("toVec2",Yi),oi("toIVec2",Qi),oi("toUVec2",Zi),oi("toBVec2",Ji),oi("toVec3",en),oi("toIVec3",tn),oi("toUVec3",rn),oi("toBVec3",sn),oi("toVec4",nn),oi("toIVec4",an),oi("toUVec4",on),oi("toBVec4",un),oi("toMat2",ln),oi("toMat3",dn),oi("toMat4",cn);const hn=Vi(qs).setParameterLength(2),pn=(e,t)=>Fi(new Xs(Fi(e),t));oi("element",hn),oi("convert",pn);oi("append",(e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),$i(e))));class gn extends js{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}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 mn=(e,t)=>Fi(new gn(e,t)),fn=(e,t)=>Fi(new gn(e,t,!0)),yn=Ui(gn,"vec4","DiffuseColor"),bn=Ui(gn,"vec3","EmissiveColor"),xn=Ui(gn,"float","Roughness"),Tn=Ui(gn,"float","Metalness"),_n=Ui(gn,"float","Clearcoat"),vn=Ui(gn,"float","ClearcoatRoughness"),Nn=Ui(gn,"vec3","Sheen"),Sn=Ui(gn,"float","SheenRoughness"),En=Ui(gn,"float","Iridescence"),wn=Ui(gn,"float","IridescenceIOR"),An=Ui(gn,"float","IridescenceThickness"),Rn=Ui(gn,"float","AlphaT"),Cn=Ui(gn,"float","Anisotropy"),Mn=Ui(gn,"vec3","AnisotropyT"),Pn=Ui(gn,"vec3","AnisotropyB"),Bn=Ui(gn,"color","SpecularColor"),Ln=Ui(gn,"float","SpecularF90"),Fn=Ui(gn,"float","Shininess"),In=Ui(gn,"vec4","Output"),Dn=Ui(gn,"float","dashSize"),Vn=Ui(gn,"float","gapSize"),Un=Ui(gn,"float","pointWidth"),On=Ui(gn,"float","IOR"),kn=Ui(gn,"float","Transmission"),Gn=Ui(gn,"float","Thickness"),zn=Ui(gn,"float","AttenuationDistance"),Hn=Ui(gn,"color","AttenuationColor"),$n=Ui(gn,"float","Dispersion");class Wn extends js{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1){super("string"),this.name=e,this.shared=t,this.order=r,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const jn=e=>new Wn(e),qn=(e,t=0)=>new Wn(e,!0,t),Xn=qn("frame"),Kn=qn("render"),Yn=jn("object");class Qn extends ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Yn}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const r=this.getSelf();return e=e.bind(r),super.onUpdate((t=>{const s=e(t,r);void 0!==s&&(this.value=s)}),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.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,r,t)}}const Zn=(e,t)=>{const r=Bi(t||e),s=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Fi(new Qn(s,r))};class Jn extends Ks{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const ea=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Jn(null,r.length,r)}else{const r=e[0],s=e[1];t=new Jn(r,s)}return Fi(t)};oi("toArray",((e,t)=>ea(Array(t).fill(e))));class ta extends Ks{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return Hs.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=e.getNodeProperties(this);s.sourceNode=r,s.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.getNodeType(e),a=r.build(e),o=s.build(e,n),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=a);else if(i){const s=e.getVarFromNode(this,null,n),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)console.error("THREE.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?Di(t):Ii(t[0]),Fi(new sa(Fi(e),t)));oi("call",ia);const na={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class aa extends Ks{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new aa(e,t,r);for(let t=0;t>"===t||"<<"===t)return e.getIntegerType(i);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(i),e.getTypeLength(n));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(i)){if("float"===n)return i;if(e.isVector(n))return e.getVectorFromMatrix(i);if(e.isMatrix(n))return i}else if(e.isMatrix(n)){if("float"===i)return n;if(e.isVector(i))return e.getVectorFromMatrix(n)}return e.getTypeLength(n)>e.getTypeLength(i)?n:i}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e);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),d=i?i.build(e,o):null,c=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===l;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${d} )`,n,t):e.format(`( ${u} ${r} ${d} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${d} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${d} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(c)return e.format(`${c}( ${u}, ${d} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${d} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${d}`,n,t);{let i=`( ${u} ${r} ${d} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return c?e.format(`${c}( ${u}, ${d} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${d} ${r} ${u}`,n,t):e.format(`${u} ${r} ${d}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const oa=Vi(aa,"+").setParameterLength(2,1/0).setName("add"),ua=Vi(aa,"-").setParameterLength(2,1/0).setName("sub"),la=Vi(aa,"*").setParameterLength(2,1/0).setName("mul"),da=Vi(aa,"/").setParameterLength(2,1/0).setName("div"),ca=Vi(aa,"%").setParameterLength(2).setName("mod"),ha=Vi(aa,"==").setParameterLength(2).setName("equal"),pa=Vi(aa,"!=").setParameterLength(2).setName("notEqual"),ga=Vi(aa,"<").setParameterLength(2).setName("lessThan"),ma=Vi(aa,">").setParameterLength(2).setName("greaterThan"),fa=Vi(aa,"<=").setParameterLength(2).setName("lessThanEqual"),ya=Vi(aa,">=").setParameterLength(2).setName("greaterThanEqual"),ba=Vi(aa,"&&").setParameterLength(2,1/0).setName("and"),xa=Vi(aa,"||").setParameterLength(2,1/0).setName("or"),Ta=Vi(aa,"!").setParameterLength(1).setName("not"),_a=Vi(aa,"^^").setParameterLength(2).setName("xor"),va=Vi(aa,"&").setParameterLength(2).setName("bitAnd"),Na=Vi(aa,"~").setParameterLength(2).setName("bitNot"),Sa=Vi(aa,"|").setParameterLength(2).setName("bitOr"),Ea=Vi(aa,"^").setParameterLength(2).setName("bitXor"),wa=Vi(aa,"<<").setParameterLength(2).setName("shiftLeft"),Aa=Vi(aa,">>").setParameterLength(2).setName("shiftRight"),Ra=ki((([e])=>(e.addAssign(1),e))),Ca=ki((([e])=>(e.subAssign(1),e))),Ma=ki((([e])=>{const t=qi(e).toConst();return e.addAssign(1),t})),Pa=ki((([e])=>{const t=qi(e).toConst();return e.subAssign(1),t}));oi("add",oa),oi("sub",ua),oi("mul",la),oi("div",da),oi("mod",ca),oi("equal",ha),oi("notEqual",pa),oi("lessThan",ga),oi("greaterThan",ma),oi("lessThanEqual",fa),oi("greaterThanEqual",ya),oi("and",ba),oi("or",xa),oi("not",Ta),oi("xor",_a),oi("bitAnd",va),oi("bitNot",Na),oi("bitOr",Sa),oi("bitXor",Ea),oi("shiftLeft",wa),oi("shiftRight",Aa),oi("incrementBefore",Ra),oi("decrementBefore",Ca),oi("increment",Ma),oi("decrement",Pa);const Ba=(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),ca(qi(e),qi(t)));oi("modInt",Ba);class La extends Ks{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===La.MAX||e===La.MIN)&&arguments.length>3){let i=new La(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}getNodeType(e){const t=this.method;return t===La.LENGTH||t===La.DISTANCE||t===La.DOT?"float":t===La.CROSS?"vec3":t===La.ALL||t===La.ANY?"bool":t===La.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===La.ONE_MINUS)i=ua(1,t);else if(s===La.RECIPROCAL)i=da(1,t);else if(s===La.DIFFERENCE)i=io(ua(t,r));else if(s===La.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=nn(en(n),0):s=nn(en(s),0);const a=la(s,n).xyz;i=Ya(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===La.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const c=[];return r===La.CROSS?c.push(n.build(e,s),a.build(e,s)):u===l&&r===La.STEP?c.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==l||r!==La.MIN&&r!==La.MAX?r===La.REFRACT?c.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===La.MIX?c.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===d&&r===La.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==La.DFDX&&r!==La.DFDY||(console.warn(`THREE.TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),c.push(n.build(e,i)),null!==a&&c.push(a.build(e,i)),null!==o&&c.push(o.build(e,i))):c.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${c.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}La.ALL="all",La.ANY="any",La.RADIANS="radians",La.DEGREES="degrees",La.EXP="exp",La.EXP2="exp2",La.LOG="log",La.LOG2="log2",La.SQRT="sqrt",La.INVERSE_SQRT="inversesqrt",La.FLOOR="floor",La.CEIL="ceil",La.NORMALIZE="normalize",La.FRACT="fract",La.SIN="sin",La.COS="cos",La.TAN="tan",La.ASIN="asin",La.ACOS="acos",La.ATAN="atan",La.ABS="abs",La.SIGN="sign",La.LENGTH="length",La.NEGATE="negate",La.ONE_MINUS="oneMinus",La.DFDX="dFdx",La.DFDY="dFdy",La.ROUND="round",La.RECIPROCAL="reciprocal",La.TRUNC="trunc",La.FWIDTH="fwidth",La.TRANSPOSE="transpose",La.BITCAST="bitcast",La.EQUALS="equals",La.MIN="min",La.MAX="max",La.STEP="step",La.REFLECT="reflect",La.DISTANCE="distance",La.DIFFERENCE="difference",La.DOT="dot",La.CROSS="cross",La.POW="pow",La.TRANSFORM_DIRECTION="transformDirection",La.MIX="mix",La.CLAMP="clamp",La.REFRACT="refract",La.SMOOTHSTEP="smoothstep",La.FACEFORWARD="faceforward";const Fa=ji(1e-6),Ia=ji(1e6),Da=ji(Math.PI),Va=ji(2*Math.PI),Ua=Vi(La,La.ALL).setParameterLength(1),Oa=Vi(La,La.ANY).setParameterLength(1),ka=Vi(La,La.RADIANS).setParameterLength(1),Ga=Vi(La,La.DEGREES).setParameterLength(1),za=Vi(La,La.EXP).setParameterLength(1),Ha=Vi(La,La.EXP2).setParameterLength(1),$a=Vi(La,La.LOG).setParameterLength(1),Wa=Vi(La,La.LOG2).setParameterLength(1),ja=Vi(La,La.SQRT).setParameterLength(1),qa=Vi(La,La.INVERSE_SQRT).setParameterLength(1),Xa=Vi(La,La.FLOOR).setParameterLength(1),Ka=Vi(La,La.CEIL).setParameterLength(1),Ya=Vi(La,La.NORMALIZE).setParameterLength(1),Qa=Vi(La,La.FRACT).setParameterLength(1),Za=Vi(La,La.SIN).setParameterLength(1),Ja=Vi(La,La.COS).setParameterLength(1),eo=Vi(La,La.TAN).setParameterLength(1),to=Vi(La,La.ASIN).setParameterLength(1),ro=Vi(La,La.ACOS).setParameterLength(1),so=Vi(La,La.ATAN).setParameterLength(1,2),io=Vi(La,La.ABS).setParameterLength(1),no=Vi(La,La.SIGN).setParameterLength(1),ao=Vi(La,La.LENGTH).setParameterLength(1),oo=Vi(La,La.NEGATE).setParameterLength(1),uo=Vi(La,La.ONE_MINUS).setParameterLength(1),lo=Vi(La,La.DFDX).setParameterLength(1),co=Vi(La,La.DFDY).setParameterLength(1),ho=Vi(La,La.ROUND).setParameterLength(1),po=Vi(La,La.RECIPROCAL).setParameterLength(1),go=Vi(La,La.TRUNC).setParameterLength(1),mo=Vi(La,La.FWIDTH).setParameterLength(1),fo=Vi(La,La.TRANSPOSE).setParameterLength(1),yo=Vi(La,La.BITCAST).setParameterLength(2),bo=(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),ha(e,t)),xo=Vi(La,La.MIN).setParameterLength(2,1/0),To=Vi(La,La.MAX).setParameterLength(2,1/0),_o=Vi(La,La.STEP).setParameterLength(2),vo=Vi(La,La.REFLECT).setParameterLength(2),No=Vi(La,La.DISTANCE).setParameterLength(2),So=Vi(La,La.DIFFERENCE).setParameterLength(2),Eo=Vi(La,La.DOT).setParameterLength(2),wo=Vi(La,La.CROSS).setParameterLength(2),Ao=Vi(La,La.POW).setParameterLength(2),Ro=Vi(La,La.POW,2).setParameterLength(1),Co=Vi(La,La.POW,3).setParameterLength(1),Mo=Vi(La,La.POW,4).setParameterLength(1),Po=Vi(La,La.TRANSFORM_DIRECTION).setParameterLength(2),Bo=e=>la(no(e),Ao(io(e),1/3)),Lo=e=>Eo(e,e),Fo=Vi(La,La.MIX).setParameterLength(3),Io=(e,t=0,r=1)=>Fi(new La(La.CLAMP,Fi(e),Fi(t),Fi(r))),Do=e=>Io(e),Vo=Vi(La,La.REFRACT).setParameterLength(3),Uo=Vi(La,La.SMOOTHSTEP).setParameterLength(3),Oo=Vi(La,La.FACEFORWARD).setParameterLength(3),ko=ki((([e])=>{const t=Eo(e.xy,Yi(12.9898,78.233)),r=ca(t,Da);return Qa(Za(r).mul(43758.5453))})),Go=(e,t,r)=>Fo(t,r,e),zo=(e,t,r)=>Uo(t,r,e),Ho=(e,t)=>_o(t,e),$o=(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),so(e,t)),Wo=Oo,jo=qa;oi("all",Ua),oi("any",Oa),oi("equals",bo),oi("radians",ka),oi("degrees",Ga),oi("exp",za),oi("exp2",Ha),oi("log",$a),oi("log2",Wa),oi("sqrt",ja),oi("inverseSqrt",qa),oi("floor",Xa),oi("ceil",Ka),oi("normalize",Ya),oi("fract",Qa),oi("sin",Za),oi("cos",Ja),oi("tan",eo),oi("asin",to),oi("acos",ro),oi("atan",so),oi("abs",io),oi("sign",no),oi("length",ao),oi("lengthSq",Lo),oi("negate",oo),oi("oneMinus",uo),oi("dFdx",lo),oi("dFdy",co),oi("round",ho),oi("reciprocal",po),oi("trunc",go),oi("fwidth",mo),oi("atan2",$o),oi("min",xo),oi("max",To),oi("step",Ho),oi("reflect",vo),oi("distance",No),oi("dot",Eo),oi("cross",wo),oi("pow",Ao),oi("pow2",Ro),oi("pow3",Co),oi("pow4",Mo),oi("transformDirection",Po),oi("mix",Go),oi("clamp",Io),oi("refract",Vo),oi("smoothstep",zo),oi("faceForward",Oo),oi("difference",So),oi("saturate",Do),oi("cbrt",Bo),oi("transpose",fo),oi("rand",ko);class qo extends js{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}getNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),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.cache(),r=this.ifNode.cache(),s=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=r.context({nodeBlock:r}),n.elseNode=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?mn(r).build(e):"";s.nodeProperty=l;const d=i.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${d} ) {\n\n`).addFlowTab();let c=n.build(e,r);if(c&&(u?c=l+" = "+c+";":(c="return "+c+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Xo=Vi(qo).setParameterLength(2,3);oi("select",Xo);class Ko extends js{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const r=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e,t);return e.setContext(r),s}}const Yo=Vi(Ko).setParameterLength(1,2),Qo=(e,t)=>Yo(e,{label:t});oi("context",Yo),oi("label",Qo);class Zo extends js{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;s&&(a=e.isDeterministic(t),o=n?s:a);const u=e.getVectorType(this.getNodeType(e)),l=t.build(e,u),d=e.getVarFromNode(this,r,u,void 0,o),c=e.getPropertyName(d);let h=c;if(o)if(n)h=a?`const ${c}`:`let ${c}`;else{const r=e.getArrayCount(t);h=`const ${e.getVar(d.type,c,r)}`}return e.addLineFlowCode(`${h} = ${l}`,this),c}}const Jo=Vi(Zo),eu=(e,t=null)=>Jo(e,t).toStack(),tu=(e,t=null)=>Jo(e,t,!0).toStack();oi("toVar",eu),oi("toConst",tu);const ru=e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Jo(e));oi("temp",ru);class su extends js{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(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 iu=(e,t,r=null)=>Fi(new su(Fi(e),t,r));class nu extends js{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let 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=iu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.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,Ds.VERTEX);e.flowNodeFromShaderStage(Ds.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const au=Vi(nu).setParameterLength(1,2),ou=e=>au(e);oi("toVarying",au),oi("toVertexStage",ou),oi("varying",((...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),au(...e)))),oi("vertexStage",((...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),au(...e))));const uu=ki((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return Fo(t,r,s)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lu=ki((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return Fo(t,r,s)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),du="WorkingColorSpace";class cu extends Ks{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===du?c.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!==c.enabled&&r!==s&&r&&s?(c.getTransfer(r)===h&&(i=nn(uu(i.rgb),i.a)),c.getPrimaries(r)!==c.getPrimaries(s)&&(i=nn(dn(c._getMatrix(new n,r,s)).mul(i.rgb),i.a)),c.getTransfer(s)===h&&(i=nn(lu(i.rgb),i.a)),i):i}}const hu=(e,t)=>Fi(new cu(Fi(e),du,t)),pu=(e,t)=>Fi(new cu(Fi(e),t,du));oi("workingToColorSpace",hu),oi("colorSpaceToWorking",pu);let gu=class extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class mu extends js{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=Vs.OBJECT}setGroup(e){return this.group=e,this}element(e){return Fi(new gu(this,Fi(e)))}setNodeType(e){const t=Zn(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new fu(e,t,r));class bu extends Ks{static get type(){return"ToneMappingNode"}constructor(e,t=Tu,r=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Ts(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,r=this.toneMapping;if(r===p)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=nn(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const xu=(e,t,r)=>Fi(new bu(e,Fi(t),Fi(r))),Tu=yu("toneMappingExposure","float");oi("toneMapping",((e,t,r)=>xu(t,r,e)));class _u 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=g,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=this.value,s=e.getTypeLength(t),i=this.bufferStride||s,n=this.bufferOffset,a=!0===r.isInterleavedBuffer?r:new m(r,i),o=new f(a,s,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=au(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}}const vu=(e,t=null,r=0,s=0)=>Fi(new _u(e,t,r,s)),Nu=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setUsage(y),Su=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setInstanced(!0),Eu=(e,t=null,r=0,s=0)=>Nu(e,t,r,s).setInstanced(!0);oi("toAttribute",(e=>vu(e.value)));class wu extends js{static get type(){return"ComputeNode"}constructor(e,t,r=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=r,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Vs.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let r=t[0];for(let e=1;eFi(new wu(Fi(e),t,r));oi("compute",Au);class Ru extends js{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),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}}const Cu=(e,t)=>Fi(new Ru(Fi(e),t));oi("cache",Cu);class Mu extends js{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Pu=Vi(Mu).setParameterLength(2);oi("bypass",Pu);class Bu extends js{static get type(){return"RemapNode"}constructor(e,t,r,s=ji(0),i=ji(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=r,this.outLowNode=s,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:r,outLowNode:s,outHighNode:i,doClamp:n}=this;let a=e.sub(t).div(r.sub(t));return!0===n&&(a=a.clamp()),a.mul(i.sub(s)).add(s)}}const Lu=Vi(Bu,null,null,{doClamp:!1}).setParameterLength(3,5),Fu=Vi(Bu).setParameterLength(3,5);oi("remap",Lu),oi("remapClamp",Fu);class Iu extends js{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 Du=Vi(Iu).setParameterLength(1,2),Vu=e=>(e?Xo(e,Du("discard")):Du("discard")).toStack();oi("discard",Vu);class Uu extends Ks{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||p,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||b;return r!==p&&(t=t.toneMapping(r)),s!==b&&s!==c.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Ou=(e,t=null,r=null)=>Fi(new Uu(Fi(e),t,r));oi("renderOutput",Ou);class ku extends Ks{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e),s="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(s.length);let n="";return n+="// #"+s+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+r+" /* ... */\n",n+="// #"+i+"#\n",null!==t?t(e,n):console.log(n),r}}const Gu=(e,t=null)=>Fi(new ku(Fi(e),t));oi("debug",Gu);class zu extends js{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const 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 au(this).build(e,r)}return console.warn(`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 Hu=(e,t=null)=>Fi(new zu(e,t)),$u=(e=0)=>Hu("uv"+(e>0?e:""),"vec2");class Wu extends js{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 ju=Vi(Wu).setParameterLength(1,2);class qu extends Qn{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vs.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 Xu=Vi(qu).setParameterLength(1),Ku=new x;class Yu extends Qn{static get type(){return"TextureNode"}constructor(e=Ku,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.sampler=!0,this.updateMatrix=!1,this.updateType=Vs.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===T?"uvec4":this.value.type===_?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return $u(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Zn(this.value.matrix)),this._matrixUniform.mul(en(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Vs.OBJECT:Vs.NONE,this}setupUV(e,t){const r=this.value;return e.isFlipY()&&(r.image instanceof ImageBitmap&&!0===r.flipY||!0===r.isRenderTargetTexture||!0===r.isFramebufferTexture||!0===r.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this,e)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,r,s,i,n,a,o){const u=this.value;let l;return l=s?e.generateTextureLevel(u,t,r,s,n):i?e.generateTextureBias(u,t,r,i,n):o?e.generateTextureGrad(u,t,r,o,n):a?e.generateTextureCompare(u,t,r,a,n):!1===this.sampler?e.generateTextureLoad(u,t,r,n):e.generateTexture(u,t,r,n),l}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);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:r,biasNode:o,compareNode:u,depthNode:l,gradNode:d}=s,c=this.generateUV(e,t),h=r?r.build(e,"float"):null,p=o?o.build(e,"float"):null,g=l?l.build(e,"int"):null,m=u?u.build(e,"float"):null,f=d?[d[0].build(e,"vec2"),d[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);a=e.getPropertyName(y);const b=this.generateSnippet(e,i,c,h,p,g,m,f);e.addLineFlowCode(`${a} = ${b}`,this),n.snippet=b,n.propertyName=a}let o=a;const u=this.getNodeType(e);return e.needsToWorkingColorSpace(r)&&(o=pu(Du(o,u),r.colorSpace).setup(e).build(e,u)),e.format(o,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}blur(e){const t=this.clone();t.biasNode=Fi(e).mul(Xu(t)),t.referenceNode=this.getSelf();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===v||r.magFilter===v)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Fi(t)}level(e){const t=this.clone();return t.levelNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}size(e){return ju(this,e)}bias(e){const t=this.clone();return t.biasNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}compare(e){const t=this.clone();return t.compareNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}grad(e,t){const r=this.clone();return r.gradNode=[Fi(e),Fi(t)],r.referenceNode=this.getSelf(),Fi(r)}depth(e){const t=this.clone();return t.depthNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}const Qu=Vi(Yu).setParameterLength(1,4).setName("texture"),Zu=(e=Ku,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=Qu(e,t,r,s),i},Ju=(...e)=>Zu(...e).setSampler(!1);class el extends Qn{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const tl=(e,t,r)=>Fi(new el(e,t,r));class rl extends qs{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(),s=this.node.getPaddedType();return e.format(t,s,r)}}class sl extends el{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ms(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Vs.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rFi(new sl(e,t));const nl=Vi(class extends js{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),al=Zn(0,"uint").label("u_cameraIndex").setGroup(qn("cameraIndex")).toVarying("v_cameraIndex"),ol=Zn("float").label("cameraNear").setGroup(Kn).onRenderUpdate((({camera:e})=>e.near)),ul=Zn("float").label("cameraFar").setGroup(Kn).onRenderUpdate((({camera:e})=>e.far)),ll=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);t=il(r).setGroup(Kn).label("cameraProjectionMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrix")}else t=Zn("mat4").label("cameraProjectionMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),dl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);t=il(r).setGroup(Kn).label("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrixInverse")}else t=Zn("mat4").label("cameraProjectionMatrixInverse").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse));return t})).once()(),cl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);t=il(r).setGroup(Kn).label("cameraViewMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraViewMatrix")}else t=Zn("mat4").label("cameraViewMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),hl=Zn("mat4").label("cameraWorldMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorld)),pl=Zn("mat3").label("cameraNormalMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.normalMatrix)),gl=Zn(new r).label("cameraPosition").setGroup(Kn).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),ml=new N;class fl extends js{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Vs.OBJECT,this.uniformNode=new Qn(null)}getNodeType(){const e=this.scope;return e===fl.WORLD_MATRIX?"mat4":e===fl.POSITION||e===fl.VIEW_POSITION||e===fl.DIRECTION||e===fl.SCALE?"vec3":e===fl.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===fl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===fl.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===fl.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===fl.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===fl.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===fl.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),ml.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=ml.radius}}generate(e){const t=this.scope;return t===fl.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===fl.POSITION||t===fl.VIEW_POSITION||t===fl.DIRECTION||t===fl.SCALE?this.uniformNode.nodeType="vec3":t===fl.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}}fl.WORLD_MATRIX="worldMatrix",fl.POSITION="position",fl.SCALE="scale",fl.VIEW_POSITION="viewPosition",fl.DIRECTION="direction",fl.RADIUS="radius";const yl=Vi(fl,fl.DIRECTION).setParameterLength(1),bl=Vi(fl,fl.WORLD_MATRIX).setParameterLength(1),xl=Vi(fl,fl.POSITION).setParameterLength(1),Tl=Vi(fl,fl.SCALE).setParameterLength(1),_l=Vi(fl,fl.VIEW_POSITION).setParameterLength(1),vl=Vi(fl,fl.RADIUS).setParameterLength(1);class Nl extends fl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Sl=Ui(Nl,Nl.DIRECTION),El=Ui(Nl,Nl.WORLD_MATRIX),wl=Ui(Nl,Nl.POSITION),Al=Ui(Nl,Nl.SCALE),Rl=Ui(Nl,Nl.VIEW_POSITION),Cl=Ui(Nl,Nl.RADIUS),Ml=Zn(new n).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),Pl=Zn(new a).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),Bl=ki((e=>e.renderer.overrideNodes.modelViewMatrix||Ll)).once()().toVar("modelViewMatrix"),Ll=cl.mul(El),Fl=ki((e=>(e.context.isHighPrecisionModelViewMatrix=!0,Zn("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highpModelViewMatrix"),Il=ki((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Zn("mat3").onObjectUpdate((({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highpModelNormalViewMatrix"),Dl=Hu("position","vec3"),Vl=Dl.toVarying("positionLocal"),Ul=Dl.toVarying("positionPrevious"),Ol=ki((e=>El.mul(Vl).xyz.toVarying(e.getSubBuildProperty("v_positionWorld"))),"vec3").once(["POSITION"])(),kl=ki((()=>Vl.transformDirection(El).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection")),"vec3").once(["POSITION"])(),Gl=ki((e=>e.context.setupPositionView().toVarying("v_positionView")),"vec3").once(["POSITION"])(),zl=Gl.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Hl extends js{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{renderer:t,material:r}=e;return t.coordinateSystem===l&&r.side===S?"false":e.getFrontFacing()}}const $l=Ui(Hl),Wl=ji($l).mul(2).sub(1),jl=ki((([e],{material:t})=>{const r=t.side;return r===S?e=e.mul(-1):r===E&&(e=e.mul(Wl)),e})),ql=Hu("normal","vec3"),Xl=ki((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),en(0,1,0)):ql),"vec3").once()().toVar("normalLocal"),Kl=Gl.dFdx().cross(Gl.dFdy()).normalize().toVar("normalFlat"),Yl=ki((e=>{let t;return t=!0===e.material.flatShading?Kl:rd(Xl).toVarying("v_normalViewGeometry").normalize(),t}),"vec3").once()().toVar("normalViewGeometry"),Ql=ki((e=>{let t=Yl.transformDirection(cl);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")}),"vec3").once()(),Zl=ki((({subBuildFn:e,material:t,context:r})=>{let s;return"NORMAL"===e||"VERTEX"===e?(s=Yl,!0!==t.flatShading&&(s=jl(s))):s=r.setupNormal().context({getUV:null}),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Jl=Zl.transformDirection(cl).toVar("normalWorld"),ed=ki((({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Zl:t.setupClearcoatNormal().context({getUV:null}),r}),"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),td=ki((([e,t=El])=>{const r=dn(t),s=e.div(en(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz})),rd=ki((([e],t)=>{const r=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==r)return r.transformDirection(e);const s=Ml.mul(e);return cl.transformDirection(s)})),sd=ki((()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Zl))).once(["NORMAL","VERTEX"])(),id=ki((()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Jl))).once(["NORMAL","VERTEX"])(),nd=ki((()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),ed))).once(["NORMAL","VERTEX"])(),ad=new w,od=new a,ud=Zn(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),ld=Zn(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),dd=Zn(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?(ad.copy(r),od.makeRotationFromEuler(ad)):od.identity(),od})),cd=zl.negate().reflect(Zl),hd=zl.negate().refract(Zl,ud),pd=cd.transformDirection(cl).toVar("reflectVector"),gd=hd.transformDirection(cl).toVar("reflectVector"),md=new A;class fd extends Yu{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===R?pd:e.mapping===C?gd:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),en(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return e.renderer.coordinateSystem!==d&&r.isRenderTargetTexture||(t=en(t.x.negate(),t.yz)),dd.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const yd=Vi(fd).setParameterLength(1,4).setName("cubeTexture"),bd=(e=md,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=yd(e,t,r,s),i};class xd extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}}class Td extends js{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=Vs.OBJECT}element(e){return Fi(new xd(this,Fi(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?tl(null,e,this.count):Array.isArray(this.getValueFromReference())?il(null,e):"texture"===e?Zu(null):"cubeTexture"===e?bd(null):Zn(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new Td(e,t,r)),vd=(e,t,r,s)=>Fi(new Td(e,t,s,r));class Nd extends Td{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 Sd=(e,t,r=null)=>Fi(new Nd(e,t,r)),Ed=ki((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Hu("tangent","vec4"))))(),wd=Ed.xyz.toVar("tangentLocal"),Ad=Bl.mul(nn(wd,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView"),Rd=Ad.transformDirection(cl).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),Cd=ki((([e,t],{subBuildFn:r,material:s})=>{let i=e.mul(Ed.w).xyz;return"NORMAL"===r&&!0!==s.flatShading&&(i=i.toVarying(t)),i})).once(["NORMAL"]),Md=Cd(ql.cross(Ed),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Pd=Cd(Xl.cross(wd),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Bd=Cd(Zl.cross(Ad),"v_bitangentView").normalize().toVar("bitangentView"),Ld=Cd(Jl.cross(Rd),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Fd=dn(Ad,Bd,Zl).toVar("TBNViewMatrix"),Id=zl.mul(Fd),Dd=ki((()=>{let e=Pn.cross(zl);return e=e.cross(Pn).normalize(),e=Fo(e,Zl,Cn.mul(xn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})).once()(),Vd=ki((e=>{const{eye_pos:t,surf_norm:r,mapN:s,uv:i}=e,n=t.dFdx(),a=t.dFdy(),o=i.dFdx(),u=i.dFdy(),l=r,d=a.cross(l),c=l.cross(n),h=d.mul(o.x).add(c.mul(u.x)),p=d.mul(o.y).add(c.mul(u.y)),g=h.dot(h).max(p.dot(p)),m=Wl.mul(g.inverseSqrt());return oa(h.mul(s.x,m),p.mul(s.y,m),l.mul(s.z)).normalize()}));class Ud extends Ks{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=M}setup(e){const{normalMapType:t,scaleNode:r}=this;let s=this.node.mul(2).sub(1);null!==r&&(s=en(s.xy.mul(r),s.z));let i=null;if(t===P)i=rd(s);else if(t===M){i=!0===e.hasGeometryAttribute("tangent")?Fd.mul(s).normalize():Vd({eye_pos:Gl,surf_norm:Zl,mapN:s,uv:$u()})}else console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=Zl;return i}}const Od=Vi(Ud).setParameterLength(1,2),kd=ki((({textureNode:e,bumpScale:t})=>{const r=t=>e.cache().context({getUV:e=>t(e.uvNode||$u()),forceUVContext:!0}),s=ji(r((e=>e)));return Yi(ji(r((e=>e.add(e.dFdx())))).sub(s),ji(r((e=>e.add(e.dFdy())))).sub(s)).mul(t)})),Gd=ki((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(Wl),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()}));class zd extends Ks{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=kd({textureNode:this.textureNode,bumpScale:e});return Gd({surf_pos:Gl,surf_norm:Zl,dHdxy:t})}}const Hd=Vi(zd).setParameterLength(1,2),$d=new Map;class Wd extends js{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=$d.get(e);return void 0===r&&(r=Sd(e,t),$d.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===Wd.COLOR){const e=void 0!==t.color?this.getColor(r):en();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Wd.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Wd.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ji(1);else if(r===Wd.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Wd.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Wd.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Wd.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Wd.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===Wd.NORMAL)t.normalMap?(s=Od(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType):s=t.bumpMap?Hd(this.getTexture("bump").r,this.getFloat("bumpScale")):Zl;else if(r===Wd.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Wd.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Wd.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Od(this.getTexture(r),this.getCache(r+"Scale","vec2")):Zl;else if(r===Wd.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===Wd.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(.07,1)}else if(r===Wd.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=ln(Cc.x,Cc.y,Cc.y.negate(),Cc.x).mul(e.rg.mul(2).sub(Yi(1)).normalize().mul(e.b))}else s=Cc;else if(r===Wd.IRIDESCENCE_THICKNESS){const e=_d("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=_d("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Wd.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Wd.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Wd.IOR)s=this.getFloat(r);else if(r===Wd.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Wd.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Wd.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):ji(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Wd.ALPHA_TEST="alphaTest",Wd.COLOR="color",Wd.OPACITY="opacity",Wd.SHININESS="shininess",Wd.SPECULAR="specular",Wd.SPECULAR_STRENGTH="specularStrength",Wd.SPECULAR_INTENSITY="specularIntensity",Wd.SPECULAR_COLOR="specularColor",Wd.REFLECTIVITY="reflectivity",Wd.ROUGHNESS="roughness",Wd.METALNESS="metalness",Wd.NORMAL="normal",Wd.CLEARCOAT="clearcoat",Wd.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Wd.CLEARCOAT_NORMAL="clearcoatNormal",Wd.EMISSIVE="emissive",Wd.ROTATION="rotation",Wd.SHEEN="sheen",Wd.SHEEN_ROUGHNESS="sheenRoughness",Wd.ANISOTROPY="anisotropy",Wd.IRIDESCENCE="iridescence",Wd.IRIDESCENCE_IOR="iridescenceIOR",Wd.IRIDESCENCE_THICKNESS="iridescenceThickness",Wd.IOR="ior",Wd.TRANSMISSION="transmission",Wd.THICKNESS="thickness",Wd.ATTENUATION_DISTANCE="attenuationDistance",Wd.ATTENUATION_COLOR="attenuationColor",Wd.LINE_SCALE="scale",Wd.LINE_DASH_SIZE="dashSize",Wd.LINE_GAP_SIZE="gapSize",Wd.LINE_WIDTH="linewidth",Wd.LINE_DASH_OFFSET="dashOffset",Wd.POINT_SIZE="size",Wd.DISPERSION="dispersion",Wd.LIGHT_MAP="light",Wd.AO="ao";const jd=Ui(Wd,Wd.ALPHA_TEST),qd=Ui(Wd,Wd.COLOR),Xd=Ui(Wd,Wd.SHININESS),Kd=Ui(Wd,Wd.EMISSIVE),Yd=Ui(Wd,Wd.OPACITY),Qd=Ui(Wd,Wd.SPECULAR),Zd=Ui(Wd,Wd.SPECULAR_INTENSITY),Jd=Ui(Wd,Wd.SPECULAR_COLOR),ec=Ui(Wd,Wd.SPECULAR_STRENGTH),tc=Ui(Wd,Wd.REFLECTIVITY),rc=Ui(Wd,Wd.ROUGHNESS),sc=Ui(Wd,Wd.METALNESS),ic=Ui(Wd,Wd.NORMAL),nc=Ui(Wd,Wd.CLEARCOAT),ac=Ui(Wd,Wd.CLEARCOAT_ROUGHNESS),oc=Ui(Wd,Wd.CLEARCOAT_NORMAL),uc=Ui(Wd,Wd.ROTATION),lc=Ui(Wd,Wd.SHEEN),dc=Ui(Wd,Wd.SHEEN_ROUGHNESS),cc=Ui(Wd,Wd.ANISOTROPY),hc=Ui(Wd,Wd.IRIDESCENCE),pc=Ui(Wd,Wd.IRIDESCENCE_IOR),gc=Ui(Wd,Wd.IRIDESCENCE_THICKNESS),mc=Ui(Wd,Wd.TRANSMISSION),fc=Ui(Wd,Wd.THICKNESS),yc=Ui(Wd,Wd.IOR),bc=Ui(Wd,Wd.ATTENUATION_DISTANCE),xc=Ui(Wd,Wd.ATTENUATION_COLOR),Tc=Ui(Wd,Wd.LINE_SCALE),_c=Ui(Wd,Wd.LINE_DASH_SIZE),vc=Ui(Wd,Wd.LINE_GAP_SIZE),Nc=Ui(Wd,Wd.LINE_WIDTH),Sc=Ui(Wd,Wd.LINE_DASH_OFFSET),Ec=Ui(Wd,Wd.POINT_SIZE),wc=Ui(Wd,Wd.DISPERSION),Ac=Ui(Wd,Wd.LIGHT_MAP),Rc=Ui(Wd,Wd.AO),Cc=Zn(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))})),Mc=ki((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Pc extends js{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===Pc.VERTEX)s=e.getVertexIndex();else if(r===Pc.INSTANCE)s=e.getInstanceIndex();else if(r===Pc.DRAW)s=e.getDrawIndex();else if(r===Pc.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===Pc.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==Pc.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=au(this).build(e,t)}return i}}Pc.VERTEX="vertex",Pc.INSTANCE="instance",Pc.SUBGROUP="subgroup",Pc.INVOCATION_LOCAL="invocationLocal",Pc.INVOCATION_SUBGROUP="invocationSubgroup",Pc.DRAW="draw";const Bc=Ui(Pc,Pc.VERTEX),Lc=Ui(Pc,Pc.INSTANCE),Fc=Ui(Pc,Pc.SUBGROUP),Ic=Ui(Pc,Pc.INVOCATION_SUBGROUP),Dc=Ui(Pc,Pc.INVOCATION_LOCAL),Vc=Ui(Pc,Pc.DRAW);class Uc extends js{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=Vs.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:r,instanceColor:s}=this;let{instanceMatrixNode:i,instanceColorNode:n}=this;if(null===i){if(t<=1e3)i=tl(r.array,"mat4",Math.max(t,1)).element(Lc);else{const e=new B(r.array,16,1);this.buffer=e;const t=r.usage===y?Eu:Su,s=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];i=cn(...s)}this.instanceMatrixNode=i}if(s&&null===n){const e=new L(s.array,3),t=s.usage===y?Eu:Su;this.bufferColor=e,n=en(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=i.mul(Vl).xyz;if(Vl.assign(a),e.hasGeometryAttribute("normal")){const e=td(Xl,i);Xl.assign(e)}null!==this.instanceColorNode&&fn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==y&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==y&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}const Oc=Vi(Uc).setParameterLength(2,3);class kc extends Uc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Gc=Vi(kc).setParameterLength(1);class zc extends js{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Lc:this.batchingIdNode=Vc);const t=ki((([e])=>{const t=qi(ju(Ju(this.batchMesh._indirectTexture),0).x),r=qi(e).mod(t),s=qi(e).div(t);return Ju(this.batchMesh._indirectTexture,Qi(r,s)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(qi(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=qi(ju(Ju(s),0).x),n=ji(r).mul(4).toInt().toVar(),a=n.mod(i),o=n.div(i),u=cn(Ju(s,Qi(a,o)),Ju(s,Qi(a.add(1),o)),Ju(s,Qi(a.add(2),o)),Ju(s,Qi(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=ki((([e])=>{const t=qi(ju(Ju(l),0).x),r=e,s=r.mod(t),i=r.div(t);return Ju(l,Qi(s,i)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);fn("vec3","vBatchColor").assign(t)}const d=dn(u);Vl.assign(u.mul(Vl));const c=Xl.div(en(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Xl.assign(h),e.hasGeometryAttribute("tangent")&&wd.mulAssign(d)}}const Hc=Vi(zc).setParameterLength(1);class $c extends qs{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 Wc=Vi($c).setParameterLength(2);class jc extends el{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=Es(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=Os.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){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Wc(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Os.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=vu(this.value),this._varying=au(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(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 qc=(e,t=null,r=0)=>Fi(new jc(e,t,r)),Xc=new WeakMap;class Kc extends js{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Vs.OBJECT,this.skinIndexNode=Hu("skinIndex","uvec4"),this.skinWeightNode=Hu("skinWeight","vec4"),this.bindMatrixNode=_d("bindMatrix","mat4"),this.bindMatrixInverseNode=_d("bindMatrixInverse","mat4"),this.boneMatricesNode=vd("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Vl,this.toPositionNode=Vl,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=oa(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}getSkinnedNormal(e=this.boneMatricesNode,t=Xl){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);let d=oa(s.x.mul(a),s.y.mul(o),s.z.mul(u),s.w.mul(l));return d=n.mul(d).mul(i),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=vd("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Ul)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Bs(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Ul.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Xl.assign(t),e.hasGeometryAttribute("tangent")&&wd.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Xc.get(t)!==e.frameId&&(Xc.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const Yc=e=>Fi(new Kc(e));class Qc extends js{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;eNumber(u)?">=":"<")),a)n=`while ( ${u} )`;else{const r={start:o,end:u},s=r.start,i=r.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=h)switch(typeof h){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(d,h);break;case"string":a=l+" "+h;break;default:h.isNode?a=l+" "+p()+" "+h.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else h="int"===d||"uint"===d?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+h;n=`for ( ${e.getVar(d,l)+" = "+s}; ${l+" "+c+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tFi(new Qc(Di(e,"int"))).toStack(),Jc=()=>Du("break").toStack(),eh=new WeakMap,th=new s,rh=ki((({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=qi(Bc).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ju(e,Qi(u,o)).depth(i).xyz.mul(t)}));class sh extends js{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Zn(1),this.updateType=Vs.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=eh.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 F(m,h,p,a);f.type=I,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=ji(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ju(this.mesh.morphTexture,Qi(qi(e).add(1),qi(Lc))).r):t.assign(_d("morphTargetInfluences","float").element(e).toVar()),Hi(t.notEqual(0),(()=>{!0===s&&Vl.addAssign(rh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(0)})),!0===i&&Xl.addAssign(rh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(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 ih=Vi(sh).setParameterLength(1);class nh extends js{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class ah extends nh{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class oh extends Ko{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:en().toVar("directDiffuse"),directSpecular:en().toVar("directSpecular"),indirectDiffuse:en().toVar("indirectDiffuse"),indirectSpecular:en().toVar("indirectSpecular")};return{radiance:en().toVar("radiance"),irradiance:en().toVar("irradiance"),iblIrradiance:en().toVar("iblIrradiance"),ambientOcclusion:ji(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 uh=Vi(oh);class lh extends nh{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let dh,ch;class hh extends js{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===hh.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Vs.NONE;return this.scope!==hh.SIZE&&this.scope!==hh.VIEWPORT||(e=Vs.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===hh.VIEWPORT?null!==t?ch.copy(t.viewport):(e.getViewport(ch),ch.multiplyScalar(e.getPixelRatio())):null!==t?(dh.width=t.width,dh.height=t.height):e.getDrawingBufferSize(dh)}setup(){const e=this.scope;let r=null;return r=e===hh.SIZE?Zn(dh||(dh=new t)):e===hh.VIEWPORT?Zn(ch||(ch=new s)):Yi(mh.div(gh)),r}generate(e){if(this.scope===hh.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(gh).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}hh.COORDINATE="coordinate",hh.VIEWPORT="viewport",hh.SIZE="size",hh.UV="uv";const ph=Ui(hh,hh.UV),gh=Ui(hh,hh.SIZE),mh=Ui(hh,hh.COORDINATE),fh=Ui(hh,hh.VIEWPORT),yh=fh.zw,bh=mh.sub(fh.xy),xh=bh.div(yh),Th=ki((()=>(console.warn('THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),gh)),"vec2").once()(),_h=new t;class vh extends Yu{static get type(){return"ViewportTextureNode"}constructor(e=ph,t=null,r=null){null===r&&((r=new D).minFilter=V),super(r,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Vs.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(_h);const r=this.value;r.image.width===_h.width&&r.image.height===_h.height||(r.image.width=_h.width,r.image.height=_h.height,r.needsUpdate=!0);const s=r.generateMipmaps;r.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(r),r.generateMipmaps=s}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Nh=Vi(vh).setParameterLength(0,3),Sh=Vi(vh,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Eh=null;class wh extends vh{static get type(){return"ViewportDepthTextureNode"}constructor(e=ph,t=null){null===Eh&&(Eh=new U),super(e,t,Eh)}}const Ah=Vi(wh).setParameterLength(0,2);class Rh extends js{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===Rh.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Rh.DEPTH_BASE)null!==r&&(s=Lh().assign(r));else if(t===Rh.DEPTH)s=e.isPerspectiveCamera?Mh(Gl.z,ol,ul):Ch(Gl.z,ol,ul);else if(t===Rh.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=Ph(r,ol,ul);s=Ch(e,ol,ul)}else s=r;else s=Ch(Gl.z,ol,ul);return s}}Rh.DEPTH_BASE="depthBase",Rh.DEPTH="depth",Rh.LINEAR_DEPTH="linearDepth";const Ch=(e,t,r)=>e.add(t).div(t.sub(r)),Mh=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),Ph=(e,t,r)=>t.mul(r).div(r.sub(t).mul(e).sub(r)),Bh=(e,t,r)=>{t=t.max(1e-6).toVar();const s=Wa(e.negate().div(t)),i=Wa(r.div(t));return s.div(i)},Lh=Vi(Rh,Rh.DEPTH_BASE),Fh=Ui(Rh,Rh.DEPTH),Ih=Vi(Rh,Rh.LINEAR_DEPTH).setParameterLength(0,1),Dh=Ih(Ah());Fh.assign=e=>Lh(e);class Vh extends js{static get type(){return"ClippingNode"}constructor(e=Vh.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===Vh.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===Vh.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return ki((()=>{const r=ji().toVar("distanceToPlane"),s=ji().toVar("distanceToGradient"),i=ji(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=il(t);Zc(n,(({i:t})=>{const n=e.element(t);r.assign(Gl.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Uo(s.negate(),s,r))}))}const a=e.length;if(a>0){const t=il(e),n=ji(1).toVar("intersectionClipOpacity");Zc(a,(({i:e})=>{const i=t.element(e);r.assign(Gl.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Uo(s.negate(),s,r).oneMinus())})),i.mulAssign(n.oneMinus())}yn.a.mulAssign(i),yn.a.equal(0).discard()}))()}setupDefault(e,t){return ki((()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=il(t);Zc(r,(({i:t})=>{const r=e.element(t);Gl.dot(r.xyz).greaterThan(r.w).discard()}))}const s=e.length;if(s>0){const t=il(e),r=Ki(!0).toVar("clipped");Zc(s,(({i:e})=>{const s=t.element(e);r.assign(Gl.dot(s.xyz).greaterThan(s.w).and(r))})),r.discard()}}))()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),ki((()=>{const s=il(e),i=nl(t.getClipDistance());Zc(r,(({i:e})=>{const t=s.element(e),r=Gl.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)}))}))()}}Vh.ALPHA_TO_COVERAGE="alphaToCoverage",Vh.DEFAULT="default",Vh.HARDWARE="hardware";const Uh=ki((([e])=>Qa(la(1e4,Za(la(17,e.x).add(la(.1,e.y)))).mul(oa(.1,io(Za(la(13,e.y).add(e.x)))))))),Oh=ki((([e])=>Uh(Yi(Uh(e.xy),e.z)))),kh=ki((([e])=>{const t=To(ao(lo(e.xyz)),ao(co(e.xyz))),r=ji(1).div(ji(.05).mul(t)).toVar("pixScale"),s=Yi(Ha(Xa(Wa(r))),Ha(Ka(Wa(r)))),i=Yi(Oh(Xa(s.x.mul(e.xyz))),Oh(Xa(s.y.mul(e.xyz)))),n=Qa(Wa(r)),a=oa(la(n.oneMinus(),i.x),la(n,i.y)),o=xo(n,n.oneMinus()),u=en(a.mul(a).div(la(2,o).mul(ua(1,o))),a.sub(la(.5,o)).div(ua(1,o)),ua(1,ua(1,a).mul(ua(1,a)).div(la(2,o).mul(ua(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Io(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Gh extends zu{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 zh=(e=0)=>Fi(new Gh(e)),Hh=ki((([e,t])=>xo(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),$h=ki((([e,t])=>xo(e.div(t.oneMinus()),1))).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Wh=ki((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),jh=ki((([e,t])=>Fo(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),_o(.5,e)))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),qh=ki((([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return nn(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"}]}),Xh=ki((([e])=>nn(e.rgb.mul(e.a),e.a)),{color:"vec4",return:"vec4"}),Kh=ki((([e])=>(Hi(e.a.equal(0),(()=>nn(0))),nn(e.rgb.div(e.a),e.a))),{color:"vec4",return:"vec4"});class Yh extends O{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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+_s(this)}build(e){this.setup(e)}setupObserver(e){return new fs(e)}setup(e){e.context.setupNormal=()=>iu(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=iu(this.setupVertex(e),"VERTEX"),i=this.vertexNode||s;let n;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.add(a);const i=nn(s,yn.a).max(0);n=this.setupOutput(e,i),In.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&In.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=nn(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.samples;this.alphaToCoverage&&t>1?s=Fi(new Vh(Vh.ALPHA_TO_COVERAGE)):e.stack.add(Fi(new Vh))}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.add(Fi(new Vh(Vh.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?Bh(Gl.z,ol,ul):Ch(Gl.z,ol,ul))}null!==s&&Fh.assign(s).toStack()}setupPositionView(){return Bl.mul(Vl).xyz}setupModelViewProjection(){return ll.mul(Gl)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Mc}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&ih(t).toStack(),!0===t.isSkinnedMesh&&Yc(t).toStack(),this.displacementMap){const e=Sd("displacementMap","texture"),t=Sd("displacementScale","float"),r=Sd("displacementBias","float");Vl.addAssign(Xl.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Hc(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Gc(t).toStack(),null!==this.positionNode&&Vl.assign(iu(this.positionNode,"POSITION","vec3")),Vl}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&Ki(this.maskNode).not().discard();let r=this.colorNode?nn(this.colorNode):qd;if(!0===this.vertexColors&&t.hasAttribute("color")&&(r=r.mul(zh())),e.instanceColor){r=fn("vec3","vInstanceColor").mul(r)}if(e.isBatchedMesh&&e._colorsTexture){r=fn("vec3","vBatchColor").mul(r)}yn.assign(r);const s=this.opacityNode?ji(this.opacityNode):Yd;yn.a.assign(yn.a.mul(s));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?ji(this.alphaTestNode):jd,yn.a.lessThanEqual(i).discard()),!0===this.alphaHash&&yn.a.lessThan(kh(Vl)).discard();!1===this.transparent&&this.blending===k&&!1===this.alphaToCoverage?yn.a.assign(1):null===i&&yn.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?en(0):yn.rgb}setupNormal(){return this.normalNode?en(this.normalNode):ic}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Sd("envMap","cubeTexture"):Sd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new lh(Ac)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);if(s&&s.isLightingNode&&t.push(s),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Rc;t.push(new ah(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}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=uh(n,t,r,s)}else null!==r&&(a=en(null!==s?Fo(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(bn.assign(en(i||Kd)),a=a.add(bn)),a}setupFog(e,t){const r=e.fogNode;return r&&(In.assign(t),t=nn(r)),t}setupPremultipliedAlpha(e,t){return Xh(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=O.prototype.toJSON.call(this,e),s=vs(this);r.inputNodes={};for(const{property:t,childNode:i}of s)r.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=i(e.textures),s=i(e.images),n=i(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Qh=new G;class Zh extends Yh{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Qh),this.setValues(e)}}const Jh=new z;class ep extends Yh{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Jh),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ji(this.offsetNode):Sc,t=this.dashScaleNode?ji(this.dashScaleNode):Tc,r=this.dashSizeNode?ji(this.dashSizeNode):_c,s=this.gapSizeNode?ji(this.gapSizeNode):vc;Dn.assign(r),Vn.assign(s);const i=au(Hu("lineDistance").mul(t));(e?i.add(e):i).mod(Dn.add(Vn)).greaterThan(Dn).discard()}}let tp=null;class rp extends vh{static get type(){return"ViewportSharedTextureNode"}constructor(e=ph,t=null){null===tp&&(tp=new D),super(e,t,tp)}updateReference(){return this}}const sp=Vi(rp).setParameterLength(0,2),ip=new z;class np extends Yh{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(ip),this.useColor=e.vertexColors,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=H,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.useColor,i=this._useDash,n=this._useWorldUnits,a=ki((({start:e,end:t})=>{const r=ll.element(2).element(2),s=ll.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return nn(Fo(e.xyz,t.xyz,s),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=ki((()=>{const e=Hu("instanceStart"),t=Hu("instanceEnd"),r=nn(Bl.mul(nn(e,1))).toVar("start"),s=nn(Bl.mul(nn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?ji(this.dashScaleNode):Tc,t=this.offsetNode?ji(this.offsetNode):Sc,r=Hu("instanceDistanceStart"),s=Hu("instanceDistanceEnd");let i=Dl.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),fn("float","lineDistance").assign(i)}n&&(fn("vec3","worldStart").assign(r.xyz),fn("vec3","worldEnd").assign(s.xyz));const o=fh.z.div(fh.w),u=ll.element(2).element(3).equal(-1);Hi(u,(()=>{Hi(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=ll.mul(r),d=ll.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=nn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=Fo(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=fn("vec4","worldPos");o.assign(Dl.y.lessThan(.5).select(r,s));const u=Nc.mul(.5);o.addAssign(nn(Dl.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(nn(Dl.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(nn(a.mul(u),0)),Hi(Dl.y.greaterThan(1).or(Dl.y.lessThan(0)),(()=>{o.subAssign(nn(a.mul(2).mul(u),0))}))),g.assign(ll.mul(o));const l=en().toVar();l.assign(Dl.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=Yi(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(Dl.x.lessThan(0).select(e.negate(),e)),Hi(Dl.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(Dl.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(Nc)),e.assign(e.div(fh.w)),g.assign(Dl.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(nn(e,0,0)))}return g}))();const o=ki((({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 Yi(h,p)}));if(this.colorNode=ki((()=>{const e=$u();if(i){const t=this.dashSizeNode?ji(this.dashSizeNode):_c,r=this.gapSizeNode?ji(this.gapSizeNode):vc;Dn.assign(t),Vn.assign(r);const s=fn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(Dn.add(Vn)).greaterThan(Dn).discard()}const a=ji(1).toVar("alpha");if(n){const e=fn("vec3","worldStart"),s=fn("vec3","worldEnd"),n=fn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:en(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(Nc);if(!i)if(r&&t.samples>1){const e=h.fwidth();a.assign(Uo(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.samples>1){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=ji(s.fwidth()).toVar("dlen");Hi(e.y.abs().greaterThan(1),(()=>{a.assign(Uo(i.oneMinus(),i.add(1),s).oneMinus())}))}else Hi(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=Hu("instanceColorStart"),t=Hu("instanceColorEnd");u=Dl.y.lessThan(.5).select(e,t).mul(qd)}else u=qd;return nn(u,a)}))(),this.transparent){const e=this.opacityNode?ji(this.opacityNode):Yd;this.outputNode=nn(this.colorNode.rgb.mul(e).add(sp().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)}}const ap=e=>Fi(e).mul(.5).add(.5),op=new $;class up extends Yh{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(op),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ji(this.opacityNode):Yd;yn.assign(pu(nn(ap(Zl),e),W))}}class lp extends Ks{static get type(){return"EquirectUVNode"}constructor(e=kl){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,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 Yi(t,r)}}const dp=Vi(lp).setParameterLength(0,1);class cp extends j{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 q(5,5,5),n=dp(kl),a=new Yh;a.colorNode=Zu(t,n,0),a.side=S,a.blending=H;const o=new X(i,a),u=new K;u.add(o),t.minFilter===V&&(t.minFilter=Y);const l=new Q(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.currentGenerateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}}const hp=new WeakMap;class pp extends Ks{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=bd(null);const t=new A;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Vs.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===Z||r===J){if(hp.has(e)){const t=hp.get(e);mp(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new cp(r.height);s.fromEquirectangularTexture(t,e),mp(s.texture,e.mapping),this._cubeTexture=s.texture,hp.set(e,s.texture),e.addEventListener("dispose",gp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function gp(e){const t=e.target;t.removeEventListener("dispose",gp);const r=hp.get(t);void 0!==r&&(hp.delete(t),r.dispose())}function mp(e,t){t===Z?e.mapping=R:t===J&&(e.mapping=C)}const fp=Vi(pp).setParameterLength(1);class yp extends nh{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=fp(this.envNode)}}class bp extends nh{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ji(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class xp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Tp extends xp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(nn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(nn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(yn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case re:s.rgb.assign(Fo(s.rgb,s.rgb.mul(i.rgb),ec.mul(tc)));break;case te:s.rgb.assign(Fo(s.rgb,i.rgb,ec.mul(tc)));break;case ee:s.rgb.addAssign(i.rgb.mul(ec.mul(tc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const _p=new se;class vp extends Yh{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(_p),this.setValues(e)}setupNormal(){return jl(Yl)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new bp(Ac)),t}setupOutgoingLight(){return yn.rgb}setupLightingModel(){return new Tp}}const Np=ki((({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))})),Sp=ki((e=>e.diffuseColor.mul(1/Math.PI))),Ep=ki((({dotNH:e})=>Fn.mul(ji(.5)).add(1).mul(ji(1/Math.PI)).mul(e.pow(Fn)))),wp=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(t).clamp(),s=zl.dot(t).clamp(),i=Np({f0:Bn,f90:1,dotVH:s}),n=ji(.25),a=Ep({dotNH:r});return i.mul(n).mul(a)}));class Ap extends Tp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Sp({diffuseColor:yn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(wp({lightDirection:e})).mul(ec))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Sp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const Rp=new ie;class Cp extends Yh{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Rp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yp(t):null}setupLightingModel(){return new Ap(!1)}}const Mp=new ne;class Pp extends Yh{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Mp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new yp(t):null}setupLightingModel(){return new Ap}setupVariants(){const e=(this.shininessNode?ji(this.shininessNode):Xd).max(1e-4);Fn.assign(e);const t=this.specularNode||Qd;Bn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Bp=ki((e=>{if(!1===e.geometry.hasAttribute("normal"))return ji(0);const t=Yl.dFdx().abs().max(Yl.dFdy().abs());return t.x.max(t.y).max(t.z)})),Lp=ki((e=>{const{roughness:t}=e,r=Bp();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s})),Fp=ki((({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(Fa))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Ip=ki((({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(en(e.mul(r),t.mul(s),a).length()),l=a.mul(en(e.mul(i),t.mul(n),o).length());return da(.5,u.add(l)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Dp=ki((({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"}]}),Vp=ji(1/Math.PI),Up=ki((({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=en(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return Vp.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"}]}),Op=ki((({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Zl,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(zl).normalize(),d=n.dot(e).clamp(),c=n.dot(zl).clamp(),h=n.dot(l).clamp(),p=zl.dot(l).clamp();let g,m,f=Np({f0:t,f90:r,dotVH:p});if(Pi(a)&&(f=En.mix(f,i)),Pi(o)){const t=Mn.dot(e),r=Mn.dot(zl),s=Mn.dot(l),i=Pn.dot(e),n=Pn.dot(zl),a=Pn.dot(l);g=Ip({alphaT:Rn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=Up({alphaT:Rn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=Fp({alpha:u,dotNL:d,dotNV:c}),m=Dp({alpha:u,dotNH:h});return f.mul(g).mul(m)})),kp=ki((({roughness:e,dotNV:t})=>{const r=nn(-1,-.0275,-.572,.022),s=nn(1,.0425,1.04,-.04),i=e.mul(r).add(s),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return Yi(-1.04,1.04).mul(n).add(i.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),Gp=ki((e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=kp({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))})),zp=ki((({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(en(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"}]}),Hp=ki((({roughness:e,dotNH:t})=>{const r=e.pow2(),s=ji(1).div(r),i=t.pow2().oneMinus().max(.0078125);return ji(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"}]}),$p=ki((({dotNV:e,dotNL:t})=>ji(1).div(ji(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Wp=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(e).clamp(),s=Zl.dot(zl).clamp(),i=Zl.dot(t).clamp(),n=Hp({roughness:Sn,dotNH:i}),a=$p({dotNV:s,dotNL:r});return Nn.mul(n).mul(a)})),jp=ki((({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=Yi(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"}]}),qp=ki((({f:e})=>{const t=e.length();return To(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Xp=ki((({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,To(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"}]}),Kp=ki((({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=en().toVar();return Hi(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(dn(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=en(0).toVar();f.addAssign(Xp({v1:h,v2:p})),f.addAssign(Xp({v1:p,v2:g})),f.addAssign(Xp({v1:g,v2:m})),f.addAssign(Xp({v1:m,v2:h})),c.assign(en(qp({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"}]}),Yp=ki((({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=en().toVar();return Hi(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=en(0).toVar();d.addAssign(Xp({v1:n,v2:a})),d.addAssign(Xp({v1:a,v2:o})),d.addAssign(Xp({v1:o,v2:l})),d.addAssign(Xp({v1:l,v2:n})),u.assign(en(qp({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"}]}),Qp=1/6,Zp=e=>la(Qp,la(e,la(e,e.negate().add(3)).sub(3)).add(1)),Jp=e=>la(Qp,la(e,la(e,la(3,e).sub(6))).add(4)),eg=e=>la(Qp,la(e,la(e,la(-3,e).add(3)).add(3)).add(1)),tg=e=>la(Qp,Ao(e,3)),rg=e=>Zp(e).add(Jp(e)),sg=e=>eg(e).add(tg(e)),ig=e=>oa(-1,Jp(e).div(Zp(e).add(Jp(e)))),ng=e=>oa(1,tg(e).div(eg(e).add(tg(e)))),ag=(e,t,r)=>{const s=e.uvNode,i=la(s,t.zw).add(.5),n=Xa(i),a=Qa(i),o=rg(a.x),u=sg(a.x),l=ig(a.x),d=ng(a.x),c=ig(a.y),h=ng(a.y),p=Yi(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Yi(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=Yi(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Yi(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=rg(a.y).mul(oa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=sg(a.y).mul(oa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},og=ki((([e,t=ji(3)])=>{const r=Yi(e.size(qi(t))),s=Yi(e.size(qi(t.add(1)))),i=da(1,r),n=da(1,s),a=ag(e,nn(i,r),Xa(t)),o=ag(e,nn(n,s),Ka(t));return Qa(t).mix(a,o)})),ug=ki((([e,t,r,s,i])=>{const n=en(Vo(t.negate(),Ya(e),da(1,s))),a=en(ao(i[0].xyz),ao(i[1].xyz),ao(i[2].xyz));return Ya(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"}]}),lg=ki((([e,t])=>e.mul(Io(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),dg=Sh(),cg=Sh(),hg=ki((([e,t,r],{material:s})=>{const i=(s.side===S?dg:cg).sample(e),n=Wa(gh.x).mul(lg(t,r));return og(i,n)})),pg=ki((([e,t,r])=>(Hi(r.notEqual(0),(()=>{const s=$a(t).negate().div(r);return za(s.negate().mul(e))})),en(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),gg=ki((([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=nn().toVar(),f=en().toVar();const i=d.sub(1).mul(g.mul(.025)),n=en(d.sub(i),d,d.add(i));Zc({start:0,end:3},(({i:i})=>{const d=n.element(i),g=ug(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(nn(y,1))),x=Yi(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Yi(x.x,x.y.oneMinus()));const T=hg(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(pg(ao(g),h,p).element(i)))})),m.a.divAssign(3)}else{const i=ug(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(nn(n,1))),y=Yi(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Yi(y.x,y.y.oneMinus())),m=hg(y,r,d),f=s.mul(pg(ao(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=en(Gp({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return nn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())})),mg=dn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),fg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),yg=ki((({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=Fo(e,t,Uo(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();Hi(a.lessThan(0),(()=>en(1)));const o=a.sqrt(),u=fg(n,e),l=Np({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=ji(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return en(1).add(t).div(en(1).sub(t))})(i.clamp(0,.9999)),g=fg(p,n.toVec3()),m=Np({f0:g,f90:1,dotVH:o}),f=en(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=en(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(en(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Zc({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=en(54856e-17,44201e-17,52481e-17),i=en(1681e3,1795300,2208400),n=en(43278e5,93046e5,66121e5),a=ji(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=en(o.x.add(a),o.y,o.z).div(1.0685e-7),mg.mul(o)})(ji(e).mul(y),ji(e).mul(b)).mul(2);v.addAssign(N.mul(t))})),v.max(en(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"}]}),bg=ki((({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.pow2(),n=Xo(r.lessThan(.25),ji(-339.2).mul(i).add(ji(161.4).mul(r)).sub(25.9),ji(-8.48).mul(i).add(ji(14.3).mul(r)).sub(9.95)),a=Xo(r.lessThan(.25),ji(44).mul(i).sub(ji(23.7).mul(r)).add(3.26),ji(1.97).mul(i).sub(ji(3.27).mul(r)).add(.72));return Xo(r.lessThan(.25),0,ji(.1).mul(r).sub(.025)).add(n.mul(s).add(a).exp()).mul(1/Math.PI).saturate()})),xg=en(.04),Tg=ji(1);class _g extends xp{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}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=en().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=en().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=en().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=en().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=en().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Zl.dot(zl).clamp();this.iridescenceFresnel=yg({outsideIOR:ji(1),eta2:wn,cosTheta1:e,thinFilmThickness:An,baseF0:Bn}),this.iridescenceF0=zp({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Ol,r=gl.sub(Ol).normalize(),s=Jl,i=e.context;i.backdrop=gg(s,r,xn,yn,Bn,Ln,t,El,cl,ll,On,Gn,Hn,zn,this.dispersion?$n:null),i.backdropAlpha=kn,yn.a.mulAssign(Fo(1,i.backdrop.a,kn))}super.start(e)}computeMultiscattering(e,t,r){const s=Zl.dot(zl).clamp(),i=kp({roughness:xn,dotNV:s}),n=(this.iridescenceF0?En.mix(Bn,this.iridescenceF0):Bn).mul(i.x).add(r.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=Bn.add(Bn.oneMinus().mul(.047619)),u=n.mul(o).div(a.mul(o).oneMinus());e.addAssign(n),t.addAssign(u.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(s.mul(Wp({lightDirection:e}))),!0===this.clearcoat){const r=ed.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(Op({lightDirection:e,f0:xg,f90:Tg,roughness:vn,normalView:ed})))}r.directDiffuse.addAssign(s.mul(Sp({diffuseColor:yn.rgb}))),r.directSpecular.addAssign(s.mul(Op({lightDirection:e,f0:Bn,f90:1,roughness:xn,iridescence:this.iridescence,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=Zl,h=zl,p=Gl.toVar(),g=jp({N:c,V:h,roughness:xn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=dn(en(m.x,0,m.y),en(0,1,0),en(m.z,0,m.w)).toVar(),b=Bn.mul(f.x).add(Bn.oneMinus().mul(f.y)).toVar();i.directSpecular.addAssign(e.mul(b).mul(Kp({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(yn).mul(Kp({N:c,V:h,P:p,mInv:dn(1,0,0,0,1,0,0,0,1),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;r.indirectDiffuse.addAssign(t.mul(Sp({diffuseColor:yn})))}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Nn,bg({normal:Zl,viewDir:zl,roughness:Sn}))),!0===this.clearcoat){const e=ed.dot(zl).clamp(),t=Gp({dotNV:e,specularColor:xg,specularF90:Tg,roughness:vn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=en().toVar("singleScattering"),n=en().toVar("multiScattering"),a=r.mul(1/Math.PI);this.computeMultiscattering(i,n,Ln);const o=i.add(n),u=yn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(t.mul(i)),s.indirectSpecular.addAssign(n.mul(a)),s.indirectDiffuse.addAssign(u.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Zl.dot(zl).clamp().add(t),i=xn.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=ed.dot(zl).clamp(),r=Np({dotVH:e,f0:xg,f90:Tg}),s=t.mul(_n.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(_n));t.assign(s)}if(!0===this.sheen){const e=Nn.r.max(Nn.g).max(Nn.b).mul(.157).oneMinus(),r=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(r)}}}const vg=ji(1),Ng=ji(-2),Sg=ji(.8),Eg=ji(-1),wg=ji(.4),Ag=ji(2),Rg=ji(.305),Cg=ji(3),Mg=ji(.21),Pg=ji(4),Bg=ji(4),Lg=ji(16),Fg=ki((([e])=>{const t=en(io(e)).toVar(),r=ji(-1).toVar();return Hi(t.x.greaterThan(t.z),(()=>{Hi(t.x.greaterThan(t.y),(()=>{r.assign(Xo(e.x.greaterThan(0),0,3))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})).Else((()=>{Hi(t.z.greaterThan(t.y),(()=>{r.assign(Xo(e.z.greaterThan(0),2,5))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})),r})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Ig=ki((([e,t])=>{const r=Yi().toVar();return Hi(t.equal(0),(()=>{r.assign(Yi(e.z,e.y).div(io(e.x)))})).ElseIf(t.equal(1),(()=>{r.assign(Yi(e.x.negate(),e.z.negate()).div(io(e.y)))})).ElseIf(t.equal(2),(()=>{r.assign(Yi(e.x.negate(),e.y).div(io(e.z)))})).ElseIf(t.equal(3),(()=>{r.assign(Yi(e.z.negate(),e.y).div(io(e.x)))})).ElseIf(t.equal(4),(()=>{r.assign(Yi(e.x.negate(),e.z).div(io(e.y)))})).Else((()=>{r.assign(Yi(e.x,e.y).div(io(e.z)))})),la(.5,r.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Dg=ki((([e])=>{const t=ji(0).toVar();return Hi(e.greaterThanEqual(Sg),(()=>{t.assign(vg.sub(e).mul(Eg.sub(Ng)).div(vg.sub(Sg)).add(Ng))})).ElseIf(e.greaterThanEqual(wg),(()=>{t.assign(Sg.sub(e).mul(Ag.sub(Eg)).div(Sg.sub(wg)).add(Eg))})).ElseIf(e.greaterThanEqual(Rg),(()=>{t.assign(wg.sub(e).mul(Cg.sub(Ag)).div(wg.sub(Rg)).add(Ag))})).ElseIf(e.greaterThanEqual(Mg),(()=>{t.assign(Rg.sub(e).mul(Pg.sub(Cg)).div(Rg.sub(Mg)).add(Cg))})).Else((()=>{t.assign(ji(-2).mul(Wa(la(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Vg=ki((([e,t])=>{const r=e.toVar();r.assign(la(2,r).sub(1));const s=en(r,1).toVar();return Hi(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"}]}),Ug=ki((([e,t,r,s,i,n])=>{const a=ji(r),o=en(t),u=Io(Dg(a),Ng,n),l=Qa(u),d=Xa(u),c=en(Og(e,o,d,s,i,n)).toVar();return Hi(l.notEqual(0),(()=>{const t=en(Og(e,o,d.add(1),s,i,n)).toVar();c.assign(Fo(c,t,l))})),c})),Og=ki((([e,t,r,s,i,n])=>{const a=ji(r).toVar(),o=en(t),u=ji(Fg(o)).toVar(),l=ji(To(Bg.sub(a),0)).toVar();a.assign(To(a,Bg));const d=ji(Ha(a)).toVar(),c=Yi(Ig(o,u).mul(d.sub(2)).add(1)).toVar();return Hi(u.greaterThan(2),(()=>{c.y.addAssign(d),u.subAssign(3)})),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(la(3,Lg))),c.y.addAssign(la(4,Ha(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(Yi(),Yi())})),kg=ki((({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Ja(s),l=r.mul(u).add(i.cross(r).mul(Za(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return Og(e,l,t,n,a,o)})),Gg=ki((({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=en(Xo(t,r,wo(r,s))).toVar();Hi(h.equal(en(0)),(()=>{h.assign(en(s.z,0,s.x.negate()))})),h.assign(Ya(h));const p=en().toVar();return p.addAssign(i.element(0).mul(kg({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Zc({start:qi(1),end:e},(({i:e})=>{Hi(e.greaterThanEqual(n),(()=>{Jc()}));const t=ji(a.mul(ji(e))).toVar();p.addAssign(i.element(e).mul(kg({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(kg({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))})),nn(p,1)})),zg=[.125,.215,.35,.446,.526,.582],Hg=20,$g=new ae(-1,1,1,-1,0,1),Wg=new oe(90,1),jg=new e;let qg=null,Xg=0,Kg=0;const Yg=(1+Math.sqrt(5))/2,Qg=1/Yg,Zg=[new r(-Yg,Qg,0),new r(Yg,Qg,0),new r(-Qg,0,Yg),new r(Qg,0,Yg),new r(0,Yg,-Qg),new r(0,Yg,Qg),new r(-1,1,-1),new r(1,1,-1),new r(-1,1,1),new r(1,1,1)],Jg=new r,em=new WeakMap,tm=[3,1,5,0,4,2],rm=Vg($u(),Hu("faceIndex")).normalize(),sm=en(rm.x,rm.y,rm.z);class im{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Jg,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}qg=this._renderer.getRenderTarget(),Xg=this._renderer.getActiveCubeFace(),Kg=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!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=um(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=lm(),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===R||e.mapping===C?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?u=zg[o-e+4-1]:0===o&&(u=0),s.push(u);const l=1/(a-2),d=-l,c=1+l,h=[d,d,c,d,c,c,d,d,c,c,d,c],p=6,g=6,m=3,f=2,y=1,b=new Float32Array(m*g*p),x=new Float32Array(f*g*p),T=new Float32Array(y*g*p);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=tm[e];b.set(s,m*g*i),x.set(h,f*g*i);const n=[i,i,i,i,i,i];T.set(n,y*g*i)}const _=new pe;_.setAttribute("position",new ge(b,m)),_.setAttribute("uv",new ge(x,f)),_.setAttribute("faceIndex",new ge(T,y)),t.push(_),i.push(new X(_,null)),n>4&&n--}return{lodPlanes:t,sizeLods:r,sigmas:s,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,s){const i=il(new Array(Hg).fill(0)),n=Zn(new r(0,1,0)),a=Zn(0),o=ji(Hg),u=Zn(0),l=Zn(1),d=Zu(null),c=Zn(0),h=ji(1/t),p=ji(1/s),g=ji(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:sm,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=om("blur");return f.fragmentNode=Gg({...m,latitudinal:u.equal(1)}),em.set(f,m),f}(t,e.width,e.height)}}async _compileMaterial(e){const t=new X(this._lodPlanes[0],e);await this._renderer.compile(t,$g)}_sceneToCubeUV(e,t,r,s,i){const n=Wg;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(jg),u.autoClear=!1;let d=this._backgroundBox;if(null===d){const e=new se({name:"PMREM.Background",side:S,depthWrite:!1,depthTest:!1});d=new X(new q,e)}let c=!1;const h=e.background;h?h.isColor&&(d.material.color.copy(h),e.background=null,c=!0):(d.material.color.copy(jg),c=!0),u.setRenderTarget(s),u.clear(),c&&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;am(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=h}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===R||e.mapping===C;s?null===this._cubemapMaterial&&(this._cubemapMaterial=um(e)):null===this._equirectMaterial&&(this._equirectMaterial=lm(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;am(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,$g)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let t=1;tHg&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${g} samples when the maximum is set to 20`);const m=[];let f=0;for(let e=0;ey-4?s-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(l,$g)}}function nm(e,t){const r=new ue(e,t,{magFilter:Y,minFilter:Y,generateMipmaps:!1,type:ce,format:de,colorSpace:le});return r.texture.mapping=he,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function am(e,t,r,s,i){e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i)}function om(e){const t=new Yh;return t.depthTest=!1,t.depthWrite=!1,t.blending=H,t.name=`PMREM_${e}`,t}function um(e){const t=om("cubemap");return t.fragmentNode=bd(e,sm),t}function lm(e){const t=om("equirect");return t.fragmentNode=Zu(e,dp(sm),0),t}const dm=new WeakMap;function cm(e,t,r){const s=function(e){let t=dm.get(e);void 0===t&&(t=new WeakMap,dm.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 hm extends Ks{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 x;s.isRenderTargetTexture=!0,this._texture=Zu(s),this._width=Zn(0),this._height=Zn(0),this._maxMip=Zn(0),this.updateBeforeType=Vs.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:cm(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new im(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=dd.mul(en(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),Ug(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const pm=Vi(hm).setParameterLength(1,3),gm=new WeakMap;class mm extends nh{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 e=r.isTextureNode?r.value:t[r.property];let s=gm.get(e);void 0===s&&(s=pm(e),gm.set(e,s)),r=s}const s=!0===t.useAnisotropy||t.anisotropy>0?Dd:Zl,i=r.context(fm(xn,s)).mul(ld),n=r.context(ym(Jl)).mul(Math.PI).mul(ld),a=Cu(i),o=Cu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(fm(vn,ed)).mul(ld),t=Cu(e);u.addAssign(t)}}}const fm=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=zl.negate().reflect(t),r=e.mul(e).mix(r,t).normalize(),r=r.transformDirection(cl)),r),getTextureLevel:()=>e}},ym=e=>({getUV:()=>e,getTextureLevel:()=>ji(1)}),bm=new me;class xm extends Yh{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(bm),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new mm(t):null}setupLightingModel(){return new _g}setupSpecular(){const e=Fo(en(.04),yn.rgb,Tn);Bn.assign(e),Ln.assign(1)}setupVariants(){const e=this.metalnessNode?ji(this.metalnessNode):sc;Tn.assign(e);let t=this.roughnessNode?ji(this.roughnessNode):rc;t=Lp({roughness:t}),xn.assign(t),this.setupSpecular(),yn.assign(nn(yn.rgb.mul(e.oneMinus()),yn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Tm=new fe;class _m extends xm{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(Tm),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?ji(this.iorNode):yc;On.assign(e),Bn.assign(Fo(xo(Ro(On.sub(1).div(On.add(1))).mul(Jd),en(1)).mul(Zd),yn.rgb,Tn)),Ln.assign(Fo(Zd,1,Tn))}setupLightingModel(){return new _g(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ji(this.clearcoatNode):nc,t=this.clearcoatRoughnessNode?ji(this.clearcoatRoughnessNode):ac;_n.assign(e),vn.assign(Lp({roughness:t}))}if(this.useSheen){const e=this.sheenNode?en(this.sheenNode):lc,t=this.sheenRoughnessNode?ji(this.sheenRoughnessNode):dc;Nn.assign(e),Sn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ji(this.iridescenceNode):hc,t=this.iridescenceIORNode?ji(this.iridescenceIORNode):pc,r=this.iridescenceThicknessNode?ji(this.iridescenceThicknessNode):gc;En.assign(e),wn.assign(t),An.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?Yi(this.anisotropyNode):cc).toVar();Cn.assign(e.length()),Hi(Cn.equal(0),(()=>{e.assign(Yi(1,0))})).Else((()=>{e.divAssign(Yi(Cn)),Cn.assign(Cn.saturate())})),Rn.assign(Cn.pow2().mix(xn.pow2(),1)),Mn.assign(Fd[0].mul(e.x).add(Fd[1].mul(e.y))),Pn.assign(Fd[1].mul(e.x).sub(Fd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ji(this.transmissionNode):mc,t=this.thicknessNode?ji(this.thicknessNode):fc,r=this.attenuationDistanceNode?ji(this.attenuationDistanceNode):bc,s=this.attenuationColorNode?en(this.attenuationColorNode):xc;if(kn.assign(e),Gn.assign(t),zn.assign(r),Hn.assign(s),this.useDispersion){const e=this.dispersionNode?ji(this.dispersionNode):wc;$n.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?en(this.clearcoatNormalNode):oc}setup(e){e.context.setupClearcoatNormal=()=>iu(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.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 vm extends _g{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(Zl.mul(a)).normalize(),h=ji(zl.dot(c.negate()).saturate().pow(l).mul(d)),p=en(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Nm extends _m{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=ji(.1),this.thicknessAmbientNode=ji(0),this.thicknessAttenuationNode=ji(.1),this.thicknessPowerNode=ji(2),this.thicknessScaleNode=ji(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new vm(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 Sm=ki((({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=Yi(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Sd("gradientMap","texture").context({getUV:()=>i});return en(e.r)}{const e=i.fwidth().mul(.5);return Fo(en(.7),en(1),Uo(ji(.7).sub(e.x),ji(.7).add(e.x),i.x))}}));class Em extends xp{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Sm({normal:ql,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Sp({diffuseColor:yn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Sp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const wm=new ye;class Am extends Yh{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(wm),this.setValues(e)}setupLightingModel(){return new Em}}class Rm extends Ks{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=en(zl.z,0,zl.x.negate()).normalize(),t=zl.cross(e);return Yi(e.dot(Zl),t.dot(Zl)).mul(.495).add(.5)}}const Cm=Ui(Rm),Mm=new be;class Pm extends Yh{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Mm),this.setValues(e)}setupVariants(e){const t=Cm;let r;r=e.material.matcap?Sd("matcap","texture").context({getUV:()=>t}):en(Fo(.2,.8,t.y)),yn.rgb.mulAssign(r.rgb)}}class Bm extends Ks{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode: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=cn(nn(1,0,0,0),nn(0,Ja(e.x),Za(e.x).negate(),0),nn(0,Za(e.x),Ja(e.x),0),nn(0,0,0,1)),i=cn(nn(Ja(e.y),0,Za(e.y),0),nn(0,1,0,0),nn(Za(e.y).negate(),0,Ja(e.y),0),nn(0,0,0,1)),n=cn(nn(Ja(e.z),Za(e.z).negate(),0,0),nn(Za(e.z),Ja(e.z),0,0),nn(0,0,1,0),nn(0,0,0,1));return s.mul(i).mul(n).mul(nn(r,1)).xyz}}}const Lm=Vi(Bm).setParameterLength(2),Fm=new xe;class Im extends Yh{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(Fm),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,s=this.sizeAttenuation,{positionNode:i,rotationNode:n,scaleNode:a}=this,o=Bl.mul(en(i||0));let u=Yi(El[0].xyz.length(),El[1].xyz.length());if(null!==a&&(u=u.mul(Yi(a))),!1===s)if(r.isPerspectiveCamera)u=u.mul(o.z.negate());else{const e=ji(2).div(ll.element(1).element(1));u=u.mul(e.mul(2))}let l=Dl.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>Fi(new mu(e,t,r)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=ji(n||uc),c=Lm(l,d);return nn(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 Dm=new Te;class Vm extends Im{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(Dm),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Bl.mul(en(e||Vl)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:r,scaleNode:s,sizeNode:i}=this,n=Dl.xy.toVar(),a=fh.z.div(fh.w);if(r&&r.isNode){const e=ji(r);n.assign(Lm(n,e))}let o=null!==i?Yi(i):Ec;return!0===this.sizeAttenuation&&(o=o.mul(o.div(Gl.z.negate()))),s&&s.isNode&&(o=o.mul(Yi(s))),n.mulAssign(o.mul(2)),n.assign(n.div(fh.z)),n.y.assign(n.y.mul(a)),n.assign(n.mul(t.w)),t.addAssign(nn(n,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class Um extends xp{constructor(){super(),this.shadowNode=ji(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){yn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(yn.rgb)}}const Om=new _e;class km extends Yh{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Om),this.setValues(e)}setupLightingModel(){return new Um}}const Gm=mn("vec3"),zm=mn("vec3"),Hm=mn("vec3");class $m extends xp{constructor(){super()}start(e){const{material:t,context:r}=e,s=mn("vec3"),i=mn("vec3");Hi(gl.sub(Ol).length().greaterThan(Cl.mul(2)),(()=>{s.assign(gl),i.assign(Ol)})).Else((()=>{s.assign(Ol),i.assign(gl)}));const n=i.sub(s),a=Zn("int").onRenderUpdate((({material:e})=>e.steps)),o=n.length().div(a).toVar(),u=n.normalize().toVar(),l=ji(0).toVar(),d=en(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(o)),Zc(a,(()=>{const i=s.add(u.mul(l)),n=cl.mul(nn(i,1)).xyz;let a;null!==t.depthNode&&(zm.assign(Ih(Mh(n.z,ol,ul))),r.sceneDepthNode=Ih(t.depthNode).toVar()),r.positionWorld=i,r.shadowPositionWorld=i,r.positionView=n,Gm.assign(0),t.scatteringNode&&(a=t.scatteringNode({positionRay:i})),super.start(e),a&&Gm.mulAssign(a);const c=Gm.mul(.01).negate().mul(o).exp();d.mulAssign(c),l.addAssign(o)})),Hm.addAssign(d.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?Hi(r.greaterThanEqual(zm),(()=>{Gm.addAssign(e)})):Gm.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(Yp({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(Hm)}}class Wm extends Yh{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=S,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new $m}}class jm{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,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,null!==this._animationLoop&&this._animationLoop(t,r)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class qm{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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)}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.version),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&&(r+=e.uuid+","),r+=e.receiveShadow+",",bs(r)}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=Ts(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ts(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Ym=[];class Qm{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);Ym[0]=e,Ym[1]=t,Ym[2]=n,Ym[3]=i;let l=u.get(Ym);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Ym,l)):(l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Ym.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new qm)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new Km(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Zm{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 Jm=1,ef=2,tf=3,rf=4,sf=16;class nf extends Zm{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===Jm?this.backend.createAttribute(e):t===ef?this.backend.createIndexAttribute(e):t===tf?this.backend.createStorageAttribute(e):t===rf&&this.backend.createIndirectStorageAttribute(e),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version{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)};t.addEventListener("dispose",r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,tf):this.updateAttribute(e,Jm);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,ef);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,rf)}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}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=of(t),e.set(t,r)):r.version!==af(t)&&(this.attributes.delete(r),r=of(t),e.set(t,r)),s=r}return s}}class lf{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,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):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class df{constructor(e){this.cacheKey=e,this.usedTimes=0}}class cf extends df{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class hf extends df{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let pf=0;class gf{constructor(e,t,r,s=null,i=null){this.id=pf++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class mf extends Zm{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend: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 gf(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.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 gf(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new gf(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.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}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 hf(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 cf(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)}_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 ff extends Zm{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))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?rf:tf;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(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?rf:tf;this.attributes.update(e,r)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(s=!0);const o=t.update(),u=t.texture;o&&this.textures.updateTexture(u);const l=r.get(u);if(void 0!==l.externalTexture||e.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===r.isWebGPUBackend&&void 0===l.texture&&void 0===l.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,u,t.textureNode.value,s),this.textures.updateTexture(u),s=!0),!0===u.isStorageTexture){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)}}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function yf(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 bf(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 xf(e){return(e.transmission>0||e.transmissionNode)&&e.side===E&&!1===e.forceSinglePass}class Tf{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?(xf(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?(xf(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||yf),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||bf),this.transparent.length>1&&this.transparent.sort(t||bf)}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 U,l.format=e.stencilBuffer?we:Ae,l.type=e.stencilBuffer?Re:T,l.image.width=o,l.image.height=u,l.image.depth=a.depth,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{e.removeEventListener("dispose",t);for(let e=0;e0){const s=e.image;if(void 0===s)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)console.warn("THREE.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),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version}if(!0!==r.initialized){r.initialized=!0,r.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}r.version=e.version}getSize(e,t=Mf){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),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.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class Bf extends e{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Lf extends gn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class Ff extends js{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const r=new Li(t);return this._currentCond=Xo(e,r),this.add(this._currentCond)}ElseIf(e,t){const r=new Li(t),s=Xo(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Li(e),this}Switch(e){return this._expressionNode=Fi(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let r=0;r"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=0;for(const r of this.membersLayout){const s=r.type,i=Rs(s)*e,n=t%8,a=n%Cs(s),o=n+a;t+=a,0!==o&&8-oe.name===t));return r?r.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.addInclude(this)}generate(e){return this.getNodeType(e)}}class Vf extends js{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structLayoutNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structLayoutNode.getNodeType(e)}getMemberType(e,t){return this.structLayoutNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structLayoutNode.membersLayout,this.values)}`,this),t.name}}class Uf extends js{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t{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)})),$f=(e,t)=>Ao(la(4,e.mul(ua(1,e))),t),Wf=ki((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),jf=ki((([e])=>en(Wf(e.z.add(Wf(e.y.mul(1)))),Wf(e.z.add(Wf(e.x.mul(1)))),Wf(e.y.add(Wf(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),qf=ki((([e,t,r])=>{const s=en(e).toVar(),i=ji(1.4).toVar(),n=ji(0).toVar(),a=en(s).toVar();return Zc({start:ji(0),end:ji(3),type:"float",condition:"<="},(()=>{const e=en(jf(a.mul(2))).toVar();s.addAssign(e.add(r.mul(ji(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=ji(Wf(s.z.add(Wf(s.x.add(Wf(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 Xf extends js{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null,this.global=!0}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let r=this._candidateFnCall;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._candidateFnCall=r=s(...t)}return r}}const Kf=Vi(Xf),Yf=e=>(...t)=>Kf(e,...t),Qf=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.time)),Zf=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.deltaTime)),Jf=Zn(0,"uint").setGroup(Kn).onRenderUpdate((e=>e.frameId)),ey=ki((([e,t,r=Yi(.5)])=>Lm(e.sub(r),t).add(r))),ty=ki((([e,t,r=Yi(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))})),ry=ki((({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=El.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=El;const i=cl.mul(s);return Pi(t)&&(i[0][0]=El[0].length(),i[0][1]=0,i[0][2]=0),Pi(r)&&(i[1][0]=0,i[1][1]=El[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,ll.mul(i).mul(Vl)})),sy=ki((([e=null])=>{const t=Ih();return Ih(Ah(e)).sub(t).lessThan(0).select(ph,e)}));class iy extends js{static get type(){return"SpriteSheetUVNode"}constructor(e,t=$u(),r=ji(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=r}setup(){const{frameNode:e,uvNode:t,countNode:r}=this,{width:s,height:i}=r,n=e.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=r.reciprocal(),l=Yi(a,o);return t.add(l).mul(u)}}const ny=Vi(iy).setParameterLength(3);class ay extends js{static get type(){return"TriplanarTexturesNode"}constructor(e,t=null,r=null,s=ji(1),i=Vl,n=Xl){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=r,this.scaleNode=s,this.positionNode=i,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:r,scaleNode:s,positionNode:i,normalNode:n}=this;let a=n.abs().normalize();a=a.div(a.dot(en(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=Zu(d,o).mul(a.x),g=Zu(c,u).mul(a.y),m=Zu(h,l).mul(a.z);return oa(p,g,m)}}const oy=Vi(ay).setParameterLength(1,6),uy=new Me,ly=new r,dy=new r,cy=new r,hy=new a,py=new r(0,0,-1),gy=new s,my=new r,fy=new r,yy=new s,by=new t,xy=new ue,Ty=ph.flipX();xy.depthTexture=new U(1,1);let _y=!1;class vy extends Yu{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||xy.texture,Ty),this._reflectorBaseNode=e.reflector||new Ny(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=Fi(new vy({defaultTexture:xy.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._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class Ny extends js{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new Pe,resolution:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1}=t;this.textureNode=e,this.target=r,this.resolution=s,this.generateMipmaps=i,this.bounces=n,this.depth=a,this.updateBeforeType=n?Vs.RENDER:Vs.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolution;t.getDrawingBufferSize(by),e.setSize(Math.round(by.width*r),Math.round(by.height*r))}setup(e){return this._updateResolution(xy,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 ue(0,0,{type:ce}),!0===this.generateMipmaps&&(t.texture.minFilter=Be,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new U),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&_y)return!1;_y=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(by),this._updateResolution(o,s),dy.setFromMatrixPosition(n.matrixWorld),cy.setFromMatrixPosition(r.matrixWorld),hy.extractRotation(n.matrixWorld),ly.set(0,0,1),ly.applyMatrix4(hy),my.subVectors(dy,cy);let u=!1;if(!0===my.dot(ly)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(_y=!1);u=!0}my.reflect(ly).negate(),my.add(dy),hy.extractRotation(r.matrixWorld),py.set(0,0,-1),py.applyMatrix4(hy),py.add(cy),fy.subVectors(dy,py),fy.reflect(ly).negate(),fy.add(dy),a.coordinateSystem=r.coordinateSystem,a.position.copy(my),a.up.set(0,1,0),a.up.applyMatrix4(hy),a.up.reflect(ly),a.lookAt(fy),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),uy.setFromNormalAndCoplanarPoint(ly,dy),uy.applyMatrix4(a.matrixWorldInverse),gy.set(uy.normal.x,uy.normal.y,uy.normal.z,uy.constant);const l=a.projectionMatrix;yy.x=(Math.sign(gy.x)+l.elements[8])/l.elements[0],yy.y=(Math.sign(gy.y)+l.elements[9])/l.elements[5],yy.z=-1,yy.w=(1+l.elements[10])/l.elements[14],gy.multiplyScalar(1/gy.dot(yy));l.elements[2]=gy.x,l.elements[6]=gy.y,l.elements[10]=s.coordinateSystem===d?gy.z-0:gy.z+1-0,l.elements[14]=gy.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const c=s.getRenderTarget(),h=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0,u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),s.setMRT(h),s.setRenderTarget(c),s.autoClear=p,i.visible=!0,_y=!1,this.forceUpdate=!1}}const Sy=new ae(-1,1,1,-1,0,1);class Ey extends pe{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Le([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Le(t,2))}}const wy=new Ey;class Ay extends X{constructor(e=null){super(wy,e),this.camera=Sy,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,Sy)}render(e){e.render(this,Sy)}}const Ry=new t;class Cy extends Yu{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:ce}){const i=new ue(t,r,s);super(i.texture,$u()),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 Ay(new Yh),this.updateBeforeType=Vs.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(Ry),s=r.width*t,i=r.height*t;s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}this._quadMesh.material.fragmentNode=this._rttNode;const t=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){const e=new Yu(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const My=(e,...t)=>Fi(new Cy(Fi(e),...t)),Py=ki((([e,t,r],s)=>{let i;s.renderer.coordinateSystem===d?(e=Yi(e.x,e.y.oneMinus()).mul(2).sub(1),i=nn(en(e,t),1)):i=nn(en(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=nn(r.mul(i));return n.xyz.div(n.w)})),By=ki((([e,t])=>{const r=t.mul(nn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return Yi(s.x,s.y.oneMinus())})),Ly=ki((([e,t,r])=>{const s=ju(Ju(t)),i=Qi(e.mul(s)).toVar(),n=Ju(t,i).toVar(),a=Ju(t,i.sub(Qi(2,0))).toVar(),o=Ju(t,i.sub(Qi(1,0))).toVar(),u=Ju(t,i.add(Qi(1,0))).toVar(),l=Ju(t,i.add(Qi(2,0))).toVar(),d=Ju(t,i.add(Qi(0,2))).toVar(),c=Ju(t,i.add(Qi(0,1))).toVar(),h=Ju(t,i.sub(Qi(0,1))).toVar(),p=Ju(t,i.sub(Qi(0,2))).toVar(),g=io(ua(ji(2).mul(o).sub(a),n)).toVar(),m=io(ua(ji(2).mul(u).sub(l),n)).toVar(),f=io(ua(ji(2).mul(c).sub(d),n)).toVar(),y=io(ua(ji(2).mul(h).sub(p),n)).toVar(),b=Py(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(Py(e.sub(Yi(ji(1).div(s.x),0)),o,r)),b.negate().add(Py(e.add(Yi(ji(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(Py(e.add(Yi(0,ji(1).div(s.y))),c,r)),b.negate().add(Py(e.sub(Yi(0,ji(1).div(s.y))),h,r)));return Ya(wo(x,T))}));class Fy extends L{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Iy extends ge{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class Dy extends js{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Vy=Ui(Dy),Uy=new w,Oy=new a;class ky extends js{static get type(){return"SceneNode"}constructor(e=ky.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,r=null!==this.scene?this.scene:e.scene;let s;return t===ky.BACKGROUND_BLURRINESS?s=_d("backgroundBlurriness","float",r):t===ky.BACKGROUND_INTENSITY?s=_d("backgroundIntensity","float",r):t===ky.BACKGROUND_ROTATION?s=Zn("mat4").label("backgroundRotation").setGroup(Kn).onRenderUpdate((()=>{const e=r.background;return null!==e&&e.isTexture&&e.mapping!==Fe?(Uy.copy(r.backgroundRotation),Uy.x*=-1,Uy.y*=-1,Uy.z*=-1,Oy.makeRotationFromEuler(Uy)):Oy.identity(),Oy})):console.error("THREE.SceneNode: Unknown scope:",t),s}}ky.BACKGROUND_BLURRINESS="backgroundBlurriness",ky.BACKGROUND_INTENSITY="backgroundIntensity",ky.BACKGROUND_ROTATION="backgroundRotation";const Gy=Ui(ky,ky.BACKGROUND_BLURRINESS),zy=Ui(ky,ky.BACKGROUND_INTENSITY),Hy=Ui(ky,ky.BACKGROUND_ROTATION);class $y extends Yu{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.isStorageTextureNode=!0,this.access=Os.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}generate(e,t){let r;return r=null!==this.storeNode?this.generateStore(e):super.generate(e,t),r}toReadWrite(){return this.setAccess(Os.READ_WRITE)}toReadOnly(){return this.setAccess(Os.READ_ONLY)}toWriteOnly(){return this.setAccess(Os.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,"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(e,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e}}const Wy=Vi($y).setParameterLength(1,3),jy=ki((({texture:e,uv:t})=>{const r=1e-4,s=en().toVar();return Hi(t.x.lessThan(r),(()=>{s.assign(en(1,0,0))})).ElseIf(t.y.lessThan(r),(()=>{s.assign(en(0,1,0))})).ElseIf(t.z.lessThan(r),(()=>{s.assign(en(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{s.assign(en(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{s.assign(en(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{s.assign(en(0,0,-1))})).Else((()=>{const r=.01,i=e.sample(t.add(en(-.01,0,0))).r.sub(e.sample(t.add(en(r,0,0))).r),n=e.sample(t.add(en(0,-.01,0))).r.sub(e.sample(t.add(en(0,r,0))).r),a=e.sample(t.add(en(0,0,-.01))).r.sub(e.sample(t.add(en(0,0,r))).r);s.assign(en(i,n,a))})),s.normalize()}));class qy extends Yu{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return en(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!e.isFlipY()||!0!==r.isRenderTargetTexture&&!0!==r.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return jy({texture:this,uv:e})}}const Xy=Vi(qy).setParameterLength(1,3);class Ky extends Td{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 Yy=new WeakMap;class Qy extends Ks{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=Vs.OBJECT,this.updateAfterType=Vs.OBJECT,this.previousModelWorldMatrix=Zn(new a),this.previousProjectionMatrix=Zn(new a).setGroup(Kn),this.previousCameraViewMatrix=Zn(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=Jy(r);this.previousModelWorldMatrix.value.copy(s);const i=Zy(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}){Jy(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?ll:Zn(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(Bl).mul(Vl),s=this.previousProjectionMatrix.mul(t).mul(Ul),i=r.xy.div(r.w),n=s.xy.div(s.w);return ua(i,n)}}function Zy(e){let t=Yy.get(e);return void 0===t&&(t={},Yy.set(e,t)),t}function Jy(e,t=0){const r=Zy(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const eb=Ui(Qy),tb=ki((([e])=>nb(e.rgb))),rb=ki((([e,t=ji(1)])=>t.mix(nb(e.rgb),e.rgb))),sb=ki((([e,t=ji(1)])=>{const r=oa(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 Fo(e.rgb,s,i)})),ib=ki((([e,t=ji(1)])=>{const r=en(.57735,.57735,.57735),s=t.cos();return en(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(Eo(r,e.rgb).mul(s.oneMinus())))))})),nb=(e,t=en(c.getLuminanceCoefficients(new r)))=>Eo(e,t),ab=ki((([e,t=en(1),s=en(0),i=en(1),n=ji(1),a=en(c.getLuminanceCoefficients(new r,le))])=>{const o=e.rgb.dot(en(a)),u=To(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return Hi(u.r.greaterThan(0),(()=>{u.r.assign(l.r)})),Hi(u.g.greaterThan(0),(()=>{u.g.assign(l.g)})),Hi(u.b.greaterThan(0),(()=>{u.b.assign(l.b)})),u.assign(o.add(u.sub(o).mul(n))),nn(u.rgb,e.a)}));class ob extends Ks{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const ub=Vi(ob).setParameterLength(2),lb=new t;class db extends Yu{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class cb extends db{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class hb extends Ks{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 U;i.isRenderTargetTexture=!0,i.name="depth";const n=new ue(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Zn(0),this._cameraFar=Zn(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=Vs.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}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=Fi(new cb(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=Fi(new cb(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=Ph(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=Ch(i,r,s)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===hb.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),lb.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(lb)),this._pixelRatio=i,this.setSize(lb.width,lb.height);const a=t.getRenderTarget(),o=t.getMRT(),u=s.layers.mask;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);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(r,s),t.setRenderTarget(a),t.setMRT(o),s.layers.mask=u}setSize(e,t){this._width=e,this._height=t;const r=this._width*this._pixelRatio*this._resolution,s=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(r,s)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}hb.COLOR="color",hb.DEPTH="depth";class pb extends hb{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(hb.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap}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 Yh;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=S;const t=Xl.negate(),r=ll.mul(Bl),s=ji(1),i=r.mul(nn(Vl,1)),n=r.mul(nn(Vl.add(t),1)),a=Ya(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=nn(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 gb=ki((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),mb=ki((([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"}]}),fb=ki((([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"}]}),yb=ki((([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)})),bb=ki((([e,t])=>{const r=dn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=dn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=yb(e),(e=s.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),xb=dn(en(1.6605,-.1246,-.0182),en(-.5876,1.1329,-.1006),en(-.0728,-.0083,1.1187)),Tb=dn(en(.6274,.0691,.0164),en(.3293,.9195,.088),en(.0433,.0113,.8956)),_b=ki((([e])=>{const t=en(e).toVar(),r=en(t.mul(t)).toVar(),s=en(r.mul(r)).toVar();return ji(15.5).mul(s.mul(r)).sub(la(40.14,s.mul(t))).add(la(31.96,s).sub(la(6.868,r.mul(t))).add(la(.4298,r).add(la(.1191,t).sub(.00232))))})),vb=ki((([e,t])=>{const r=en(e).toVar(),s=dn(en(.856627153315983,.137318972929847,.11189821299995),en(.0951212405381588,.761241990602591,.0767994186031903),en(.0482516061458583,.101439036467562,.811302368396859)),i=dn(en(1.1271005818144368,-.1413297634984383,-.14132976349843826),en(-.11060664309660323,1.157823702216272,-.11060664309660294),en(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ji(-12.47393),a=ji(4.026069);return r.mulAssign(t),r.assign(Tb.mul(r)),r.assign(s.mul(r)),r.assign(To(r,1e-10)),r.assign(Wa(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Io(r,0,1)),r.assign(_b(r)),r.assign(i.mul(r)),r.assign(Ao(To(en(0),r),en(2.2))),r.assign(xb.mul(r)),r.assign(Io(r,0,1)),r})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Nb=ki((([e,t])=>{const r=ji(.76),s=ji(.15);e=e.mul(t);const i=xo(e.r,xo(e.g,e.b)),n=Xo(i.lessThan(.08),i.sub(la(6.25,i.mul(i))),.04);e.subAssign(n);const a=To(e.r,To(e.g,e.b));Hi(a.lessThan(r),(()=>e));const o=ua(1,r),u=ua(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=ua(1,da(1,s.mul(a.sub(u)).add(1)));return Fo(e,en(u),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Sb extends js{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 Eb=Vi(Sb).setParameterLength(1,3);class wb extends Sb{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}getNodeType(e){return this.getNodeFunction(e).type}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 Ab=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};class Rb extends js{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new o,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:ji()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ls(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?Fs(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const Cb=Vi(Rb).setParameterLength(1);class Mb extends Map{get(e,t=null,...r){if(this.has(e))return super.get(e);if(null!==t){const s=t(...r);return this.set(e,s),s}}}class Pb{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const Bb=new Mb;class Lb extends js{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new Mb,this._output=Cb(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const r=this._outputs;return void 0===r[e]?r[e]=Cb(t):r[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const r=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),r[e]=t,r[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),r[e]=t,r[e].events.addEventListener("refresh",this.onRefresh)):void 0===r[e]?(r[e]=Cb(t),r[e].events.addEventListener("refresh",this.onRefresh)):r[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const r=this.getObject()[e];if("function"==typeof r)return r(...t)}async callAsync(e,...t){const r=this.getObject()[e];if("function"==typeof r)return"AsyncFunction"===r.constructor.name?await r(...t):r(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new Pb(this),t=Bb.get("THREE"),r=Bb.get("TSL"),s=this.getMethod(),i=[e,this._local,Bb,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,r];this._object=s(...i);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:ji()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",r="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],r),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[bs(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const r in this.parameters)t.push(this.parameters[r].getCacheKey(e));return xs(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const Fb=Vi(Lb).setParameterLength(1,2);function Ib(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||Gl.z).negate()}const Db=ki((([e,t],r)=>{const s=Ib(r);return Uo(e,t,s)})),Vb=ki((([e],t)=>{const r=Ib(t);return e.mul(e,r,r).negate().exp().oneMinus()})),Ub=ki((([e,t])=>nn(t.toFloat().mix(In.rgb,e.toVec3()),In.a)));let Ob=null,kb=null;class Gb extends js{static get type(){return"RangeNode"}constructor(e=ji(),t=ji()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Ms(this.minNode.value)),r=e.getTypeLength(Ms(this.maxNode.value));return t>r?t:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.minNode.value,n=this.maxNode.value,a=e.getTypeLength(Ms(i)),o=e.getTypeLength(Ms(n));Ob=Ob||new s,kb=kb||new s,Ob.setScalar(0),kb.setScalar(0),1===a?Ob.setScalar(i):i.isColor?Ob.set(i.r,i.g,i.b,1):Ob.set(i.x,i.y,i.z||0,i.w||0),1===o?kb.setScalar(n):n.isColor?kb.set(n.r,n.g,n.b,1):kb.set(n.x,n.y,n.z||0,n.w||0);const l=4,d=l*t.count,c=new Float32Array(d);for(let e=0;eFi(new Hb(e,t)),Wb=$b("numWorkgroups","uvec3"),jb=$b("workgroupId","uvec3"),qb=$b("globalId","uvec3"),Xb=$b("localId","uvec3"),Kb=$b("subgroupSize","uint");const Yb=Vi(class extends js{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class Qb extends qs{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 Zb extends js{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e}label(e){return this.name=e,this}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return Fi(new Qb(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class Jb extends js{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)}getNodeType(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(!(1===r.length&&!0===r[0].isStackNode))return void 0===t.constNode&&(t.constNode=Du(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}Jb.ATOMIC_LOAD="atomicLoad",Jb.ATOMIC_STORE="atomicStore",Jb.ATOMIC_ADD="atomicAdd",Jb.ATOMIC_SUB="atomicSub",Jb.ATOMIC_MAX="atomicMax",Jb.ATOMIC_MIN="atomicMin",Jb.ATOMIC_AND="atomicAnd",Jb.ATOMIC_OR="atomicOr",Jb.ATOMIC_XOR="atomicXor";const ex=Vi(Jb),tx=(e,t,r)=>ex(e,t,r).toStack();let rx;function sx(e){rx=rx||new WeakMap;let t=rx.get(e);return void 0===t&&rx.set(e,t={}),t}function ix(e){const t=sx(e);return t.shadowMatrix||(t.shadowMatrix=Zn("mat4").setGroup(Kn).onRenderUpdate((t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix))))}function nx(e,t=Ol){const r=ix(e).mul(t);return r.xyz.div(r.w)}function ax(e){const t=sx(e);return t.position||(t.position=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld))))}function ox(e){const t=sx(e);return t.targetPosition||(t.targetPosition=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld))))}function ux(e){const t=sx(e);return t.viewPosition||(t.viewPosition=Zn(new r).setGroup(Kn).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const lx=e=>cl.transformDirection(ax(e).sub(ox(e))),dx=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},cx=new WeakMap,hx=[];class px extends js{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=mn("vec3","totalDiffuse"),this.totalSpecularNode=mn("vec3","totalSpecular"),this.outgoingLightNode=mn("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(Fi(e));else{let s=null;if(null!==r&&(s=dx(e.id,r)),null===s){const r=i.getLightNodeClass(e.constructor);if(null===r){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let s=null;cx.has(e)?s=cx.get(e):(s=Fi(new r(e)),cx.set(e,s)),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=en(null!==l?l.mix(g,u):u),s.material.transparent=!0),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 gx extends js{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Vs.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){mx.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ol)}}const mx=mn("vec3","shadowPositionWorld");function fx(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 yx(e,t){return t=fx(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function bx(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 xx(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function Tx(e,t){return t=xx(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function _x(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function vx(e,t,r){return r=Tx(t,r=yx(e,r))}function Nx(e,t,r){bx(e,r),_x(t,r)}var Sx=Object.freeze({__proto__:null,resetRendererAndSceneState:vx,resetRendererState:yx,resetSceneState:Tx,restoreRendererAndSceneState:Nx,restoreRendererState:bx,restoreSceneState:_x,saveRendererAndSceneState:function(e,t,r={}){return r=xx(t,r=fx(e,r))},saveRendererState:fx,saveSceneState:xx});const Ex=new WeakMap,wx=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Zu(e,t.xy).label("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)})),Ax=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=_d("radius","float",r).setGroup(Kn),o=Yi(1).div(n),u=o.x.negate().mul(a),l=o.y.negate().mul(a),d=o.x.mul(a),c=o.y.mul(a),h=u.div(2),p=l.div(2),g=d.div(2),m=c.div(2);return oa(i(t.xy.add(Yi(u,l)),t.z),i(t.xy.add(Yi(0,l)),t.z),i(t.xy.add(Yi(d,l)),t.z),i(t.xy.add(Yi(h,p)),t.z),i(t.xy.add(Yi(0,p)),t.z),i(t.xy.add(Yi(g,p)),t.z),i(t.xy.add(Yi(u,0)),t.z),i(t.xy.add(Yi(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(Yi(g,0)),t.z),i(t.xy.add(Yi(d,0)),t.z),i(t.xy.add(Yi(h,m)),t.z),i(t.xy.add(Yi(0,m)),t.z),i(t.xy.add(Yi(g,m)),t.z),i(t.xy.add(Yi(u,c)),t.z),i(t.xy.add(Yi(0,c)),t.z),i(t.xy.add(Yi(d,c)),t.z)).mul(1/17)})),Rx=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=Yi(1).div(n),o=a.x,u=a.y,l=t.xy,d=Qa(l.mul(n).add(.5));return l.subAssign(d.mul(a)),oa(i(l,t.z),i(l.add(Yi(o,0)),t.z),i(l.add(Yi(0,u)),t.z),i(l.add(a),t.z),Fo(i(l.add(Yi(o.negate(),0)),t.z),i(l.add(Yi(o.mul(2),0)),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u)),t.z),i(l.add(Yi(o.mul(2),u)),t.z),d.x),Fo(i(l.add(Yi(0,u.negate())),t.z),i(l.add(Yi(0,u.mul(2))),t.z),d.y),Fo(i(l.add(Yi(o,u.negate())),t.z),i(l.add(Yi(o,u.mul(2))),t.z),d.y),Fo(Fo(i(l.add(Yi(o.negate(),u.negate())),t.z),i(l.add(Yi(o.mul(2),u.negate())),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u.mul(2))),t.z),i(l.add(Yi(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)})),Cx=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{const s=ji(1).toVar();let i=Zu(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=_o(t.z,i.x);return Hi(n.notEqual(ji(1)),(()=>{const e=t.z.sub(i.x),r=To(0,i.y.mul(i.y));let a=r.div(r.add(e.mul(e)));a=Io(ua(a,.3).div(.95-.3)),s.assign(Io(To(n,a)))})),s})),Mx=ki((([e,t,r])=>{let s=Ol.sub(e).length();return s=s.sub(t).div(r.sub(t)),s=s.saturate(),s})),Px=e=>{let t=Ex.get(e);if(void 0===t){const r=e.isPointLight?(e=>{const t=e.shadow.camera,r=_d("near","float",t).setGroup(Kn),s=_d("far","float",t).setGroup(Kn),i=xl(e);return Mx(i,r,s)})(e):null;t=new Yh,t.colorNode=nn(0,0,0,1),t.depthNode=r,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,Ex.set(e,t)}return t},Bx=new qm,Lx=[],Fx=(e,t,r,s)=>{Lx[0]=e,Lx[1]=t;let i=Bx.get(Lx);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===Ie)&&(s&&(Bs(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,Bx.set(Lx,i)),Lx[0]=null,Lx[1]=null,i},Ix=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanVertical"),a=ji(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));Zc({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(mh.xy,Yi(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=ja(a.sub(n.mul(n)));return Yi(n,l)})),Dx=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanHorizontal"),a=ji(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));Zc({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(mh.xy,Yi(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(oa(d.y.mul(d.y),d.x.mul(d.x)))})),n.divAssign(e),a.divAssign(e);const l=ja(a.sub(n.mul(n)));return Yi(n,l)})),Vx=[wx,Ax,Rx,Cx];let Ux;const Ox=new Ay;class kx extends gx{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture: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,ji(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=_d("bias","float",r).setGroup(Kn);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,s.coordinateSystem===d&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=_d("near","float",r.camera).setGroup(Kn),s=_d("far","float",r.camera).setGroup(Kn);n=Bh(e.negate(),t,s)}return a=en(a.x,a.y.oneMinus(),n.add(i)),a}getShadowFilterFn(e){return Vx[e]}setupRenderTarget(e,t){const r=new U(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=De;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}=e,{light:r,shadow:s}=this,i=t.shadowMap.type,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(s,e);if(s.camera.updateProjectionMatrix(),i===Ie&&!0!==s.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}));let t=Zu(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Zu(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const i=_d("blurSamples","float",s).setGroup(Kn),o=_d("radius","float",s).setGroup(Kn),u=_d("mapSize","vec2",s).setGroup(Kn);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Yh);l.fragmentNode=Ix({samples:i,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Yh),l.fragmentNode=Dx({samples:i,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=_d("intensity","float",s).setGroup(Kn),u=_d("normalBias","float",s).setGroup(Kn),l=ix(r).mul(mx.add(Jl.mul(u))),d=this.setupShadowCoord(e,l),c=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const h=i===Ie&&!0!==s.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:a.texture,depthTexture:h,shadowCoord:d,shadow:s,depthLayer:this.depthLayer});let g=Zu(a.texture,d);n.isArrayTexture&&(g=g.depth(this.depthLayer));const m=Fo(1,p.rgb.mix(g,1),o.mul(g.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return ki((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth),i.render(n,t.camera)}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");Ux=vx(i,n,Ux),n.overrideMaterial=Px(r),i.setRenderObjectFunction(Fx(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===Ie&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,Nx(i,n,Ux)}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),Ox.material=this.vsmMaterialVertical,Ox.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Ox.material=this.vsmMaterialHorizontal,Ox.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let 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 Gx=(e,t)=>Fi(new kx(e,t)),zx=new e,Hx=ki((([e,t])=>{const r=e.toVar(),s=io(r),i=da(1,To(s.x,To(s.y,s.z)));s.mulAssign(i),r.mulAssign(i.mul(t.mul(2).oneMinus()));const n=Yi(r.xy).toVar(),a=t.mul(1.5).oneMinus();return Hi(s.z.greaterThanEqual(a),(()=>{Hi(r.z.greaterThan(0),(()=>{n.x.assign(ua(4,r.x))}))})).ElseIf(s.x.greaterThanEqual(a),(()=>{const e=no(r.x);n.x.assign(r.z.mul(e).add(e.mul(2)))})).ElseIf(s.y.greaterThanEqual(a),(()=>{const e=no(r.y);n.x.assign(r.x.add(e.mul(2)).add(2)),n.y.assign(r.z.mul(e).sub(2))})),Yi(.125,.25).mul(n).add(Yi(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),$x=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s})=>Zu(e,Hx(t,s.y)).compare(r))),Wx=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s,shadow:i})=>{const n=_d("radius","float",i).setGroup(Kn),a=Yi(-1,1).mul(n).mul(s.y);return Zu(e,Hx(t.add(a.xyy),s.y)).compare(r).add(Zu(e,Hx(t.add(a.yyy),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.xyx),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.yyx),s.y)).compare(r)).add(Zu(e,Hx(t,s.y)).compare(r)).add(Zu(e,Hx(t.add(a.xxy),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.yxy),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.xxx),s.y)).compare(r)).add(Zu(e,Hx(t.add(a.yxx),s.y)).compare(r)).mul(1/9)})),jx=ki((({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s})=>{const i=r.xyz.toVar(),n=i.length(),a=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.near)),o=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.far)),u=_d("bias","float",s).setGroup(Kn),l=Zn(s.mapSize).setGroup(Kn),d=ji(1).toVar();return Hi(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),(()=>{const r=n.sub(a).div(o.sub(a)).toVar();r.addAssign(u);const c=i.normalize(),h=Yi(1).div(l.mul(Yi(4,2)));d.assign(e({depthTexture:t,bd3D:c,dp:r,texelSize:h,shadow:s}))})),d})),qx=new s,Xx=new t,Kx=new t;class Yx extends kx{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Ue?$x:Wx}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n}){return jx({filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.getFrameExtents();Kx.copy(t.mapSize),Kx.multiply(a),r.setSize(Kx.width,Kx.height),Xx.copy(t.mapSize);const o=i.autoClear,u=i.getClearColor(zx),l=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const d=t.getViewportCount();for(let e=0;eFi(new Yx(e,t));class Zx extends nh{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Zn(this.color).setGroup(Kn),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vs.FRAME}getHash(){return this.light.uuid}getLightVector(e){return ux(this.light).sub(e.context.positionView||Gl)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return Gx(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?Fi(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}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 Jx=ki((({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)})),eT=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=Jx({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class tT extends Zx{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(2).setGroup(Kn)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return Qx(this.light)}setupDirect(e){return eT({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const rT=ki((([e=t()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()})),sT=ki((([e=$u()],{renderer:t,material:r})=>{const s=Lo(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.samples>1){const e=ji(s.fwidth()).toVar();i=Uo(e.oneMinus(),e.add(1),s).oneMinus()}else i=Xo(s.greaterThan(1),0,1);return i})),iT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Ki(e).toVar();return Xo(n,i,s)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),nT=ki((([e,t])=>{const r=Ki(t).toVar(),s=ji(e).toVar();return Xo(r,s.negate(),s)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),aT=ki((([e])=>{const t=ji(e).toVar();return qi(Xa(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),oT=ki((([e,t])=>{const r=ji(e).toVar();return t.assign(aT(r)),r.sub(ji(t))})),uT=Yf([ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=ji(s).toVar(),l=ji(r).toVar(),d=ji(t).toVar(),c=ji(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]}),ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=en(s).toVar(),l=en(r).toVar(),d=en(t).toVar(),c=en(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]})]),lT=Yf([ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=ji(o).toVar(),m=ji(a).toVar(),f=ji(n).toVar(),y=ji(i).toVar(),b=ji(s).toVar(),x=ji(r).toVar(),T=ji(t).toVar(),_=ji(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]}),ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=en(o).toVar(),m=en(a).toVar(),f=en(n).toVar(),y=en(i).toVar(),b=en(s).toVar(),x=en(r).toVar(),T=en(t).toVar(),_=en(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]})]),dT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Xi(e).toVar(),a=Xi(n.bitAnd(Xi(7))).toVar(),o=ji(iT(a.lessThan(Xi(4)),i,s)).toVar(),u=ji(la(2,iT(a.lessThan(Xi(4)),s,i))).toVar();return nT(o,Ki(a.bitAnd(Xi(1)))).add(nT(u,Ki(a.bitAnd(Xi(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),cT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=Xi(e).toVar(),u=Xi(o.bitAnd(Xi(15))).toVar(),l=ji(iT(u.lessThan(Xi(8)),a,n)).toVar(),d=ji(iT(u.lessThan(Xi(4)),n,iT(u.equal(Xi(12)).or(u.equal(Xi(14))),a,i))).toVar();return nT(l,Ki(u.bitAnd(Xi(1)))).add(nT(d,Ki(u.bitAnd(Xi(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"}]}),hT=Yf([dT,cT]),pT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=rn(e).toVar();return en(hT(n.x,i,s),hT(n.y,i,s),hT(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"}]}),gT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=rn(e).toVar();return en(hT(o.x,a,n,i),hT(o.y,a,n,i),hT(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"}]}),mT=Yf([pT,gT]),fT=ki((([e])=>{const t=ji(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),yT=ki((([e])=>{const t=ji(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),bT=Yf([fT,ki((([e])=>{const t=en(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),xT=Yf([yT,ki((([e])=>{const t=en(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),TT=ki((([e,t])=>{const r=qi(t).toVar(),s=Xi(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(qi(32).sub(r)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),_T=ki((([e,t,r])=>{e.subAssign(r),e.bitXorAssign(TT(r,qi(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(TT(e,qi(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(TT(t,qi(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(TT(r,qi(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(TT(e,qi(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(TT(t,qi(4))),t.addAssign(e)})),vT=ki((([e,t,r])=>{const s=Xi(r).toVar(),i=Xi(t).toVar(),n=Xi(e).toVar();return s.bitXorAssign(i),s.subAssign(TT(i,qi(14))),n.bitXorAssign(s),n.subAssign(TT(s,qi(11))),i.bitXorAssign(n),i.subAssign(TT(n,qi(25))),s.bitXorAssign(i),s.subAssign(TT(i,qi(16))),n.bitXorAssign(s),n.subAssign(TT(s,qi(4))),i.bitXorAssign(n),i.subAssign(TT(n,qi(14))),s.bitXorAssign(i),s.subAssign(TT(i,qi(24))),s})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),NT=ki((([e])=>{const t=Xi(e).toVar();return ji(t).div(ji(Xi(qi(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),ST=ki((([e])=>{const t=ji(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"}]}),ET=Yf([ki((([e])=>{const t=qi(e).toVar(),r=Xi(Xi(1)).toVar(),s=Xi(Xi(qi(3735928559)).add(r.shiftLeft(Xi(2))).add(Xi(13))).toVar();return vT(s.add(Xi(t)),s,s)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(Xi(2)).toVar(),n=Xi().toVar(),a=Xi().toVar(),o=Xi().toVar();return n.assign(a.assign(o.assign(Xi(qi(3735928559)).add(i.shiftLeft(Xi(2))).add(Xi(13))))),n.addAssign(Xi(s)),a.addAssign(Xi(r)),vT(n,a,o)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(Xi(3)).toVar(),o=Xi().toVar(),u=Xi().toVar(),l=Xi().toVar();return o.assign(u.assign(l.assign(Xi(qi(3735928559)).add(a.shiftLeft(Xi(2))).add(Xi(13))))),o.addAssign(Xi(n)),u.addAssign(Xi(i)),l.addAssign(Xi(s)),vT(o,u,l)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),ki((([e,t,r,s])=>{const i=qi(s).toVar(),n=qi(r).toVar(),a=qi(t).toVar(),o=qi(e).toVar(),u=Xi(Xi(4)).toVar(),l=Xi().toVar(),d=Xi().toVar(),c=Xi().toVar();return l.assign(d.assign(c.assign(Xi(qi(3735928559)).add(u.shiftLeft(Xi(2))).add(Xi(13))))),l.addAssign(Xi(o)),d.addAssign(Xi(a)),c.addAssign(Xi(n)),_T(l,d,c),l.addAssign(Xi(i)),vT(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"}]}),ki((([e,t,r,s,i])=>{const n=qi(i).toVar(),a=qi(s).toVar(),o=qi(r).toVar(),u=qi(t).toVar(),l=qi(e).toVar(),d=Xi(Xi(5)).toVar(),c=Xi().toVar(),h=Xi().toVar(),p=Xi().toVar();return c.assign(h.assign(p.assign(Xi(qi(3735928559)).add(d.shiftLeft(Xi(2))).add(Xi(13))))),c.addAssign(Xi(l)),h.addAssign(Xi(u)),p.addAssign(Xi(o)),_T(c,h,p),c.addAssign(Xi(a)),h.addAssign(Xi(n)),vT(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"}]})]),wT=Yf([ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(ET(s,r)).toVar(),n=rn().toVar();return n.x.assign(i.bitAnd(qi(255))),n.y.assign(i.shiftRight(qi(8)).bitAnd(qi(255))),n.z.assign(i.shiftRight(qi(16)).bitAnd(qi(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(ET(n,i,s)).toVar(),o=rn().toVar();return o.x.assign(a.bitAnd(qi(255))),o.y.assign(a.shiftRight(qi(8)).bitAnd(qi(255))),o.z.assign(a.shiftRight(qi(16)).bitAnd(qi(255))),o})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),AT=Yf([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(oT(t.x,r)).toVar(),n=ji(oT(t.y,s)).toVar(),a=ji(ST(i)).toVar(),o=ji(ST(n)).toVar(),u=ji(uT(hT(ET(r,s),i,n),hT(ET(r.add(qi(1)),s),i.sub(1),n),hT(ET(r,s.add(qi(1))),i,n.sub(1)),hT(ET(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return bT(u)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(oT(t.x,r)).toVar(),a=ji(oT(t.y,s)).toVar(),o=ji(oT(t.z,i)).toVar(),u=ji(ST(n)).toVar(),l=ji(ST(a)).toVar(),d=ji(ST(o)).toVar(),c=ji(lT(hT(ET(r,s,i),n,a,o),hT(ET(r.add(qi(1)),s,i),n.sub(1),a,o),hT(ET(r,s.add(qi(1)),i),n,a.sub(1),o),hT(ET(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),hT(ET(r,s,i.add(qi(1))),n,a,o.sub(1)),hT(ET(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),hT(ET(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),hT(ET(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return xT(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),RT=Yf([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(oT(t.x,r)).toVar(),n=ji(oT(t.y,s)).toVar(),a=ji(ST(i)).toVar(),o=ji(ST(n)).toVar(),u=en(uT(mT(wT(r,s),i,n),mT(wT(r.add(qi(1)),s),i.sub(1),n),mT(wT(r,s.add(qi(1))),i,n.sub(1)),mT(wT(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return bT(u)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(oT(t.x,r)).toVar(),a=ji(oT(t.y,s)).toVar(),o=ji(oT(t.z,i)).toVar(),u=ji(ST(n)).toVar(),l=ji(ST(a)).toVar(),d=ji(ST(o)).toVar(),c=en(lT(mT(wT(r,s,i),n,a,o),mT(wT(r.add(qi(1)),s,i),n.sub(1),a,o),mT(wT(r,s.add(qi(1)),i),n,a.sub(1),o),mT(wT(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),mT(wT(r,s,i.add(qi(1))),n,a,o.sub(1)),mT(wT(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),mT(wT(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),mT(wT(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return xT(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),CT=Yf([ki((([e])=>{const t=ji(e).toVar(),r=qi(aT(t)).toVar();return NT(ET(r))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar();return NT(ET(r,s))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar();return NT(ET(r,s,i))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar(),n=qi(aT(t.w)).toVar();return NT(ET(r,s,i,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),MT=Yf([ki((([e])=>{const t=ji(e).toVar(),r=qi(aT(t)).toVar();return en(NT(ET(r,qi(0))),NT(ET(r,qi(1))),NT(ET(r,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar();return en(NT(ET(r,s,qi(0))),NT(ET(r,s,qi(1))),NT(ET(r,s,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar();return en(NT(ET(r,s,i,qi(0))),NT(ET(r,s,i,qi(1))),NT(ET(r,s,i,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(aT(t.x)).toVar(),s=qi(aT(t.y)).toVar(),i=qi(aT(t.z)).toVar(),n=qi(aT(t.w)).toVar();return en(NT(ET(r,s,i,n,qi(0))),NT(ET(r,s,i,n,qi(1))),NT(ET(r,s,i,n,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),PT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=ji(0).toVar(),l=ji(1).toVar();return Zc(a,(()=>{u.addAssign(l.mul(AT(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"}]}),BT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en(0).toVar(),l=ji(1).toVar();return Zc(a,(()=>{u.addAssign(l.mul(RT(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"}]}),LT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar();return Yi(PT(o,a,n,i),PT(o.add(en(qi(19),qi(193),qi(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"}]}),FT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en(BT(o,a,n,i)).toVar(),l=ji(PT(o.add(en(qi(19),qi(193),qi(17))),a,n,i)).toVar();return nn(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"}]}),IT=Yf([ki((([e,t,r,s,i,n,a])=>{const o=qi(a).toVar(),u=ji(n).toVar(),l=qi(i).toVar(),d=qi(s).toVar(),c=qi(r).toVar(),h=qi(t).toVar(),p=Yi(e).toVar(),g=en(MT(Yi(h.add(d),c.add(l)))).toVar(),m=Yi(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Yi(Yi(ji(h),ji(c)).add(m)).toVar(),y=Yi(f.sub(p)).toVar();return Hi(o.equal(qi(2)),(()=>io(y.x).add(io(y.y)))),Hi(o.equal(qi(3)),(()=>To(io(y.x),io(y.y)))),Eo(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"}]}),ki((([e,t,r,s,i,n,a,o,u])=>{const l=qi(u).toVar(),d=ji(o).toVar(),c=qi(a).toVar(),h=qi(n).toVar(),p=qi(i).toVar(),g=qi(s).toVar(),m=qi(r).toVar(),f=qi(t).toVar(),y=en(e).toVar(),b=en(MT(en(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=en(en(ji(f),ji(m),ji(g)).add(b)).toVar(),T=en(x.sub(y)).toVar();return Hi(l.equal(qi(2)),(()=>io(T.x).add(io(T.y)).add(io(T.z)))),Hi(l.equal(qi(3)),(()=>To(io(T.x),io(T.y),io(T.z)))),Eo(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"}]})]),DT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(oT(n.x,a),oT(n.y,o)).toVar(),l=ji(1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(IT(u,e,t,a,o,i,s)).toVar();l.assign(xo(l,r))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),VT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(oT(n.x,a),oT(n.y,o)).toVar(),l=Yi(1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(IT(u,e,t,a,o,i,s)).toVar();Hi(r.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(r)})).ElseIf(r.lessThan(l.y),(()=>{l.y.assign(r)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),UT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(oT(n.x,a),oT(n.y,o)).toVar(),l=en(1e6,1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(IT(u,e,t,a,o,i,s)).toVar();Hi(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)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),OT=Yf([DT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(oT(n.x,a),oT(n.y,o),oT(n.z,u)).toVar(),d=ji(1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{Zc({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(IT(l,e,t,r,a,o,u,i,s)).toVar();d.assign(xo(d,n))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),kT=Yf([VT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(oT(n.x,a),oT(n.y,o),oT(n.z,u)).toVar(),d=Yi(1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{Zc({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(IT(l,e,t,r,a,o,u,i,s)).toVar();Hi(n.lessThan(d.x),(()=>{d.y.assign(d.x),d.x.assign(n)})).ElseIf(n.lessThan(d.y),(()=>{d.y.assign(n)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),GT=Yf([UT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(oT(n.x,a),oT(n.y,o),oT(n.z,u)).toVar(),d=en(1e6,1e6,1e6).toVar();return Zc({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{Zc({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{Zc({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(IT(l,e,t,r,a,o,u,i,s)).toVar();Hi(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)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),zT=ki((([e])=>{const t=e.y,r=e.z,s=en().toVar();return Hi(t.lessThan(1e-4),(()=>{s.assign(en(r,r,r))})).Else((()=>{let i=e.x;i=i.sub(Xa(i)).mul(6).toVar();const n=qi(go(i)),a=i.sub(ji(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());Hi(n.equal(qi(0)),(()=>{s.assign(en(r,l,o))})).ElseIf(n.equal(qi(1)),(()=>{s.assign(en(u,r,o))})).ElseIf(n.equal(qi(2)),(()=>{s.assign(en(o,r,l))})).ElseIf(n.equal(qi(3)),(()=>{s.assign(en(o,u,r))})).ElseIf(n.equal(qi(4)),(()=>{s.assign(en(l,o,r))})).Else((()=>{s.assign(en(r,o,u))}))})),s})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),HT=ki((([e])=>{const t=en(e).toVar(),r=ji(t.x).toVar(),s=ji(t.y).toVar(),i=ji(t.z).toVar(),n=ji(xo(r,xo(s,i))).toVar(),a=ji(To(r,To(s,i))).toVar(),o=ji(a.sub(n)).toVar(),u=ji().toVar(),l=ji().toVar(),d=ji().toVar();return d.assign(a),Hi(a.greaterThan(0),(()=>{l.assign(o.div(a))})).Else((()=>{l.assign(0)})),Hi(l.lessThanEqual(0),(()=>{u.assign(0)})).Else((()=>{Hi(r.greaterThanEqual(a),(()=>{u.assign(s.sub(i).div(o))})).ElseIf(s.greaterThanEqual(a),(()=>{u.assign(oa(2,i.sub(r).div(o)))})).Else((()=>{u.assign(oa(4,r.sub(s).div(o)))})),u.mulAssign(1/6),Hi(u.lessThan(0),(()=>{u.addAssign(1)}))})),en(u,l,d)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),$T=ki((([e])=>{const t=en(e).toVar(),r=sn(ma(t,en(.04045))).toVar(),s=en(t.div(12.92)).toVar(),i=en(Ao(To(t.add(en(.055)),en(0)).div(1.055),en(2.4))).toVar();return Fo(s,i,r)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),WT=(e,t)=>{e=ji(e),t=ji(t);const r=Yi(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Uo(e.sub(r),e.add(r),t)},jT=(e,t,r,s)=>Fo(e,t,r[s].clamp()),qT=(e,t,r,s,i)=>Fo(e,t,WT(r,s[i])),XT=ki((([e,t,r])=>{const s=Ya(e).toVar(),i=ua(ji(.5).mul(t.sub(r)),Ol).div(s).toVar(),n=ua(ji(-.5).mul(t.sub(r)),Ol).div(s).toVar(),a=en().toVar();a.x=s.x.greaterThan(ji(0)).select(i.x,n.x),a.y=s.y.greaterThan(ji(0)).select(i.y,n.y),a.z=s.z.greaterThan(ji(0)).select(i.z,n.z);const o=xo(a.x,a.y,a.z).toVar();return Ol.add(s.mul(o)).toVar().sub(r)})),KT=ki((([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(la(r,r).sub(la(s,s)))),n}));var YT=Object.freeze({__proto__:null,BRDF_GGX:Op,BRDF_Lambert:Sp,BasicPointShadowFilter:$x,BasicShadowFilter:wx,Break:Jc,Const:tu,Continue:()=>Du("continue").toStack(),DFGApprox:kp,D_GGX:Dp,Discard:Vu,EPSILON:Fa,F_Schlick:Np,Fn:ki,INFINITY:Ia,If:Hi,Loop:Zc,NodeAccess:Os,NodeShaderStage:Ds,NodeType:Us,NodeUpdateType:Vs,PCFShadowFilter:Ax,PCFSoftShadowFilter:Rx,PI:Da,PI2:Va,PointShadowFilter:Wx,Return:()=>Du("return").toStack(),Schlick_to_F0:zp,ScriptableNodeResources:Bb,ShaderNode:Li,Stack:$i,Switch:(...e)=>ni.Switch(...e),TBNViewMatrix:Fd,VSMShadowFilter:Cx,V_GGX_SmithCorrelated:Fp,Var:eu,abs:io,acesFilmicToneMapping:bb,acos:ro,add:oa,addMethodChaining:oi,addNodeElement:function(e){console.warn("THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:vb,all:Ua,alphaT:Rn,and:ba,anisotropy:Cn,anisotropyB:Pn,anisotropyT:Mn,any:Oa,append:e=>(console.warn("THREE.TSL: append() has been renamed to Stack()."),$i(e)),array:ea,arrayBuffer:e=>Fi(new si(e,"ArrayBuffer")),asin:to,assign:ra,atan:so,atan2:$o,atomicAdd:(e,t)=>tx(Jb.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>tx(Jb.ATOMIC_AND,e,t),atomicFunc:tx,atomicLoad:e=>tx(Jb.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>tx(Jb.ATOMIC_MAX,e,t),atomicMin:(e,t)=>tx(Jb.ATOMIC_MIN,e,t),atomicOr:(e,t)=>tx(Jb.ATOMIC_OR,e,t),atomicStore:(e,t)=>tx(Jb.ATOMIC_STORE,e,t),atomicSub:(e,t)=>tx(Jb.ATOMIC_SUB,e,t),atomicXor:(e,t)=>tx(Jb.ATOMIC_XOR,e,t),attenuationColor:Hn,attenuationDistance:zn,attribute:Hu,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new Iy(e,r,s);return qc(i,t,e)},backgroundBlurriness:Gy,backgroundIntensity:zy,backgroundRotation:Hy,batch:Hc,bentNormalView:Dd,billboarding:ry,bitAnd:va,bitNot:Na,bitOr:Sa,bitXor:Ea,bitangentGeometry:Md,bitangentLocal:Pd,bitangentView:Bd,bitangentWorld:Ld,bitcast:yo,blendBurn:Hh,blendColor:qh,blendDodge:$h,blendOverlay:jh,blendScreen:Wh,blur:Gg,bool:Ki,buffer:tl,bufferAttribute:vu,bumpMap:Hd,burn:(...e)=>(console.warn('THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.'),Hh(e)),bvec2:Ji,bvec3:sn,bvec4:un,bypass:Pu,cache:Cu,call:ia,cameraFar:ul,cameraIndex:al,cameraNear:ol,cameraNormalMatrix:pl,cameraPosition:gl,cameraProjectionMatrix:ll,cameraProjectionMatrixInverse:dl,cameraViewMatrix:cl,cameraWorldMatrix:hl,cbrt:Bo,cdl:ab,ceil:Ka,checker:rT,cineonToneMapping:fb,clamp:Io,clearcoat:_n,clearcoatNormalView:ed,clearcoatRoughness:vn,code:Eb,color:Wi,colorSpaceToWorking:pu,colorToDirection:e=>Fi(e).mul(2).sub(1),compute:Au,computeSkinning:(e,t=null)=>{const r=new Kc(e);return r.positionNode=qc(new L(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(Lc).toVar(),r.skinIndexNode=qc(new L(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(Lc).toVar(),r.skinWeightNode=qc(new L(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(Lc).toVar(),r.bindMatrixNode=Zn(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Zn(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=tl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,Fi(r)},context:Yo,convert:pn,convertColorSpace:(e,t,r)=>Fi(new cu(Fi(e),t,r)),convertToTexture:(e,...t)=>e.isTextureNode?e:e.isPassNode?e.getTextureNode():My(e,...t),cos:Ja,cross:wo,cubeTexture:bd,cubeTextureBase:yd,cubeToUV:Hx,dFdx:lo,dFdy:co,dashSize:Dn,debug:Gu,decrement:Pa,decrementBefore:Ca,defaultBuildStages:Gs,defaultShaderStages:ks,defined:Pi,degrees:Ga,deltaTime:Zf,densityFog:function(e,t){return console.warn('THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),Ub(e,Vb(t))},densityFogFactor:Vb,depth:Fh,depthPass:(e,t,r)=>Fi(new hb(hb.DEPTH,e,t,r)),difference:So,diffuseColor:yn,directPointLight:eT,directionToColor:ap,directionToFaceDirection:jl,dispersion:$n,distance:No,div:da,dodge:(...e)=>(console.warn('THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.'),$h(e)),dot:Eo,drawIndex:Vc,dynamicBufferAttribute:Nu,element:hn,emissive:bn,equal:ha,equals:bo,equirectUV:dp,exp:za,exp2:Ha,expression:Du,faceDirection:Wl,faceForward:Oo,faceforward:Wo,float:ji,floor:Xa,fog:Ub,fract:Qa,frameGroup:Xn,frameId:Jf,frontFacing:$l,fwidth:mo,gain:(e,t)=>e.lessThan(.5)?$f(e.mul(2),t).div(2):ua(1,$f(la(ua(1,e),2),t).div(2)),gapSize:Vn,getConstNodeType:Bi,getCurrentStack:zi,getDirection:Vg,getDistanceAttenuation:Jx,getGeometryRoughness:Bp,getNormalFromDepth:Ly,getParallaxCorrectNormal:XT,getRoughness:Lp,getScreenPosition:By,getShIrradianceAt:KT,getShadowMaterial:Px,getShadowRenderObjectFunction:Fx,getTextureIndex:kf,getViewPosition:Py,globalId:qb,glsl:(e,t)=>Eb(e,t,"glsl"),glslFn:(e,t)=>Ab(e,t,"glsl"),grayscale:tb,greaterThan:ma,greaterThanEqual:ya,hash:Hf,highpModelNormalViewMatrix:Il,highpModelViewMatrix:Fl,hue:ib,increment:Ma,incrementBefore:Ra,instance:Oc,instanceIndex:Lc,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new Fy(e,r,s);return qc(i,t,e)},instancedBufferAttribute:Su,instancedDynamicBufferAttribute:Eu,instancedMesh:Gc,int:qi,inverseSqrt:qa,inversesqrt:jo,invocationLocalIndex:Dc,invocationSubgroupIndex:Ic,ior:On,iridescence:En,iridescenceIOR:wn,iridescenceThickness:An,ivec2:Qi,ivec3:tn,ivec4:an,js:(e,t)=>Eb(e,t,"js"),label:Qo,length:ao,lengthSq:Lo,lessThan:ga,lessThanEqual:fa,lightPosition:ax,lightProjectionUV:nx,lightShadowMatrix:ix,lightTargetDirection:lx,lightTargetPosition:ox,lightViewPosition:ux,lightingContext:uh,lights:(e=[])=>Fi(new px).setLights(e),linearDepth:Ih,linearToneMapping:gb,localId:Xb,log:$a,log2:Wa,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul($a(r.div(t)));return ji(Math.E).pow(s).mul(t).negate()},luminance:nb,mat2:ln,mat3:dn,mat4:cn,matcapUV:Cm,materialAO:Rc,materialAlphaTest:jd,materialAnisotropy:cc,materialAnisotropyVector:Cc,materialAttenuationColor:xc,materialAttenuationDistance:bc,materialClearcoat:nc,materialClearcoatNormal:oc,materialClearcoatRoughness:ac,materialColor:qd,materialDispersion:wc,materialEmissive:Kd,materialEnvIntensity:ld,materialEnvRotation:dd,materialIOR:yc,materialIridescence:hc,materialIridescenceIOR:pc,materialIridescenceThickness:gc,materialLightMap:Ac,materialLineDashOffset:Sc,materialLineDashSize:_c,materialLineGapSize:vc,materialLineScale:Tc,materialLineWidth:Nc,materialMetalness:sc,materialNormal:ic,materialOpacity:Yd,materialPointSize:Ec,materialReference:Sd,materialReflectivity:tc,materialRefractionRatio:ud,materialRotation:uc,materialRoughness:rc,materialSheen:lc,materialSheenRoughness:dc,materialShininess:Xd,materialSpecular:Qd,materialSpecularColor:Jd,materialSpecularIntensity:Zd,materialSpecularStrength:ec,materialThickness:fc,materialTransmission:mc,max:To,maxMipLevel:Xu,mediumpModelViewMatrix:Ll,metalness:Tn,min:xo,mix:Fo,mixElement:Go,mod:ca,modInt:Ba,modelDirection:Sl,modelNormalMatrix:Ml,modelPosition:wl,modelRadius:Cl,modelScale:Al,modelViewMatrix:Bl,modelViewPosition:Rl,modelViewProjection:Mc,modelWorldMatrix:El,modelWorldMatrixInverse:Pl,morphReference:ih,mrt:zf,mul:la,mx_aastep:WT,mx_cell_noise_float:(e=$u())=>CT(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>ji(e).sub(r).mul(t).add(r),mx_fractal_noise_float:(e=$u(),t=3,r=2,s=.5,i=1)=>PT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec2:(e=$u(),t=3,r=2,s=.5,i=1)=>LT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec3:(e=$u(),t=3,r=2,s=.5,i=1)=>BT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec4:(e=$u(),t=3,r=2,s=.5,i=1)=>FT(e,qi(t),r,s).mul(i),mx_hsvtorgb:zT,mx_noise_float:(e=$u(),t=1,r=0)=>AT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=$u(),t=1,r=0)=>RT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=$u(),t=1,r=0)=>{e=e.convert("vec2|vec3");return nn(RT(e),AT(e.add(Yi(19,73)))).mul(t).add(r)},mx_ramplr:(e,t,r=$u())=>jT(e,t,r,"x"),mx_ramptb:(e,t,r=$u())=>jT(e,t,r,"y"),mx_rgbtohsv:HT,mx_safepower:(e,t=1)=>(e=ji(e)).abs().pow(t).mul(e.sign()),mx_splitlr:(e,t,r,s=$u())=>qT(e,t,r,s,"x"),mx_splittb:(e,t,r,s=$u())=>qT(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:$T,mx_transform_uv:(e=1,t=0,r=$u())=>r.mul(e).add(t),mx_worley_noise_float:(e=$u(),t=1)=>OT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec2:(e=$u(),t=1)=>kT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec3:(e=$u(),t=1)=>GT(e.convert("vec2|vec3"),t,qi(1)),negate:oo,neutralToneMapping:Nb,nodeArray:Di,nodeImmutable:Ui,nodeObject:Fi,nodeObjects:Ii,nodeProxy:Vi,normalFlat:Kl,normalGeometry:ql,normalLocal:Xl,normalMap:Od,normalView:Zl,normalViewGeometry:Yl,normalWorld:Jl,normalWorldGeometry:Ql,normalize:Ya,not:Ta,notEqual:pa,numWorkgroups:Wb,objectDirection:yl,objectGroup:Yn,objectPosition:xl,objectRadius:vl,objectScale:Tl,objectViewPosition:_l,objectWorldMatrix:bl,oneMinus:uo,or:xa,orthographicDepthToViewZ:(e,t,r)=>t.sub(r).mul(e).sub(t),oscSawtooth:(e=Qf)=>e.fract(),oscSine:(e=Qf)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=Qf)=>e.fract().round(),oscTriangle:(e=Qf)=>e.add(.5).fract().mul(2).sub(1).abs(),output:In,outputStruct:Of,overlay:(...e)=>(console.warn('THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),jh(e)),overloadingFn:Yf,parabola:$f,parallaxDirection:Id,parallaxUV:(e,t)=>e.sub(Id.mul(t)),parameter:(e,t)=>Fi(new Lf(e,t)),pass:(e,t,r)=>Fi(new hb(hb.COLOR,e,t,r)),passTexture:(e,t)=>Fi(new db(e,t)),pcurve:(e,t,r)=>Ao(da(Ao(e,t),oa(Ao(e,t),Ao(ua(1,e),r))),1/t),perspectiveDepthToViewZ:Ph,pmremTexture:pm,pointShadow:Qx,pointUV:Vy,pointWidth:Un,positionGeometry:Dl,positionLocal:Vl,positionPrevious:Ul,positionView:Gl,positionViewDirection:zl,positionWorld:Ol,positionWorldDirection:kl,posterize:ub,pow:Ao,pow2:Ro,pow3:Co,pow4:Mo,premultiplyAlpha:Xh,property:mn,radians:ka,rand:ko,range:zb,rangeFog:function(e,t,r){return console.warn('THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),Ub(e,Db(t,r))},rangeFogFactor:Db,reciprocal:po,reference:_d,referenceBuffer:vd,reflect:vo,reflectVector:pd,reflectView:cd,reflector:e=>Fi(new vy(e)),refract:Vo,refractVector:gd,refractView:hd,reinhardToneMapping:mb,remap:Lu,remapClamp:Fu,renderGroup:Kn,renderOutput:Ou,rendererReference:yu,rotate:Lm,rotateUV:ey,roughness:xn,round:ho,rtt:My,sRGBTransferEOTF:uu,sRGBTransferOETF:lu,sampler:e=>(!0===e.isNode?e:Zu(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Zu(e)).convert("samplerComparison"),saturate:Do,saturation:rb,screen:(...e)=>(console.warn('THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.'),Wh(e)),screenCoordinate:mh,screenSize:gh,screenUV:ph,scriptable:Fb,scriptableValue:Cb,select:Xo,setCurrentStack:Gi,shaderStages:zs,shadow:Gx,shadowPositionWorld:mx,shapeCircle:sT,sharedUniformGroup:qn,sheen:Nn,sheenRoughness:Sn,shiftLeft:wa,shiftRight:Aa,shininess:Fn,sign:no,sin:Za,sinc:(e,t)=>Za(Da.mul(t.mul(e).sub(1))).div(Da.mul(t.mul(e).sub(1))),skinning:Yc,smoothstep:Uo,smoothstepElement:zo,specularColor:Bn,specularF90:Ln,spherizeUV:ty,split:(e,t)=>Fi(new Zs(Fi(e),t)),spritesheetUV:ny,sqrt:ja,stack:If,step:_o,stepElement:Ho,storage:qc,storageBarrier:()=>Yb("storage").toStack(),storageObject:(e,t,r)=>(console.warn('THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),qc(e,t,r).setPBO(!0)),storageTexture:Wy,string:(e="")=>Fi(new si(e,"string")),struct:(e,t=null)=>{const r=new Df(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;eYb("texture").toStack(),textureBicubic:og,textureCubeUV:Ug,textureLoad:Ju,textureSize:ju,textureStore:(e,t,r)=>{const s=Wy(e,t,r);return null!==r&&s.toStack(),s},thickness:Gn,time:Qf,timerDelta:(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),Zf.mul(e)),timerGlobal:(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),Qf.mul(e)),timerLocal:(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),Qf.mul(e)),toneMapping:xu,toneMappingExposure:Tu,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>Fi(new pb(t,r,Fi(s),Fi(i),Fi(n))),transformDirection:Po,transformNormal:td,transformNormalToView:rd,transformedClearcoatNormalView:nd,transformedNormalView:sd,transformedNormalWorld:id,transmission:kn,transpose:fo,triNoise3D:qf,triplanarTexture:(...e)=>oy(...e),triplanarTextures:oy,trunc:go,uint:Xi,uniform:Zn,uniformArray:il,uniformCubeTexture:(e=md)=>yd(e),uniformGroup:jn,uniformTexture:(e=Ku)=>Zu(e),unpremultiplyAlpha:Kh,userData:(e,t,r)=>Fi(new Ky(e,t,r)),uv:$u,uvec2:Zi,uvec3:rn,uvec4:on,varying:au,varyingProperty:fn,vec2:Yi,vec3:en,vec4:nn,vectorComponents:Hs,velocity:eb,vertexColor:zh,vertexIndex:Bc,vertexStage:ou,vibrance:sb,viewZToLogarithmicDepth:Bh,viewZToOrthographicDepth:Ch,viewZToPerspectiveDepth:Mh,viewport:fh,viewportCoordinate:bh,viewportDepthTexture:Ah,viewportLinearDepth:Dh,viewportMipTexture:Sh,viewportResolution:Th,viewportSafeUV:sy,viewportSharedTexture:sp,viewportSize:yh,viewportTexture:Nh,viewportUV:xh,wgsl:(e,t)=>Eb(e,t,"wgsl"),wgslFn:(e,t)=>Ab(e,t,"wgsl"),workgroupArray:(e,t)=>Fi(new Zb("Workgroup",e,t)),workgroupBarrier:()=>Yb("workgroup").toStack(),workgroupId:jb,workingToColorSpace:hu,xor:_a});const QT=new Bf;class ZT extends Zm{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(QT),QT.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(QT),QT.a=1,n=!0;else if(!0===i.isNode){const o=this.get(e),u=i;QT.copy(s._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=Yo(nn(u).mul(zy),{getUV:()=>Hy.mul(Ql),getTextureLevel:()=>Gy});let h=Mc;h=h.setZ(h.w);const p=new Yh;function g(){i.removeEventListener("dispose",g),l.material.dispose(),l.geometry.dispose()}p.name="Background.material",p.side=S,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=h,p.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new X(new Oe(1,32,32),p),l.frustumCulled=!1,l.name="Background.mesh",l.onBeforeRender=function(e,t,r){this.matrixWorld.copyPosition(r.matrixWorld)},i.addEventListener("dispose",g)}const d=u.getCacheKey();o.backgroundCacheKey!==d&&(o.backgroundMeshNode.node=nn(u).mul(zy),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=d),t.unshift(l,l.geometry,l.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?QT.set(0,0,0,1):"alpha-blend"===a&&QT.set(0,0,0,0),!0===s.autoClear||!0===n){const m=r.clearColorValue;m.r=QT.r,m.g=QT.g,m.b=QT.b,m.a=QT.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),r.depthClearValue=s._clearDepth,r.stencilClearValue=s._clearStencil,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 JT=0;class e_{constructor(e="",t=[],r=0,s=[]){this.name=e,this.bindings=t,this.index=r,this.bindingsReference=s,this.id=JT++}}class t_{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 e_(t.name,[],t.index,t);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class r_{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class s_{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class i_{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class n_ extends i_{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class a_{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let o_=0;class u_{constructor(e=null){this.id=o_++,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 l_{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class d_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class c_ extends d_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class h_ extends d_{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class p_ extends d_{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class g_ extends d_{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class m_ extends d_{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class f_ extends d_{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class y_ extends d_{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class b_ extends d_{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class x_ extends c_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class T_ extends h_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class __ extends p_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class v_ extends g_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class N_ extends m_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class S_ extends f_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class E_ extends y_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class w_ extends b_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const A_=new WeakMap,R_=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),C_=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class M_{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.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=If(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new u_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=A_.get(this.renderer);return void 0===e&&(e=new qm,A_.set(this.renderer,e)),e}createRenderTarget(e,t,r){return new ue(e,t,r)}createCubeRenderTarget(e,t){return new cp(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=this.getBindGroupsCache(),s=[];let i,n=!0;for(const e of t)s.push(e),n=n&&!0!==e.groupNode.shared;return n?(i=r.get(s),void 0===i&&(i=new e_(e,s,this.bindingsIndexes[e].group,s),r.set(s,i))):i=new e_(e,s,this.bindingsIndexes[e].group,s),i}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 zs)for(const s in r[e]){const i=r[e][s];(t[s]||(t[s]=[])).push(...i)}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")}( ${C_(n.r)}, ${C_(n.g)}, ${C_(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 r_(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===_)return"int";if(t===T)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=Es(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return R_.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 ze||!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")}addStack(){return this.stack=If(this.stack),this.stacks.push(zi()||this.stack),Gi(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Gi(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);let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new r_("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}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 e=this.structs.index++;null===r&&(r="StructType"+e),n=new l_(r,t),this.structs[s].push(n),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 s_(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,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=this.getArrayCount(e);o=new i_(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 n_(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,console.warn(`THREE.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 a_("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 wb,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 Lf(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,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 u_,this.stack=If();for(const r of Gs)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(){console.warn("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(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e){let t="";const r=this.vars[e];if(void 0!==r)for(const e of r)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("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(){console.warn("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}build(){const{object:e,material:t,renderer:r}=this;if(null!==t){let e=r.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new Yh),e.build(this)}else this.addFlow("compute",e);for(const e of Gs){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of zs){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}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new x_(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new T_(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new __(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new v_(e);if("color"===t)return new N_(e);if("mat2"===t)return new S_(e);if("mat3"===t)return new E_(e);if("mat4"===t)return new w_(e);throw new Error(`Uniform "${t}" not declared.`)}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${He} - Node System\n`}*[Symbol.iterator](){}}class P_{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.frameId&&!1!==e.update(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.renderId&&!1!==e.update(this)&&t.set(r,this.renderId)}else t===Vs.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 B_{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}B_.isNodeFunctionInput=!0;class L_ extends Zx{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:lx(this.light),lightColor:e}}}const F_=new a,I_=new a;let D_=null;class V_ extends Zx{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Zn(new r).setGroup(Kn),this.halfWidth=Zn(new r).setGroup(Kn),this.updateType=Vs.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;I_.identity(),F_.copy(t.matrixWorld),F_.premultiply(r),I_.extractRotation(F_),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(I_),this.halfHeight.value.applyMatrix4(I_)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Zu(D_.LTC_FLOAT_1),r=Zu(D_.LTC_FLOAT_2)):(t=Zu(D_.LTC_HALF_1),r=Zu(D_.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:ux(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){D_=e}}class U_ extends Zx{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Zn(0).setGroup(Kn),this.penumbraCosNode=Zn(0).setGroup(Kn),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(0).setGroup(Kn),this.colorNode=Zn(this.color).setGroup(Kn)}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 Uo(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=nx(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(lx(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=Jx({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=Zu(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 O_ extends U_{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=Zu(r,Yi(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}const k_=ki((([e,t])=>{const r=e.abs().sub(t);return ao(To(r,0)).add(xo(To(r.x,r.y),0))}));class G_ extends U_{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=this.penumbraCosNode,r=this.getLightCoord(e),s=r.xyz.div(r.w),i=k_(s.xy.sub(Yi(.5)),Yi(.5)),n=da(-1,ua(1,ro(t)).sub(1));return Do(i.mul(-2).mul(n))}}class z_ extends Zx{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class H_ extends Zx{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=ax(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Zn(new e).setGroup(Kn)}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=Jl.dot(s).mul(.5).add(.5),n=Fo(r,t,i);e.context.irradiance.addAssign(n)}}class $_ extends Zx{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=il(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=KT(Jl,this.lightProbe);e.context.irradiance.addAssign(t)}}class W_{parseFunction(){console.warn("Abstract function.")}}class j_{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){console.warn("Abstract function.")}}j_.isNodeFunction=!0;const q_=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,X_=/[a-z_0-9]+/gi,K_="#pragma main";class Y_ extends j_{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(K_),r=-1!==t?e.slice(t+12):e,s=r.match(q_);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=X_.exec(i));)n.push(a);const o=[];let u=0;for(;u0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,(()=>{if(!0===r.isCubeTexture||r.mapping===Z||r.mapping===J||r.mapping===he){if(e.backgroundBlurriness>0||r.mapping===he)return pm(r);{let e;return e=!0===r.isCubeTexture?bd(r):Zu(r),fp(e)}}if(!0===r.isTexture)return Zu(r,ph.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&console.error("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=_d("color","color",r).setGroup(Kn),t=_d("density","float",r).setGroup(Kn);return Ub(e,Vb(t))}if(r.isFog){const e=_d("color","color",r).setGroup(Kn),t=_d("near","float",r).setGroup(Kn),s=_d("far","float",r).setGroup(Kn);return Ub(e,Db(t,s))}console.error("THREE.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?bd(r):!0===r.isTexture?Zu(r):void console.error("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}hasOutputChange(e){return Z_.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,r=this.getOutputCacheKey(),s=e.isArrayTexture?Xy(e,en(ph,nl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Zu(e,ph).renderOutput(t.toneMapping,t.currentColorSpace);return Z_.set(e,r),s}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 P_,this.nodeBuilderCache=new Map,this.cacheLib={}}}const rv=new Me;class sv{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;i0,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 cv(i.framebufferWidth,i.framebufferHeight,{format:de,type:Ce,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),n.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,i.layers.mask=n.layers.mask|a.layers.mask;const o=e.parent,u=i.cameras;mv(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 xv(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 Tv(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(e,t,this._renderTarget),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(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 tv(this,r),this._animation=new jm(this._nodes,this.info),this._attributes=new nf(r),this._background=new ZT(this,this._nodes),this._geometries=new uf(this._attributes,this.info),this._textures=new Pf(this,r,this.info),this._pipelines=new mf(r,this._nodes),this._bindings=new ff(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Qm(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new vf(this.lighting),this._bundles=new av,this._renderContexts=new Cf,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}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._compilationPromises,u=!0===e.isScene?e:_v;null===r&&(r=e);const l=this._renderTarget,d=this._renderContexts.get(r,t,l),c=this._activeMipmapLevel,h=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,s.renderId++,s.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new sv),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,d.clippingContext),r!==e&&r.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);d.textures=e.textures,d.depthTexture=e.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(u,p,d);const g=p.opaque,m=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,y),!0===this.transparent&&m.length>0&&this._renderTransparents(m,f,t,u,y),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=Fl,this.overrideNodes.modelNormalViewMatrix=Il):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===Fl&&this.overrideNodes.modelNormalViewMatrix===Il}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i),u=this.backend.get(o);void 0===u.renderContexts&&(u.renderContexts=new Set);const l=s.version!==u.version,d=!1===u.renderContexts.has(a)||l;if(u.renderContexts.add(a),d){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>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=T,p.viewport=!1===p.viewportValue.equals(Nv),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Nv),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new sv),p.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const _=t.isArrayCamera?Ev:Sv;t.isArrayCamera||(wv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_.setFromProjectionMatrix(wv,g));const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,p.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=h,p.depth=h.depthBuffer,p.stencil=h.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=d,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._background.update(u,v,p),p.camera=t,this.backend.beginRender(p);const{bundles:N,lightsNode:S,transparentDoublePass:E,transparent:w,opaque:A}=v;return N.length>0&&this._renderBundles(N,u,S),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,S),!0===this.transparent&&w.length>0&&this._renderTransparents(w,E,t,u,S),this.backend.finishRender(p),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==s&&(this.setRenderTarget(l,d,c),this._renderOutput(h)),u.onAfterRender(this,e,t,h),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,r);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.getForClear(s),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,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){!1===this._initialized&&await this.init(),this.clear(e,t,r)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:p}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:le}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,r=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const s=this.backend,i=this._pipelines,n=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(const t of o){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),n.delete(t),a.delete(t)};t.addEventListener("dispose",e);const r=t.onInitFunction;null!==r&&r.call(t,{renderer:this})}a.updateForCompute(t),n.updateForCompute(t);const r=n.getForCompute(t),o=i.getForCompute(t,r);s.compute(e,t,r,o)}s.finishCompute(e),t.renderId=r}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=Av.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Av.copy(t).floor()}else t=Av.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)}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)}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?Ev:Sv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&Av.setFromMatrixPosition(e.matrixWorld).applyMatrix4(wv);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,Av.z,null,i)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?Ev:Sv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Av.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(wv)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=S;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=je;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=E}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(c=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(d=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(l=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&i.side===E&&!1===i.forceSinglePass?(i.side=S,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=je,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=E):this._handleObjectFunction(e,i,t,r,a,n,o,u),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==d&&(t.overrideMaterial.colorNode=d),e.onAfterRender(this,t,r,s,i,n)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n;const l=this._nodes.needsRefresh(u);if(l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u)}_createObjectPipeline(e,t,r,s,i,n,a,o){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)}get compile(){return this.compileAsync}}class Cv{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class Mv extends Cv{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(sf-e%sf)%sf;var e}get buffer(){return this._buffer}update(){return!0}}class Pv extends Mv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Bv=0;class Lv extends Pv{constructor(e,t){super("UniformBuffer_"+Bv++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class Fv extends Pv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r0?s:"";t=`${e.name} {\n\t${r} ${i.name}[${n}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,n=!0}const a=i.node.precision;if(null!==a&&(t=Hv[a]+" "+t),n){t="\t"+t;const e=i.groupNode.name;(s[e]||(s[e]=[])).push(t)}else t="uniform "+t,r.push(t)}let i="";for(const t in s){const r=s[t];i+=this._getGLSLUniformStruct(e+"_"+t,r.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==_){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+=`${Wv[s.interpolationType]||s.interpolationType} ${jv[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+=`${Wv[e.interpolationType]||e.interpolationType} ${jv[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`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,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=$v[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)}$v[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];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r}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 Ov(i.name,i.node,s),u.push(a);else if("cubeTexture"===t)a=new kv(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new Gv(i.name,i.node,s),u.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new Lv(e,s);t.name=e.name,u.push(t),a=t}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let n=e[o];void 0===n&&(n=new Dv(r+"_"+o,s),e[o]=n,u.push(n)),a=this.getNodeUniform(i,t),n.addUniform(a)}n.uniformGPU=a}return i}}let Kv=null,Yv=null;class Qv{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void pt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void pt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Kv=Kv||new t,this.renderer.getDrawingBufferSize(Kv)}setScissorTest(){}getClearColor(){const e=this.renderer;return Yv=Yv||new Bf,e.getClearColor(Yv),Yv.getRGB(Yv),Yv}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${He} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let Zv,Jv,eN=0;class tN{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 rN{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(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===_,id:eN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new tN(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;e1?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 nN,aN,oN,uN=!1;class lN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===uN&&(this._init(),uN=!0)}_init(){const e=this.gl;nN={[Nr]:e.REPEAT,[vr]:e.CLAMP_TO_EDGE,[_r]:e.MIRRORED_REPEAT},aN={[v]:e.NEAREST,[Sr]:e.NEAREST_MIPMAP_NEAREST,[Ge]:e.NEAREST_MIPMAP_LINEAR,[Y]:e.LINEAR,[ke]:e.LINEAR_MIPMAP_NEAREST,[V]:e.LINEAR_MIPMAP_LINEAR},oN={[Pr]:e.NEVER,[Mr]:e.ALWAYS,[De]:e.LESS,[Cr]:e.LEQUAL,[Rr]:e.EQUAL,[Ar]:e.GEQUAL,[wr]:e.GREATER,[Er]: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=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(r===n.FLOAT&&(o=n.R32F),r===n.HALF_FLOAT&&(o=n.R16F),r===n.UNSIGNED_BYTE&&(o=n.R8),r===n.UNSIGNED_SHORT&&(o=n.R16),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.R8UI),r===n.UNSIGNED_SHORT&&(o=n.R16UI),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RG&&(r===n.FLOAT&&(o=n.RG32F),r===n.HALF_FLOAT&&(o=n.RG16F),r===n.UNSIGNED_BYTE&&(o=n.RG8),r===n.UNSIGNED_SHORT&&(o=n.RG16),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RG8UI),r===n.UNSIGNED_SHORT&&(o=n.RG16UI),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RGB){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGB32F),r===n.HALF_FLOAT&&(o=n.RGB16F),r===n.UNSIGNED_BYTE&&(o=n.RGB8),r===n.UNSIGNED_SHORT&&(o=n.RGB16),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8:n.RGB8),r===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),r===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5)}if(t===n.RGB_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGB8UI),r===n.UNSIGNED_SHORT&&(o=n.RGB16UI),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGBA32F),r===n.HALF_FLOAT&&(o=n.RGBA16F),r===n.UNSIGNED_BYTE&&(o=n.RGBA8),r===n.UNSIGNED_SHORT&&(o=n.RGBA16),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8_ALPHA8:n.RGBA8),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),r===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(r===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),r===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),r===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&r===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,n=c.getPrimaries(c.workingColorSpace),a=t.colorSpace===b?null:c.getPrimaries(t.colorSpace),o=t.colorSpace===b||n===a?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),r.texParameteri(e,r.TEXTURE_WRAP_S,nN[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,nN[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,nN[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,aN[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,l=t.minFilter===Y&&u?V:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,aN[l]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,oN[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===v)return;if(t.minFilter!==Ge&&t.minFilter!==V)return;if(t.type===I&&!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.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,isDefault:!0})}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.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,{textureGPU:i,glTextureType:n,glFormat:a,glType:o}=s.get(t),{width:u,height:l}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(n,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(n,0,0,0,u,l,a,o,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,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();o.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),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}}function dN(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 cN{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 hN{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const pN={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class gN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const 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){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,r]of this.queryStates)if("ended"===r){const r=this.queries[t];e.push(this.resolveQuery(r))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let 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){console.error("Error checking query:",e),t(this.lastValue)}};n()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}const yN=new t;class bN extends Qv{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.samples>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 cN(this),this.capabilities=new hN(this),this.attributeUtils=new rN(this),this.textureUtils=new lN(this),this.bufferRenderer=new gN(this),this.state=new sN(this),this.utils=new iN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return l}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,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&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new fN(this.gl,t,2048));const r=this.timestampQueryPool[t];null!==r.allocateQueriesForContext(e)&&r.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize(yN);t.viewport(0,0,e,r)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}this.initTimestampQuery(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;e0&&!1===this._useMultisampledExtension(o)){const i=s.framebuffers[e.getCacheKey()];let n=t.COLOR_BUFFER_BIT;o.resolveDepthBuffer&&(o.depthBuffer&&(n|=t.DEPTH_BUFFER_BIT),o.stencilBuffer&&o.resolveStencilBuffer&&(n|=t.STENCIL_BUFFER_BIT));const a=s.msaaFrameBuffer,u=s.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,a),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),d)for(let e=0;e{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(pt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):pt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?b.renderInstances(_,x,T):b.render(_,x)};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()}));t.push(i)}else 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");console.error("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&&console.warn("THREE.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})}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;epN[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=Ef(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;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,0)}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&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const xN="point-list",TN="line-list",_N="line-strip",vN="triangle-list",NN="triangle-strip",SN="never",EN="less",wN="equal",AN="less-equal",RN="greater",CN="not-equal",MN="greater-equal",PN="always",BN="store",LN="load",FN="clear",IN="ccw",DN="none",VN="front",UN="back",ON="uint16",kN="uint32",GN="r8unorm",zN="r8snorm",HN="r8uint",$N="r8sint",WN="r16uint",jN="r16sint",qN="r16float",XN="rg8unorm",KN="rg8snorm",YN="rg8uint",QN="rg8sint",ZN="r32uint",JN="r32sint",eS="r32float",tS="rg16uint",rS="rg16sint",sS="rg16float",iS="rgba8unorm",nS="rgba8unorm-srgb",aS="rgba8snorm",oS="rgba8uint",uS="rgba8sint",lS="bgra8unorm",dS="bgra8unorm-srgb",cS="rgb9e5ufloat",hS="rgb10a2unorm",pS="rgb10a2unorm",gS="rg32uint",mS="rg32sint",fS="rg32float",yS="rgba16uint",bS="rgba16sint",xS="rgba16float",TS="rgba32uint",_S="rgba32sint",vS="rgba32float",NS="depth16unorm",SS="depth24plus",ES="depth24plus-stencil8",wS="depth32float",AS="depth32float-stencil8",RS="bc1-rgba-unorm",CS="bc1-rgba-unorm-srgb",MS="bc2-rgba-unorm",PS="bc2-rgba-unorm-srgb",BS="bc3-rgba-unorm",LS="bc3-rgba-unorm-srgb",FS="bc4-r-unorm",IS="bc4-r-snorm",DS="bc5-rg-unorm",VS="bc5-rg-snorm",US="bc6h-rgb-ufloat",OS="bc6h-rgb-float",kS="bc7-rgba-unorm",GS="bc7-rgba-srgb",zS="etc2-rgb8unorm",HS="etc2-rgb8unorm-srgb",$S="etc2-rgb8a1unorm",WS="etc2-rgb8a1unorm-srgb",jS="etc2-rgba8unorm",qS="etc2-rgba8unorm-srgb",XS="eac-r11unorm",KS="eac-r11snorm",YS="eac-rg11unorm",QS="eac-rg11snorm",ZS="astc-4x4-unorm",JS="astc-4x4-unorm-srgb",eE="astc-5x4-unorm",tE="astc-5x4-unorm-srgb",rE="astc-5x5-unorm",sE="astc-5x5-unorm-srgb",iE="astc-6x5-unorm",nE="astc-6x5-unorm-srgb",aE="astc-6x6-unorm",oE="astc-6x6-unorm-srgb",uE="astc-8x5-unorm",lE="astc-8x5-unorm-srgb",dE="astc-8x6-unorm",cE="astc-8x6-unorm-srgb",hE="astc-8x8-unorm",pE="astc-8x8-unorm-srgb",gE="astc-10x5-unorm",mE="astc-10x5-unorm-srgb",fE="astc-10x6-unorm",yE="astc-10x6-unorm-srgb",bE="astc-10x8-unorm",xE="astc-10x8-unorm-srgb",TE="astc-10x10-unorm",_E="astc-10x10-unorm-srgb",vE="astc-12x10-unorm",NE="astc-12x10-unorm-srgb",SE="astc-12x12-unorm",EE="astc-12x12-unorm-srgb",wE="clamp-to-edge",AE="repeat",RE="mirror-repeat",CE="linear",ME="nearest",PE="zero",BE="one",LE="src",FE="one-minus-src",IE="src-alpha",DE="one-minus-src-alpha",VE="dst",UE="one-minus-dst",OE="dst-alpha",kE="one-minus-dst-alpha",GE="src-alpha-saturated",zE="constant",HE="one-minus-constant",$E="add",WE="subtract",jE="reverse-subtract",qE="min",XE="max",KE=0,YE=15,QE="keep",ZE="zero",JE="replace",ew="invert",tw="increment-clamp",rw="decrement-clamp",sw="increment-wrap",iw="decrement-wrap",nw="storage",aw="read-only-storage",ow="write-only",uw="read-only",lw="read-write",dw="non-filtering",cw="comparison",hw="float",pw="unfilterable-float",gw="depth",mw="sint",fw="uint",yw="2d",bw="3d",xw="2d",Tw="2d-array",_w="cube",vw="3d",Nw="all",Sw="vertex",Ew="instance",ww={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class Aw extends Cv{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class Rw extends Aw{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){this.texture=this.textureNode.value}}class Cw extends Mv{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let Mw=0;class Pw extends Cw{constructor(e,t){super("StorageBuffer_"+Mw++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Os.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class Bw extends Zm{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:CE}),this.flipYSampler=e.createSampler({minFilter:ME}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:NN,stripIndexFormat:kN},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:NN,stripIndexFormat:kN},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.getTransferPipeline(s),o=this.getFlipYPipeline(s),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:xw,baseArrayLayer:r}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:xw,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,r)=>{const s=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:r,loadOp:FN,storeOp:BN,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(a,l,d),h(o,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,r=0){const s=this.get(e);void 0===s.useCount&&(s.useCount=0,s.layers=[]);const i=s.layers[r]||this._mipmapCreateBundles(e,t,r),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,i),this.device.queue.submit([n.finish()]),0!==s.useCount&&(s.layers[r]=i),s.useCount++}_mipmapCreateBundles(e,t,r){const s=this.getTransferPipeline(t.format),i=s.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:xw,baseArrayLayer:r});const a=[];for(let o=1;o1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,Uw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,Ow={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 kw extends j_{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(Vw);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=Uw.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 Gw extends W_{parseFunction(e){return new kw(e)}}const zw="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},Hw={[Os.READ_ONLY]:"read",[Os.WRITE_ONLY]:"write",[Os.READ_WRITE]:"read_write"},$w={[Nr]:"repeat",[vr]:"clamp",[_r]:"mirror"},Ww={vertex:zw?zw.VERTEX:1,fragment:zw?zw.FRAGMENT:2,compute:zw?zw.COMPUTE:4},jw={instance:!0,swizzleAssign:!1,storageBuffer:!0},qw={"^^":"tsl_xor"},Xw={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"},Kw={},Yw={tsl_xor:new Sb("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Sb("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Sb("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Sb("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Sb("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Sb("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Sb("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Sb("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 Sb("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 Sb("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Sb("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 Sb("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Sb("\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")},Qw={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"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(Yw.pow_float=new Sb("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),Yw.pow_vec2=new Sb("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[Yw.pow_float]),Yw.pow_vec3=new Sb("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[Yw.pow_float]),Yw.pow_vec4=new Sb("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[Yw.pow_float]),Qw.pow_float="tsl_pow_float",Qw.pow_vec2="tsl_pow_vec2",Qw.pow_vec3="tsl_pow_vec3",Qw.pow_vec4="tsl_pow_vec4");let Zw="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(Zw+="diagnostic( off, derivative_uniformity );\n");class Jw extends M_{constructor(e,t){super(e,t,new Gw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==b}_generateTextureSample(e,t,r,s,i=this.shaderStage){return"fragment"===i?s?`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this._generateTextureSampleLevel(e,t,r,"0",s)}_generateVideoSample(e,t,r=this.shaderStage){if("fragment"===r)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${r} shader.`)}_generateTextureSampleLevel(e,t,r,s,i){return!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,s):this.generateTextureLod(e,t,r,i,s)}generateWrapFunction(e){const t=`tsl_coord_${$w[e.wrapS]}S_${$w[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let r=Kw[t];if(void 0===r){const s=[],i=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===Nr?(s.push(Yw.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===vr?(s.push(Yw.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===_r?(s.push(Yw.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",Kw[t]=r=new Sb(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.globalCache);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.isData3DTexture?"vec3":"vec2",n=u||e.isVideoTexture||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Zo(new Iu(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Zo(new Iu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Zo(new Iu("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${r} ), ${this.generateTextureDimension(e,t,s)}, u32( ${s} ) )`}generateTextureLod(e,t,r,s,i="0u"){const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i),o=e.isData3DTexture?"vec3":"vec2",u=`${o}( ${n}( ${r} ) * ${o}( ${a} ) )`;return this.generateTextureLoad(e,t,u,s,i)}generateTextureLoad(e,t,r,s,i="0u"){let n;return!0===e.isVideoTexture?n=`textureLoad( ${t}, ${r} )`:s?n=`textureLoad( ${t}, ${r}, ${s}, u32( ${i} ) )`:(n=`textureLoad( ${t}, ${r}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(n+=".x")),n}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}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===I||!1===this.isSampleCompare(e)&&e.minFilter===v&&e.magFilter===v||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,r,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,"0",i):this._generateTextureSample(e,t,r,s,i),n}generateTextureGrad(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return!0===e.isDepthTexture&&!0===e.isArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,r,s,i,n=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,r,n):this._generateTextureSampleLevel(e,t,r,s,i),a}generateTextureBias(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===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=qw[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Os.READ_ONLY:e.access}getStorageAccess(e,t){return Hw[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||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);if("texture"===t||"storageTexture"===t?s=new Ov(i.name,i.node,o,n):"cubeTexture"===t?s=new kv(i.name,i.node,o,n):"texture3D"===t&&(s=new Gv(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.setVisibility(Ww[r]),!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new Rw(`${i.name}_sampler`,i.node,o);e.setVisibility(Ww[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?Lv:Pw)(e,o);n.setVisibility(Ww[r]),l.push(n),a=n,i.name=s||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let s=e[u];void 0===s&&(s=new Dv(u,o),s.setVisibility(Ww[r]),e[u]=s,l.push(s)),a=this.getNodeUniform(i,t),s.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){let s=`var ${t} : `;return s+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),s}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];for(let i=0;ir.value.itemSize;return s&&!i}getUniforms(e){const t=this.uniforms[e],r=[],s=[],i=[],n={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let s;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture)s="texture_cube";else if(!0===t.isDepthTexture)s=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)s="texture_2d_array";else if(!0===t.isVideoTexture)s="texture_external";else if(!0===t.isData3DTexture)s="texture_3d";else if(!0===i.node.isStorageTextureNode){s=`texture_storage_2d<${Dw(t)}, ${this.getStorageAccess(i.node,e)}>`}else{s=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${s};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,r=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===i.type?", "+n:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${u}> ${i.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${o} >`;s.push(this._getWGSLStructBinding(i.name,e,u,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in n){const t=n[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=r.join("\n");return a+=s.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${u}\n`),s+=`${i.code}\n\t`,e===n&&"compute"!==t)if(s+="// result\n\n\t","vertex"===t)s+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)r.returnType=a.getNodeType(this),r.structs+="var output : "+r.returnType+";",s+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar output : OutputStruct;",s+=`output.color = ${i.result};\n\n\treturn output;`}}r.flow=s}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getType(e){return Xw[e]||e}isAvailable(e){let t=jw[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),jw[e]=t),t}_getWGSLMethod(e){return void 0!==Yw[e]&&this._include(e),Qw[e]}_include(e){const t=Yw[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${Zw}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class eA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=ES:e.depth&&(t=SS),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.samples}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}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?xN:e.isLineSegments||e.isMesh&&!0===t.wireframe?TN:e.isLine?_N:e.isMesh?vN:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ce)return lS;if(e===ce)return xS;throw new Error("Unsupported outputType")}}const tA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),rA=new Map([[ze,["float16"]]]),sA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class iA{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;e1&&(s.multisampled=!0,r.texture.isDepthTexture||(s.sampleType=pw)),r.texture.isDepthTexture)t.compatibilityMode&&null===r.texture.compareFunction?s.sampleType=pw:s.sampleType=gw;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const e=r.texture.type;e===_?s.sampleType=mw:e===T?s.sampleType=fw:e===I&&(this.backend.hasFeature("float32-filterable")?s.sampleType=hw:s.sampleType=pw)}r.isSampledCubeTexture?s.viewDimension=_w:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?s.viewDimension=Tw:r.isSampledTexture3D&&(s.viewDimension=vw),e.texture=s}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);s.push(e)}return r.createBindGroupLayout({entries:s})}createBindings(e,t,r,s=0){const{backend:i,bindGroupLayoutCache:n}=this,a=i.get(e);let o,u=n.get(e.bindingsReference);void 0===u&&(u=this.createBindingsLayout(e),n.set(e.bindingsReference,u)),r>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[r]===s&&(o=a.groups[r])),void 0===o&&(o=this.createBindGroup(e,u),r>0&&(a.groups[r]=o,a.versions[r]=s)),a.group=o,a.layout=u}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer;r.queue.writeBuffer(i,0,s,0)}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],n=r.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:s});r.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);if(void 0===e.buffer){const r=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=s.createBuffer({label:"bindingBuffer_"+t.name,size:r,usage:i});e.buffer=n}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t);if(void 0===e.buffer){const s=t.attribute;e.buffer=r.get(s).buffer}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}else if(t.isSampledTexture){const e=r.get(t.texture);let a;if(void 0!==e.externalTexture)a=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount,s=`view-${e.texture.width}-${e.texture.height}-${r}`;if(a=e[s],void 0===a){const i=Nw;let n;n=t.isSampledCubeTexture?_w:t.isSampledTexture3D?vw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Tw:xw,a=e[s]=e.texture.createView({aspect:i,dimension:n,mipLevelCount:r})}}n.push({binding:i,resource:a})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class aA{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:o}=n,u=this.backend,l=u.device,d=u.utils,c=u.get(n),h=[];for(const t of e.getBindings()){const e=u.get(t);h.push(e.layout)}const p=u.attributeUtils.createShaderVertexBuffers(e);let g;s.blending===H||s.blending===k&&!1===s.transparent||(g=this._getBlending(s));let m={};!0===s.stencilWrite&&(m={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const f=this._getColorWriteMask(s),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:l.createPipelineLayout({bindGroupLayouts:h})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=v,E.depthWriteEnabled=s.depthWrite,E.depthCompare=_),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),S.depthStencil=E),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[s.getCurrentColorFormat(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);a.push(t.layout)}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===qe){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:$E},r={srcFactor:i,dstFactor:n,operation:$E}};if(e.premultipliedAlpha)switch(s){case k:i(BE,DE,BE,DE);break;case Bt:i(BE,BE,BE,BE);break;case Pt:i(PE,FE,PE,BE);break;case Mt:i(VE,DE,PE,BE)}else switch(s){case k:i(IE,DE,BE,DE);break;case Bt:i(IE,BE,BE,BE);break;case Pt:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mt:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};console.error("THREE.WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Ke:t=PE;break;case wt:t=BE;break;case Et:t=LE;break;case Tt:t=FE;break;case St:t=IE;break;case xt:t=DE;break;case vt:t=VE;break;case bt:t=UE;break;case _t:t=OE;break;case yt:t=kE;break;case Nt:t=GE;break;case 211:t=zE;break;case 212:t=HE;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case kr:t=SN;break;case Or:t=PN;break;case Ur:t=EN;break;case Vr:t=AN;break;case Dr:t=wN;break;case Ir:t=MN;break;case Fr:t=RN;break;case Lr:t=CN;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case Xr:t=QE;break;case qr:t=ZE;break;case jr:t=JE;break;case Wr:t=ew;break;case $r:t=tw;break;case Hr:t=rw;break;case zr:t=sw;break;case Gr:t=iw;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Xe:t=$E;break;case ft:t=WE;break;case mt:t=jE;break;case Yr:t=qE;break;case Kr:t=XE;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;switch(s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?ON:kN),r.side){case je:s.frontFace=IN,s.cullMode=UN;break;case S:s.frontFace=IN,s.cullMode=VN;break;case E:s.frontFace=IN,s.cullMode=DN;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",r.side)}return s}_getColorWriteMask(e){return!0===e.colorWrite?YE:KE}_getDepthCompare(e){let t;if(!1===e.depthTest)t=PN;else{const r=e.depthFunc;switch(r){case kt:t=SN;break;case Ot:t=PN;break;case Ut:t=EN;break;case Vt:t=AN;break;case Dt:t=wN;break;case It:t=MN;break;case Ft:t=RN;break;case Lt:t=CN;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class oA extends mN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,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));let a=0;for(const[,t]of e){const e=n[t],r=n[t+1];a+=Number(r-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class uA extends Qv{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new eA(this),this.attributeUtils=new iA(this),this.bindingUtils=new nA(this),this.pipelineUtils=new aA(this),this.textureUtils=new Iw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},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(ww),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;r.lost.then((t=>{const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}));const s=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=r,this.context=s;const i=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(ww.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i}),this.updateSize()}get coordinateSystem(){return d}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const r=e.colorAttachments[0];this.renderer.samples>0?r.view=this.colorBuffer.createView():r.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;if(void 0===i||s.width!==r.width||s.height!==r.height||s.dimensions!==r.dimensions||s.activeMipmapLevel!==e.activeMipmapLevel||s.activeCubeFace!==e.activeCubeFace||s.samples!==r.samples){i={},s.descriptors=i;const e=()=>{r.removeEventListener("dispose",e),this.delete(r)};!1===r.hasEventListener("dispose",e)&&r.addEventListener("dispose",e)}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:LN}),this.initTimestampQuery(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;ea?(u.x=Math.min(t.dispatchCount,a),u.y=Math.ceil(t.dispatchCount/a)):u.x=t.dispatchCount,i.dispatchWorkgroups(u.x,u.y,u.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:r,material:s,context:i,pipeline:n}=e,a=e.getBindings(),o=this.get(i),u=this.get(n).pipeline,l=e.getIndex(),d=null!==l,c=e.getDrawParameters();if(null===c)return;const h=(t,r)=>{this.pipelineUtils.setPipeline(t,u),r.pipeline=u;const n=r.bindingGroups;for(let e=0,r=a.length;e{if(h(s,i),!0===r.isBatchedMesh){const e=r._multiDrawStarts,i=r._multiDrawCounts,n=r._multiDrawCount,a=r._multiDrawInstances;null!==a&&pt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o1?0:o;!0===d?s.drawIndexed(i[o],n,e[o]/l.array.BYTES_PER_ELEMENT,0,u):s.draw(i[o],n,e[o],u),t.update(r,i[o],n)}}else if(!0===d){const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndexedIndirect(e,0)}else s.drawIndexed(i,n,a,0,0);t.update(r,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndirect(e,0)}else s.draw(i,n,a,0);t.update(r,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),s=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==s.length){const e=this.get(n),r=[],i=new Uint32Array([0,0,0,0]);for(let t=0,n=s.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new bN(e)));super(new t(e),e),this.library=new cA,this.isWebGPURenderer=!0}}class pA extends ds{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class gA{constructor(e,t=nn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new Yh;r.name="PostProcessing",this._quadMesh=new Ay(r)}render(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}dispose(){this._quadMesh.material.dispose()}_update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;this._quadMesh.material.fragmentNode=!0===this.outputColorTransform?Ou(this.outputNode,t,r):this.outputNode.context({toneMapping:t,outputColorSpace:r}),this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,await this._quadMesh.renderAsync(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}}class mA extends x{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Y,this.minFilter=Y,this.isStorageTexture=!0}}class fA extends Iy{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class yA extends cs{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new hs(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):console.error(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]?(console.error("THREE.NodeLoader: Node type not found:",e),ji()):Fi(new this.nodes[e])}}class bA extends ps{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 xA extends gs{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 yA;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 bA;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}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={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 null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};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)}return t}equals(e){const{object:t,material:r,geometry:s}=e,i=this.getRenderObjectData(e);if(!0!==i.worldMatrix.equals(t.matrixWorld))return i.worldMatrix.copy(t.matrixWorld),!1;const n=i.material;for(const e in n){const t=n[e],s=r[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return n[e]=s,!1}if(n.transmission>0){const{width:t,height:r}=e.context;if(i.bufferWidth!==t||i.bufferHeight!==r)return i.bufferWidth=t,i.bufferHeight=r,!1}const a=i.geometry,o=s.attributes,u=a.attributes,l=Object.keys(u),d=Object.keys(o);if(a.id!==s.id)return a.id=s.id,!1;if(l.length!==d.length)return i.geometry.attributes=this.getAttributesData(o),!1;for(const e of l){const t=u[e],r=o[e];if(void 0===r)return delete u[e],!1;if(t.version!==r.version)return t.version=r.version,!1}const c=s.index,h=a.indexVersion,p=c?c.version:null;if(h!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==s.drawRange.start||a.drawRange.count!==s.drawRange.count)return a.drawRange.start=s.drawRange.start,a.drawRange.count=s.drawRange.count,!1;if(i.morphTargetInfluences){let e=!1;for(let r=0;r>>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 bs=e=>ys(e),xs=e=>ys(e),Ts=(...e)=>ys(e);function _s(e,t=!1){const r=[];!0===e.isNode&&(r.push(e.id),e=e.getSelf());for(const{property:s,childNode:i}of vs(e))r.push(ys(s.slice(0,-4)),i.getCacheKey(t));return ys(r)}function*vs(e,t=!1){for(const r in e){if(!0===r.startsWith("_"))continue;const s=e[r];if(!0===Array.isArray(s))for(let e=0;ee.charCodeAt(0))).buffer}var Is=Object.freeze({__proto__:null,arrayBufferToBase64:Ls,base64ToArrayBuffer:Fs,getByteBoundaryFromType:Cs,getCacheKey:_s,getDataFromObject:Bs,getLengthFromType:As,getMemoryLengthFromType:Rs,getNodeChildren:vs,getTypeFromLength:Es,getTypedArrayFromType:ws,getValueFromType:Ps,getValueType:Ms,hash:Ts,hashArray:xs,hashString:bs});const Ds={VERTEX:"vertex",FRAGMENT:"fragment"},Vs={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Us={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Os={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},ks=["fragment","vertex"],Gs=["setup","analyze","generate"],zs=[...ks,"compute"],Hs=["x","y","z","w"],$s={analyze:"setup",generate:"analyze"};let Ws=0;class js extends o{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Vs.NONE,this.updateBeforeType=Vs.NONE,this.updateAfterType=Vs.NONE,this.uuid=u.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ws++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Vs.FRAME)}onRenderUpdate(e){return this.onUpdate(e,Vs.RENDER)}onObjectUpdate(e){return this.onUpdate(e,Vs.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of vs(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Ts(_s(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const r=this.getShared(e);if(this!==r)return r.build(e,t);const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const i=$s[e.buildStage];if(i&&!0!==s.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const r of Object.values(t))if(r&&!0===r.isNode){if(!0===r.parents){const t=e.getNodeProperties(r);t.parents=t.parents||[],t.parents.push(this)}r.build(e)}}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const r=this.getNodeType(e),s=e.getDataFromNode(this);n=s.snippet,void 0===n?void 0===s.generated?(s.generated=!0,n=this.generate(e)||"",s.snippet=n):(console.warn("THREE.Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,r,t)}else n=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return vs(this)}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(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}}class qs extends js{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Xs extends js{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(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 Ks extends js{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 Ys extends Ks{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,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 o=0;for(const t of i){if(o>=s){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${r}()' type.`);break}let i,u=t.getNodeType(e),l=e.getTypeLength(u);o+l>s&&(console.error(`THREE.TSL: Length of '${r}()' data exceeds maximum length of output type.`),l=s-o,u=e.getTypeFromLength(l)),o+=l,i=t.build(e,u);const d=e.getComponentType(u);d!==n&&(i=e.format(i,d,n)),a.push(i)}const u=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(u,r,t)}}const Qs=Hs.join("");class Zs extends js{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(Hs.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const 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===Qs.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 Js extends Ks{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}getNodeType(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;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),li=e=>ui(e).split("").sort().join(""),di={setup(e,t){const r=t.shift();return e(Ii(r),...t)},get(e,t,r){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(ni.assign(r,...e),r);if(ai.has(t)){const s=ai.get(t);return e.isStackNode?(...e)=>r.add(s(...e)):(...e)=>s(r,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&ai.has(t.slice(0,t.length-6))){const s=ai.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>r.assign(e[0],s(...e)):(...e)=>r.assign(s(r,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=ui(t),Fi(new Zs(r,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(3).toLowerCase()),r=>Fi(new Js(e,t,Fi(r)));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=li(t.slice(4).toLowerCase()),()=>Fi(new ei(Fi(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Fi(new Zs(e,t));if(!0===/^\d+$/.test(t))return Fi(new qs(r,new si(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Fi(new ii(r,e))}return Reflect.get(e,t,r)},set:(e,t,r,s)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,r,s):(s[t].assign(r),!0)},ci=new WeakMap,hi=new WeakMap,pi=function(e,t=null){for(const r in e)e[r]=Fi(e[r],t);return e},gi=function(e,t=null){const r=e.length;for(let s=0;sFi(null!==s?Object.assign(e,s):e);let n,a,o,u=t;function l(t){let r;return r=u?/[a-z]/i.test(u)?u+"()":u:e.type,void 0!==a&&t.lengtho?(console.error(`THREE.TSL: "${r}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?n=(...t)=>i(new e(...Di(l(t)))):null!==r?(r=Fi(r),n=(...s)=>i(new e(t,...Di(l(s)),r))):n=(...r)=>i(new e(t,...Di(l(r)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(u=e,n),n},fi=function(e,...t){return Fi(new e(...Di(t)))};class yi extends js{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let s=hi.get(e.constructor);void 0===s&&(s=new WeakMap,hi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=Fi(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i),o=Fi(i.call(r))}else{const s=t.jsFunc,i=null!==r||s.length>1?s(r||[],e):s(e);o=Fi(i)}return e.subBuildFn=a,t.once&&(s[n]=o),o}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);if("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 r}}class bi extends js{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Ii(e),Fi(new yi(this,e))}setup(){return this.call()}}const xi=[!1,!0],Ti=[0,1,2,3],_i=[-1,-2],vi=[.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],Ni=new Map;for(const e of xi)Ni.set(e,new si(e));const Si=new Map;for(const e of Ti)Si.set(e,new si(e,"uint"));const Ei=new Map([...Si].map((e=>new si(e.value,"int"))));for(const e of _i)Ei.set(e,new si(e,"int"));const wi=new Map([...Ei].map((e=>new si(e.value))));for(const e of vi)wi.set(e,new si(e));for(const e of vi)wi.set(-e,new si(-e));const Ai={bool:Ni,uint:Si,ints:Ei,float:wi},Ri=new Map([...Ni,...wi]),Ci=(e,t)=>Ri.has(e)?Ri.get(e):!0===e.isNode?e:new si(e,t),Mi=function(e,t=null){return(...r)=>{if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every((e=>"object"!=typeof e)))&&(r=[Ps(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return Fi(t.get(r[0]));if(1===r.length){const t=Ci(r[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Fi(t):Fi(new Xs(t,e))}const s=r.map((e=>Ci(e)));return Fi(new Ys(s,e))}},Pi=e=>"object"==typeof e&&null!==e?e.value:e,Bi=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Li(e,t){return new Proxy(new bi(e,t),di)}const Fi=(e,t=null)=>function(e,t=null){const r=Ms(e);if("node"===r){let t=ci.get(e);return void 0===t&&(t=new Proxy(e,di),ci.set(e,t),ci.set(t,t)),t}return null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?Fi(Ci(e,t)):"shader"===r?e.isFn?e:ki(e):e}(e,t),Ii=(e,t=null)=>new pi(e,t),Di=(e,t=null)=>new gi(e,t),Vi=(...e)=>new mi(...e),Ui=(...e)=>new fi(...e);let Oi=0;const ki=(e,t=null)=>{let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:console.error("THREE.TSL: Invalid layout type."),t=null));const s=new Li(e,r),i=(...e)=>{let t;Ii(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];const i=s.call(t);return"void"===r&&i.toStack(),i};if(i.shaderNode=s,i.id=s.id,i.isFn=!0,i.getNodeType=(...e)=>s.getNodeType(...e),i.getCacheKey=(...e)=>s.getCacheKey(...e),i.setLayout=e=>(s.setLayout(e),i),i.once=(e=null)=>(s.once=!0,s.subBuilds=e,i),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+Oi++,type:r,inputs:[]};for(const r in t)"return"!==r&&e.inputs.push({name:r,type:t[r]});t=e}i.setLayout(t)}return i},Gi=e=>{ni=e},zi=()=>ni,Hi=(...e)=>ni.If(...e);function $i(e){return ni&&ni.add(e),e}oi("toStack",$i);const Wi=new Mi("color"),ji=new Mi("float",Ai.float),qi=new Mi("int",Ai.ints),Xi=new Mi("uint",Ai.uint),Ki=new Mi("bool",Ai.bool),Yi=new Mi("vec2"),Qi=new Mi("ivec2"),Zi=new Mi("uvec2"),Ji=new Mi("bvec2"),en=new Mi("vec3"),tn=new Mi("ivec3"),rn=new Mi("uvec3"),sn=new Mi("bvec3"),nn=new Mi("vec4"),an=new Mi("ivec4"),on=new Mi("uvec4"),un=new Mi("bvec4"),ln=new Mi("mat2"),dn=new Mi("mat3"),cn=new Mi("mat4");oi("toColor",Wi),oi("toFloat",ji),oi("toInt",qi),oi("toUint",Xi),oi("toBool",Ki),oi("toVec2",Yi),oi("toIVec2",Qi),oi("toUVec2",Zi),oi("toBVec2",Ji),oi("toVec3",en),oi("toIVec3",tn),oi("toUVec3",rn),oi("toBVec3",sn),oi("toVec4",nn),oi("toIVec4",an),oi("toUVec4",on),oi("toBVec4",un),oi("toMat2",ln),oi("toMat3",dn),oi("toMat4",cn);const hn=Vi(qs).setParameterLength(2),pn=(e,t)=>Fi(new Xs(Fi(e),t));oi("element",hn),oi("convert",pn);oi("append",(e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),$i(e))));class gn extends js{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}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 mn=(e,t)=>Fi(new gn(e,t)),fn=(e,t)=>Fi(new gn(e,t,!0)),yn=Ui(gn,"vec4","DiffuseColor"),bn=Ui(gn,"vec3","EmissiveColor"),xn=Ui(gn,"float","Roughness"),Tn=Ui(gn,"float","Metalness"),_n=Ui(gn,"float","Clearcoat"),vn=Ui(gn,"float","ClearcoatRoughness"),Nn=Ui(gn,"vec3","Sheen"),Sn=Ui(gn,"float","SheenRoughness"),En=Ui(gn,"float","Iridescence"),wn=Ui(gn,"float","IridescenceIOR"),An=Ui(gn,"float","IridescenceThickness"),Rn=Ui(gn,"float","AlphaT"),Cn=Ui(gn,"float","Anisotropy"),Mn=Ui(gn,"vec3","AnisotropyT"),Pn=Ui(gn,"vec3","AnisotropyB"),Bn=Ui(gn,"color","SpecularColor"),Ln=Ui(gn,"float","SpecularF90"),Fn=Ui(gn,"float","Shininess"),In=Ui(gn,"vec4","Output"),Dn=Ui(gn,"float","dashSize"),Vn=Ui(gn,"float","gapSize"),Un=Ui(gn,"float","pointWidth"),On=Ui(gn,"float","IOR"),kn=Ui(gn,"float","Transmission"),Gn=Ui(gn,"float","Thickness"),zn=Ui(gn,"float","AttenuationDistance"),Hn=Ui(gn,"color","AttenuationColor"),$n=Ui(gn,"float","Dispersion");class Wn extends js{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1){super("string"),this.name=e,this.shared=t,this.order=r,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const jn=e=>new Wn(e),qn=(e,t=0)=>new Wn(e,!0,t),Xn=qn("frame"),Kn=qn("render"),Yn=jn("object");class Qn extends ti{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Yn}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const r=this.getSelf();return e=e.bind(r),super.onUpdate((t=>{const s=e(t,r);void 0!==s&&(this.value=s)}),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.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,r,t)}}const Zn=(e,t)=>{const r=Bi(t||e),s=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Fi(new Qn(s,r))};class Jn extends Ks{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const ea=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Jn(null,r.length,r)}else{const r=e[0],s=e[1];t=new Jn(r,s)}return Fi(t)};oi("toArray",((e,t)=>ea(Array(t).fill(e))));class ta extends Ks{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return Hs.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=e.getNodeProperties(this);s.sourceNode=r,s.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.getNodeType(e),a=r.build(e),o=s.build(e,n),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=a);else if(i){const s=e.getVarFromNode(this,null,n),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)console.error("THREE.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?Di(t):Ii(t[0]),Fi(new sa(Fi(e),t)));oi("call",ia);const na={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class aa extends Ks{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new aa(e,t,r);for(let t=0;t>"===t||"<<"===t)return e.getIntegerType(i);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(i),e.getTypeLength(n));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(i)){if("float"===n)return i;if(e.isVector(n))return e.getVectorFromMatrix(i);if(e.isMatrix(n))return i}else if(e.isMatrix(n)){if("float"===i)return n;if(e.isVector(i))return e.getVectorFromMatrix(n)}return e.getTypeLength(n)>e.getTypeLength(i)?n:i}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e);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),d=i?i.build(e,o):null,c=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===l;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${d} )`,n,t):e.format(`( ${u} ${r} ${d} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${d} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${d} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(c)return e.format(`${c}( ${u}, ${d} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${d} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${d}`,n,t);{let i=`( ${u} ${r} ${d} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return c?e.format(`${c}( ${u}, ${d} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${d} ${r} ${u}`,n,t):e.format(`${u} ${r} ${d}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const oa=Vi(aa,"+").setParameterLength(2,1/0).setName("add"),ua=Vi(aa,"-").setParameterLength(2,1/0).setName("sub"),la=Vi(aa,"*").setParameterLength(2,1/0).setName("mul"),da=Vi(aa,"/").setParameterLength(2,1/0).setName("div"),ca=Vi(aa,"%").setParameterLength(2).setName("mod"),ha=Vi(aa,"==").setParameterLength(2).setName("equal"),pa=Vi(aa,"!=").setParameterLength(2).setName("notEqual"),ga=Vi(aa,"<").setParameterLength(2).setName("lessThan"),ma=Vi(aa,">").setParameterLength(2).setName("greaterThan"),fa=Vi(aa,"<=").setParameterLength(2).setName("lessThanEqual"),ya=Vi(aa,">=").setParameterLength(2).setName("greaterThanEqual"),ba=Vi(aa,"&&").setParameterLength(2,1/0).setName("and"),xa=Vi(aa,"||").setParameterLength(2,1/0).setName("or"),Ta=Vi(aa,"!").setParameterLength(1).setName("not"),_a=Vi(aa,"^^").setParameterLength(2).setName("xor"),va=Vi(aa,"&").setParameterLength(2).setName("bitAnd"),Na=Vi(aa,"~").setParameterLength(2).setName("bitNot"),Sa=Vi(aa,"|").setParameterLength(2).setName("bitOr"),Ea=Vi(aa,"^").setParameterLength(2).setName("bitXor"),wa=Vi(aa,"<<").setParameterLength(2).setName("shiftLeft"),Aa=Vi(aa,">>").setParameterLength(2).setName("shiftRight"),Ra=ki((([e])=>(e.addAssign(1),e))),Ca=ki((([e])=>(e.subAssign(1),e))),Ma=ki((([e])=>{const t=qi(e).toConst();return e.addAssign(1),t})),Pa=ki((([e])=>{const t=qi(e).toConst();return e.subAssign(1),t}));oi("add",oa),oi("sub",ua),oi("mul",la),oi("div",da),oi("mod",ca),oi("equal",ha),oi("notEqual",pa),oi("lessThan",ga),oi("greaterThan",ma),oi("lessThanEqual",fa),oi("greaterThanEqual",ya),oi("and",ba),oi("or",xa),oi("not",Ta),oi("xor",_a),oi("bitAnd",va),oi("bitNot",Na),oi("bitOr",Sa),oi("bitXor",Ea),oi("shiftLeft",wa),oi("shiftRight",Aa),oi("incrementBefore",Ra),oi("decrementBefore",Ca),oi("increment",Ma),oi("decrement",Pa);const Ba=(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),ca(qi(e),qi(t)));oi("modInt",Ba);class La extends Ks{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===La.MAX||e===La.MIN)&&arguments.length>3){let i=new La(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}getNodeType(e){const t=this.method;return t===La.LENGTH||t===La.DISTANCE||t===La.DOT?"float":t===La.CROSS?"vec3":t===La.ALL||t===La.ANY?"bool":t===La.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===La.ONE_MINUS)i=ua(1,t);else if(s===La.RECIPROCAL)i=da(1,t);else if(s===La.DIFFERENCE)i=io(ua(t,r));else if(s===La.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=nn(en(n),0):s=nn(en(s),0);const a=la(s,n).xyz;i=Ya(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===La.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const c=[];return r===La.CROSS?c.push(n.build(e,s),a.build(e,s)):u===l&&r===La.STEP?c.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==l||r!==La.MIN&&r!==La.MAX?r===La.REFRACT?c.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===La.MIX?c.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===d&&r===La.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==La.DFDX&&r!==La.DFDY||(console.warn(`THREE.TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),c.push(n.build(e,i)),null!==a&&c.push(a.build(e,i)),null!==o&&c.push(o.build(e,i))):c.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${c.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}La.ALL="all",La.ANY="any",La.RADIANS="radians",La.DEGREES="degrees",La.EXP="exp",La.EXP2="exp2",La.LOG="log",La.LOG2="log2",La.SQRT="sqrt",La.INVERSE_SQRT="inversesqrt",La.FLOOR="floor",La.CEIL="ceil",La.NORMALIZE="normalize",La.FRACT="fract",La.SIN="sin",La.COS="cos",La.TAN="tan",La.ASIN="asin",La.ACOS="acos",La.ATAN="atan",La.ABS="abs",La.SIGN="sign",La.LENGTH="length",La.NEGATE="negate",La.ONE_MINUS="oneMinus",La.DFDX="dFdx",La.DFDY="dFdy",La.ROUND="round",La.RECIPROCAL="reciprocal",La.TRUNC="trunc",La.FWIDTH="fwidth",La.TRANSPOSE="transpose",La.BITCAST="bitcast",La.EQUALS="equals",La.MIN="min",La.MAX="max",La.STEP="step",La.REFLECT="reflect",La.DISTANCE="distance",La.DIFFERENCE="difference",La.DOT="dot",La.CROSS="cross",La.POW="pow",La.TRANSFORM_DIRECTION="transformDirection",La.MIX="mix",La.CLAMP="clamp",La.REFRACT="refract",La.SMOOTHSTEP="smoothstep",La.FACEFORWARD="faceforward";const Fa=ji(1e-6),Ia=ji(1e6),Da=ji(Math.PI),Va=ji(2*Math.PI),Ua=Vi(La,La.ALL).setParameterLength(1),Oa=Vi(La,La.ANY).setParameterLength(1),ka=Vi(La,La.RADIANS).setParameterLength(1),Ga=Vi(La,La.DEGREES).setParameterLength(1),za=Vi(La,La.EXP).setParameterLength(1),Ha=Vi(La,La.EXP2).setParameterLength(1),$a=Vi(La,La.LOG).setParameterLength(1),Wa=Vi(La,La.LOG2).setParameterLength(1),ja=Vi(La,La.SQRT).setParameterLength(1),qa=Vi(La,La.INVERSE_SQRT).setParameterLength(1),Xa=Vi(La,La.FLOOR).setParameterLength(1),Ka=Vi(La,La.CEIL).setParameterLength(1),Ya=Vi(La,La.NORMALIZE).setParameterLength(1),Qa=Vi(La,La.FRACT).setParameterLength(1),Za=Vi(La,La.SIN).setParameterLength(1),Ja=Vi(La,La.COS).setParameterLength(1),eo=Vi(La,La.TAN).setParameterLength(1),to=Vi(La,La.ASIN).setParameterLength(1),ro=Vi(La,La.ACOS).setParameterLength(1),so=Vi(La,La.ATAN).setParameterLength(1,2),io=Vi(La,La.ABS).setParameterLength(1),no=Vi(La,La.SIGN).setParameterLength(1),ao=Vi(La,La.LENGTH).setParameterLength(1),oo=Vi(La,La.NEGATE).setParameterLength(1),uo=Vi(La,La.ONE_MINUS).setParameterLength(1),lo=Vi(La,La.DFDX).setParameterLength(1),co=Vi(La,La.DFDY).setParameterLength(1),ho=Vi(La,La.ROUND).setParameterLength(1),po=Vi(La,La.RECIPROCAL).setParameterLength(1),go=Vi(La,La.TRUNC).setParameterLength(1),mo=Vi(La,La.FWIDTH).setParameterLength(1),fo=Vi(La,La.TRANSPOSE).setParameterLength(1),yo=Vi(La,La.BITCAST).setParameterLength(2),bo=(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),ha(e,t)),xo=Vi(La,La.MIN).setParameterLength(2,1/0),To=Vi(La,La.MAX).setParameterLength(2,1/0),_o=Vi(La,La.STEP).setParameterLength(2),vo=Vi(La,La.REFLECT).setParameterLength(2),No=Vi(La,La.DISTANCE).setParameterLength(2),So=Vi(La,La.DIFFERENCE).setParameterLength(2),Eo=Vi(La,La.DOT).setParameterLength(2),wo=Vi(La,La.CROSS).setParameterLength(2),Ao=Vi(La,La.POW).setParameterLength(2),Ro=Vi(La,La.POW,2).setParameterLength(1),Co=Vi(La,La.POW,3).setParameterLength(1),Mo=Vi(La,La.POW,4).setParameterLength(1),Po=Vi(La,La.TRANSFORM_DIRECTION).setParameterLength(2),Bo=e=>la(no(e),Ao(io(e),1/3)),Lo=e=>Eo(e,e),Fo=Vi(La,La.MIX).setParameterLength(3),Io=(e,t=0,r=1)=>Fi(new La(La.CLAMP,Fi(e),Fi(t),Fi(r))),Do=e=>Io(e),Vo=Vi(La,La.REFRACT).setParameterLength(3),Uo=Vi(La,La.SMOOTHSTEP).setParameterLength(3),Oo=Vi(La,La.FACEFORWARD).setParameterLength(3),ko=ki((([e])=>{const t=Eo(e.xy,Yi(12.9898,78.233)),r=ca(t,Da);return Qa(Za(r).mul(43758.5453))})),Go=(e,t,r)=>Fo(t,r,e),zo=(e,t,r)=>Uo(t,r,e),Ho=(e,t)=>_o(t,e),$o=(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),so(e,t)),Wo=Oo,jo=qa;oi("all",Ua),oi("any",Oa),oi("equals",bo),oi("radians",ka),oi("degrees",Ga),oi("exp",za),oi("exp2",Ha),oi("log",$a),oi("log2",Wa),oi("sqrt",ja),oi("inverseSqrt",qa),oi("floor",Xa),oi("ceil",Ka),oi("normalize",Ya),oi("fract",Qa),oi("sin",Za),oi("cos",Ja),oi("tan",eo),oi("asin",to),oi("acos",ro),oi("atan",so),oi("abs",io),oi("sign",no),oi("length",ao),oi("lengthSq",Lo),oi("negate",oo),oi("oneMinus",uo),oi("dFdx",lo),oi("dFdy",co),oi("round",ho),oi("reciprocal",po),oi("trunc",go),oi("fwidth",mo),oi("atan2",$o),oi("min",xo),oi("max",To),oi("step",Ho),oi("reflect",vo),oi("distance",No),oi("dot",Eo),oi("cross",wo),oi("pow",Ao),oi("pow2",Ro),oi("pow3",Co),oi("pow4",Mo),oi("transformDirection",Po),oi("mix",Go),oi("clamp",Io),oi("refract",Vo),oi("smoothstep",zo),oi("faceForward",Oo),oi("difference",So),oi("saturate",Do),oi("cbrt",Bo),oi("transpose",fo),oi("rand",ko);class qo extends js{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}getNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),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.cache(),r=this.ifNode.cache(),s=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=r.context({nodeBlock:r}),n.elseNode=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?mn(r).build(e):"";s.nodeProperty=l;const d=i.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${d} ) {\n\n`).addFlowTab();let c=n.build(e,r);if(c&&(u?c=l+" = "+c+";":(c="return "+c+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Xo=Vi(qo).setParameterLength(2,3);oi("select",Xo);class Ko extends js{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const r=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e,t);return e.setContext(r),s}}const Yo=Vi(Ko).setParameterLength(1,2),Qo=(e,t)=>Yo(e,{label:t});oi("context",Yo),oi("label",Qo);class Zo extends js{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;s&&(a=e.isDeterministic(t),o=n?s:a);const u=e.getVectorType(this.getNodeType(e)),l=t.build(e,u),d=e.getVarFromNode(this,r,u,void 0,o),c=e.getPropertyName(d);let h=c;if(o)if(n)h=a?`const ${c}`:`let ${c}`;else{const r=e.getArrayCount(t);h=`const ${e.getVar(d.type,c,r)}`}return e.addLineFlowCode(`${h} = ${l}`,this),c}}const Jo=Vi(Zo),eu=(e,t=null)=>Jo(e,t).toStack(),tu=(e,t=null)=>Jo(e,t,!0).toStack();oi("toVar",eu),oi("toConst",tu);const ru=e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Jo(e));oi("temp",ru);class su extends js{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(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 iu=(e,t,r=null)=>Fi(new su(Fi(e),t,r));class nu extends js{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let 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=iu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Ds.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,Ds.VERTEX);e.flowNodeFromShaderStage(Ds.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const au=Vi(nu).setParameterLength(1,2),ou=e=>au(e);oi("toVarying",au),oi("toVertexStage",ou),oi("varying",((...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),au(...e)))),oi("vertexStage",((...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),au(...e))));const uu=ki((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return Fo(t,r,s)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lu=ki((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return Fo(t,r,s)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),du="WorkingColorSpace";class cu extends Ks{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===du?c.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!==c.enabled&&r!==s&&r&&s?(c.getTransfer(r)===h&&(i=nn(uu(i.rgb),i.a)),c.getPrimaries(r)!==c.getPrimaries(s)&&(i=nn(dn(c._getMatrix(new n,r,s)).mul(i.rgb),i.a)),c.getTransfer(s)===h&&(i=nn(lu(i.rgb),i.a)),i):i}}const hu=(e,t)=>Fi(new cu(Fi(e),du,t)),pu=(e,t)=>Fi(new cu(Fi(e),t,du));oi("workingToColorSpace",hu),oi("colorSpaceToWorking",pu);let gu=class extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class mu extends js{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=Vs.OBJECT}setGroup(e){return this.group=e,this}element(e){return Fi(new gu(this,Fi(e)))}setNodeType(e){const t=Zn(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new fu(e,t,r));class bu extends Ks{static get type(){return"ToneMappingNode"}constructor(e,t=Tu,r=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Ts(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,r=this.toneMapping;if(r===p)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=nn(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const xu=(e,t,r)=>Fi(new bu(e,Fi(t),Fi(r))),Tu=yu("toneMappingExposure","float");oi("toneMapping",((e,t,r)=>xu(t,r,e)));class _u 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=g,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=this.value,s=e.getTypeLength(t),i=this.bufferStride||s,n=this.bufferOffset,a=!0===r.isInterleavedBuffer?r:new m(r,i),o=new f(a,s,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=au(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}}const vu=(e,t=null,r=0,s=0)=>Fi(new _u(e,t,r,s)),Nu=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setUsage(y),Su=(e,t=null,r=0,s=0)=>vu(e,t,r,s).setInstanced(!0),Eu=(e,t=null,r=0,s=0)=>Nu(e,t,r,s).setInstanced(!0);oi("toAttribute",(e=>vu(e.value)));class wu extends js{static get type(){return"ComputeNode"}constructor(e,t,r=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=r,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Vs.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let r=t[0];for(let e=1;eFi(new wu(Fi(e),t,r));oi("compute",Au);class Ru extends js{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),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}}const Cu=(e,t)=>Fi(new Ru(Fi(e),t));oi("cache",Cu);class Mu extends js{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Pu=Vi(Mu).setParameterLength(2);oi("bypass",Pu);class Bu extends js{static get type(){return"RemapNode"}constructor(e,t,r,s=ji(0),i=ji(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=r,this.outLowNode=s,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:r,outLowNode:s,outHighNode:i,doClamp:n}=this;let a=e.sub(t).div(r.sub(t));return!0===n&&(a=a.clamp()),a.mul(i.sub(s)).add(s)}}const Lu=Vi(Bu,null,null,{doClamp:!1}).setParameterLength(3,5),Fu=Vi(Bu).setParameterLength(3,5);oi("remap",Lu),oi("remapClamp",Fu);class Iu extends js{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 Du=Vi(Iu).setParameterLength(1,2),Vu=e=>(e?Xo(e,Du("discard")):Du("discard")).toStack();oi("discard",Vu);class Uu extends Ks{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||p,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||b;return r!==p&&(t=t.toneMapping(r)),s!==b&&s!==c.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Ou=(e,t=null,r=null)=>Fi(new Uu(Fi(e),t,r));oi("renderOutput",Ou);class ku extends Ks{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e),s="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(s.length);let n="";return n+="// #"+s+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+r+" /* ... */\n",n+="// #"+i+"#\n",null!==t?t(e,n):console.log(n),r}}const Gu=(e,t=null)=>Fi(new ku(Fi(e),t));oi("debug",Gu);class zu extends js{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const 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 au(this).build(e,r)}return console.warn(`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 Hu=(e,t=null)=>Fi(new zu(e,t)),$u=(e=0)=>Hu("uv"+(e>0?e:""),"vec2");class Wu extends js{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 ju=Vi(Wu).setParameterLength(1,2);class qu extends Qn{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vs.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 Xu=Vi(qu).setParameterLength(1),Ku=new x;class Yu extends Qn{static get type(){return"TextureNode"}constructor(e=Ku,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.sampler=!0,this.updateMatrix=!1,this.updateType=Vs.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===T?"uvec4":this.value.type===_?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return $u(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Zn(this.value.matrix)),this._matrixUniform.mul(en(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Vs.OBJECT:Vs.NONE,this}setupUV(e,t){const r=this.value;return e.isFlipY()&&(r.image instanceof ImageBitmap&&!0===r.flipY||!0===r.isRenderTargetTexture||!0===r.isFramebufferTexture||!0===r.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this,e)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,r,s,i,n,a,o){const u=this.value;let l;return l=s?e.generateTextureLevel(u,t,r,s,n):i?e.generateTextureBias(u,t,r,i,n):o?e.generateTextureGrad(u,t,r,o,n):a?e.generateTextureCompare(u,t,r,a,n):!1===this.sampler?e.generateTextureLoad(u,t,r,n):e.generateTexture(u,t,r,n),l}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);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:r,biasNode:o,compareNode:u,depthNode:l,gradNode:d}=s,c=this.generateUV(e,t),h=r?r.build(e,"float"):null,p=o?o.build(e,"float"):null,g=l?l.build(e,"int"):null,m=u?u.build(e,"float"):null,f=d?[d[0].build(e,"vec2"),d[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);a=e.getPropertyName(y);const b=this.generateSnippet(e,i,c,h,p,g,m,f);e.addLineFlowCode(`${a} = ${b}`,this),n.snippet=b,n.propertyName=a}let o=a;const u=this.getNodeType(e);return e.needsToWorkingColorSpace(r)&&(o=pu(Du(o,u),r.colorSpace).setup(e).build(e,u)),e.format(o,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}blur(e){const t=this.clone();t.biasNode=Fi(e).mul(Xu(t)),t.referenceNode=this.getSelf();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===v||r.magFilter===v)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Fi(t)}level(e){const t=this.clone();return t.levelNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}size(e){return ju(this,e)}bias(e){const t=this.clone();return t.biasNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}compare(e){const t=this.clone();return t.compareNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}grad(e,t){const r=this.clone();return r.gradNode=[Fi(e),Fi(t)],r.referenceNode=this.getSelf(),Fi(r)}depth(e){const t=this.clone();return t.depthNode=Fi(e),t.referenceNode=this.getSelf(),Fi(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}const Qu=Vi(Yu).setParameterLength(1,4).setName("texture"),Zu=(e=Ku,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=Qu(e,t,r,s),i},Ju=(...e)=>Zu(...e).setSampler(!1);class el extends Qn{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const tl=(e,t,r)=>Fi(new el(e,t,r));class rl extends qs{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(),s=this.node.getPaddedType();return e.format(t,s,r)}}class sl extends el{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ms(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Vs.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rFi(new sl(e,t));const nl=Vi(class extends js{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),al=Zn(0,"uint").label("u_cameraIndex").setGroup(qn("cameraIndex")).toVarying("v_cameraIndex"),ol=Zn("float").label("cameraNear").setGroup(Kn).onRenderUpdate((({camera:e})=>e.near)),ul=Zn("float").label("cameraFar").setGroup(Kn).onRenderUpdate((({camera:e})=>e.far)),ll=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);t=il(r).setGroup(Kn).label("cameraProjectionMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrix")}else t=Zn("mat4").label("cameraProjectionMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),dl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);t=il(r).setGroup(Kn).label("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraProjectionMatrixInverse")}else t=Zn("mat4").label("cameraProjectionMatrixInverse").setGroup(Kn).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse));return t})).once()(),cl=ki((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);t=il(r).setGroup(Kn).label("cameraViewMatrices").element(e.isMultiViewCamera?nl("gl_ViewID_OVR"):al).toVar("cameraViewMatrix")}else t=Zn("mat4").label("cameraViewMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),hl=Zn("mat4").label("cameraWorldMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.matrixWorld)),pl=Zn("mat3").label("cameraNormalMatrix").setGroup(Kn).onRenderUpdate((({camera:e})=>e.normalMatrix)),gl=Zn(new r).label("cameraPosition").setGroup(Kn).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),ml=new N;class fl extends js{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Vs.OBJECT,this.uniformNode=new Qn(null)}getNodeType(){const e=this.scope;return e===fl.WORLD_MATRIX?"mat4":e===fl.POSITION||e===fl.VIEW_POSITION||e===fl.DIRECTION||e===fl.SCALE?"vec3":e===fl.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===fl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===fl.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===fl.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===fl.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===fl.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===fl.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),ml.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=ml.radius}}generate(e){const t=this.scope;return t===fl.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===fl.POSITION||t===fl.VIEW_POSITION||t===fl.DIRECTION||t===fl.SCALE?this.uniformNode.nodeType="vec3":t===fl.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}}fl.WORLD_MATRIX="worldMatrix",fl.POSITION="position",fl.SCALE="scale",fl.VIEW_POSITION="viewPosition",fl.DIRECTION="direction",fl.RADIUS="radius";const yl=Vi(fl,fl.DIRECTION).setParameterLength(1),bl=Vi(fl,fl.WORLD_MATRIX).setParameterLength(1),xl=Vi(fl,fl.POSITION).setParameterLength(1),Tl=Vi(fl,fl.SCALE).setParameterLength(1),_l=Vi(fl,fl.VIEW_POSITION).setParameterLength(1),vl=Vi(fl,fl.RADIUS).setParameterLength(1);class Nl extends fl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Sl=Ui(Nl,Nl.DIRECTION),El=Ui(Nl,Nl.WORLD_MATRIX),wl=Ui(Nl,Nl.POSITION),Al=Ui(Nl,Nl.SCALE),Rl=Ui(Nl,Nl.VIEW_POSITION),Cl=Ui(Nl,Nl.RADIUS),Ml=Zn(new n).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),Pl=Zn(new a).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),Bl=ki((e=>e.renderer.overrideNodes.modelViewMatrix||Ll)).once()().toVar("modelViewMatrix"),Ll=cl.mul(El),Fl=ki((e=>(e.context.isHighPrecisionModelViewMatrix=!0,Zn("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highpModelViewMatrix"),Il=ki((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Zn("mat3").onObjectUpdate((({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highpModelNormalViewMatrix"),Dl=Hu("position","vec3"),Vl=Dl.toVarying("positionLocal"),Ul=Dl.toVarying("positionPrevious"),Ol=ki((e=>El.mul(Vl).xyz.toVarying(e.getSubBuildProperty("v_positionWorld"))),"vec3").once(["POSITION"])(),kl=ki((()=>Vl.transformDirection(El).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection")),"vec3").once(["POSITION"])(),Gl=ki((e=>e.context.setupPositionView().toVarying("v_positionView")),"vec3").once(["POSITION"])(),zl=Gl.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Hl extends js{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{renderer:t,material:r}=e;return t.coordinateSystem===l&&r.side===S?"false":e.getFrontFacing()}}const $l=Ui(Hl),Wl=ji($l).mul(2).sub(1),jl=ki((([e],{material:t})=>{const r=t.side;return r===S?e=e.mul(-1):r===E&&(e=e.mul(Wl)),e})),ql=Hu("normal","vec3"),Xl=ki((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),en(0,1,0)):ql),"vec3").once()().toVar("normalLocal"),Kl=Gl.dFdx().cross(Gl.dFdy()).normalize().toVar("normalFlat"),Yl=ki((e=>{let t;return t=!0===e.material.flatShading?Kl:rd(Xl).toVarying("v_normalViewGeometry").normalize(),t}),"vec3").once()().toVar("normalViewGeometry"),Ql=ki((e=>{let t=Yl.transformDirection(cl);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")}),"vec3").once()(),Zl=ki((({subBuildFn:e,material:t,context:r})=>{let s;return"NORMAL"===e||"VERTEX"===e?(s=Yl,!0!==t.flatShading&&(s=jl(s))):s=r.setupNormal().context({getUV:null}),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Jl=Zl.transformDirection(cl).toVar("normalWorld"),ed=ki((({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Zl:t.setupClearcoatNormal().context({getUV:null}),r}),"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),td=ki((([e,t=El])=>{const r=dn(t),s=e.div(en(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz})),rd=ki((([e],t)=>{const r=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==r)return r.transformDirection(e);const s=Ml.mul(e);return cl.transformDirection(s)})),sd=ki((()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Zl))).once(["NORMAL","VERTEX"])(),id=ki((()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Jl))).once(["NORMAL","VERTEX"])(),nd=ki((()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),ed))).once(["NORMAL","VERTEX"])(),ad=new w,od=new a,ud=Zn(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),ld=Zn(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),dd=Zn(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?(ad.copy(r),od.makeRotationFromEuler(ad)):od.identity(),od})),cd=zl.negate().reflect(Zl),hd=zl.negate().refract(Zl,ud),pd=cd.transformDirection(cl).toVar("reflectVector"),gd=hd.transformDirection(cl).toVar("reflectVector"),md=new A;class fd extends Yu{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===R?pd:e.mapping===C?gd:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),en(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return e.renderer.coordinateSystem!==d&&r.isRenderTargetTexture||(t=en(t.x.negate(),t.yz)),dd.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const yd=Vi(fd).setParameterLength(1,4).setName("cubeTexture"),bd=(e=md,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Fi(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Fi(t)),null!==r&&(i.levelNode=Fi(r)),null!==s&&(i.biasNode=Fi(s))):i=yd(e,t,r,s),i};class xd extends qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}}class Td extends js{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=Vs.OBJECT}element(e){return Fi(new xd(this,Fi(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?tl(null,e,this.count):Array.isArray(this.getValueFromReference())?il(null,e):"texture"===e?Zu(null):"cubeTexture"===e?bd(null):Zn(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eFi(new Td(e,t,r)),vd=(e,t,r,s)=>Fi(new Td(e,t,s,r));class Nd extends Td{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 Sd=(e,t,r=null)=>Fi(new Nd(e,t,r)),Ed=$u(),wd=Gl.dFdx(),Ad=Gl.dFdy(),Rd=Ed.dFdx(),Cd=Ed.dFdy(),Md=Zl,Pd=Ad.cross(Md),Bd=Md.cross(wd),Ld=Pd.mul(Rd.x).add(Bd.mul(Cd.x)),Fd=Pd.mul(Rd.y).add(Bd.mul(Cd.y)),Id=Ld.dot(Ld).max(Fd.dot(Fd)),Dd=Id.equal(0).select(0,Id.inverseSqrt()),Vd=Ld.mul(Dd).toVar("tangentViewFrame"),Ud=Fd.mul(Dd).toVar("bitangentViewFrame"),Od=ki((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Hu("tangent","vec4"))))(),kd=Od.xyz.toVar("tangentLocal"),Gd=ki((({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?Bl.mul(nn(kd,0)).xyz.toVarying("v_tangentView").normalize():Vd,!0!==r.flatShading&&(s=jl(s)),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),zd=Gd.transformDirection(cl).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),Hd=ki((([e,t],{subBuildFn:r,material:s})=>{let i=e.mul(Od.w).xyz;return"NORMAL"===r&&!0!==s.flatShading&&(i=i.toVarying(t)),i})).once(["NORMAL"]),$d=Hd(ql.cross(Od),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Wd=Hd(Xl.cross(kd),"v_bitangentLocal").normalize().toVar("bitangentLocal"),jd=ki((({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?Hd(Zl.cross(Gd),"v_bitangentView").normalize():Ud,!0!==r.flatShading&&(s=jl(s)),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),qd=Hd(Jl.cross(zd),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Xd=dn(Gd,jd,Zl).toVar("TBNViewMatrix"),Kd=zl.mul(Xd),Yd=ki((()=>{let e=Pn.cross(zl);return e=e.cross(Pn).normalize(),e=Fo(e,Zl,Cn.mul(xn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})).once()();class Qd extends Ks{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=M}setup({material:e}){const{normalMapType:t,scaleNode:r}=this;let s=this.node.mul(2).sub(1);if(null!==r){let t=r;!0===e.flatShading&&(t=jl(t)),s=en(s.xy.mul(t),s.z)}let i=null;return t===P?i=rd(s):t===M?i=Xd.mul(s).normalize():(console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=Zl),i}}const Zd=Vi(Qd).setParameterLength(1,2),Jd=ki((({textureNode:e,bumpScale:t})=>{const r=t=>e.cache().context({getUV:e=>t(e.uvNode||$u()),forceUVContext:!0}),s=ji(r((e=>e)));return Yi(ji(r((e=>e.add(e.dFdx())))).sub(s),ji(r((e=>e.add(e.dFdy())))).sub(s)).mul(t)})),ec=ki((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(Wl),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()}));class tc extends Ks{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=Jd({textureNode:this.textureNode,bumpScale:e});return ec({surf_pos:Gl,surf_norm:Zl,dHdxy:t})}}const rc=Vi(tc).setParameterLength(1,2),sc=new Map;class ic extends js{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=sc.get(e);return void 0===r&&(r=Sd(e,t),sc.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===ic.COLOR){const e=void 0!==t.color?this.getColor(r):en();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===ic.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===ic.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ji(1);else if(r===ic.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===ic.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===ic.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===ic.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===ic.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===ic.NORMAL)t.normalMap?(s=Zd(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType):s=t.bumpMap?rc(this.getTexture("bump").r,this.getFloat("bumpScale")):Zl;else if(r===ic.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===ic.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===ic.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Zd(this.getTexture(r),this.getCache(r+"Scale","vec2")):Zl;else if(r===ic.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===ic.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(.07,1)}else if(r===ic.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=ln(zc.x,zc.y,zc.y.negate(),zc.x).mul(e.rg.mul(2).sub(Yi(1)).normalize().mul(e.b))}else s=zc;else if(r===ic.IRIDESCENCE_THICKNESS){const e=_d("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=_d("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===ic.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===ic.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===ic.IOR)s=this.getFloat(r);else if(r===ic.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===ic.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===ic.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):ji(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}ic.ALPHA_TEST="alphaTest",ic.COLOR="color",ic.OPACITY="opacity",ic.SHININESS="shininess",ic.SPECULAR="specular",ic.SPECULAR_STRENGTH="specularStrength",ic.SPECULAR_INTENSITY="specularIntensity",ic.SPECULAR_COLOR="specularColor",ic.REFLECTIVITY="reflectivity",ic.ROUGHNESS="roughness",ic.METALNESS="metalness",ic.NORMAL="normal",ic.CLEARCOAT="clearcoat",ic.CLEARCOAT_ROUGHNESS="clearcoatRoughness",ic.CLEARCOAT_NORMAL="clearcoatNormal",ic.EMISSIVE="emissive",ic.ROTATION="rotation",ic.SHEEN="sheen",ic.SHEEN_ROUGHNESS="sheenRoughness",ic.ANISOTROPY="anisotropy",ic.IRIDESCENCE="iridescence",ic.IRIDESCENCE_IOR="iridescenceIOR",ic.IRIDESCENCE_THICKNESS="iridescenceThickness",ic.IOR="ior",ic.TRANSMISSION="transmission",ic.THICKNESS="thickness",ic.ATTENUATION_DISTANCE="attenuationDistance",ic.ATTENUATION_COLOR="attenuationColor",ic.LINE_SCALE="scale",ic.LINE_DASH_SIZE="dashSize",ic.LINE_GAP_SIZE="gapSize",ic.LINE_WIDTH="linewidth",ic.LINE_DASH_OFFSET="dashOffset",ic.POINT_SIZE="size",ic.DISPERSION="dispersion",ic.LIGHT_MAP="light",ic.AO="ao";const nc=Ui(ic,ic.ALPHA_TEST),ac=Ui(ic,ic.COLOR),oc=Ui(ic,ic.SHININESS),uc=Ui(ic,ic.EMISSIVE),lc=Ui(ic,ic.OPACITY),dc=Ui(ic,ic.SPECULAR),cc=Ui(ic,ic.SPECULAR_INTENSITY),hc=Ui(ic,ic.SPECULAR_COLOR),pc=Ui(ic,ic.SPECULAR_STRENGTH),gc=Ui(ic,ic.REFLECTIVITY),mc=Ui(ic,ic.ROUGHNESS),fc=Ui(ic,ic.METALNESS),yc=Ui(ic,ic.NORMAL),bc=Ui(ic,ic.CLEARCOAT),xc=Ui(ic,ic.CLEARCOAT_ROUGHNESS),Tc=Ui(ic,ic.CLEARCOAT_NORMAL),_c=Ui(ic,ic.ROTATION),vc=Ui(ic,ic.SHEEN),Nc=Ui(ic,ic.SHEEN_ROUGHNESS),Sc=Ui(ic,ic.ANISOTROPY),Ec=Ui(ic,ic.IRIDESCENCE),wc=Ui(ic,ic.IRIDESCENCE_IOR),Ac=Ui(ic,ic.IRIDESCENCE_THICKNESS),Rc=Ui(ic,ic.TRANSMISSION),Cc=Ui(ic,ic.THICKNESS),Mc=Ui(ic,ic.IOR),Pc=Ui(ic,ic.ATTENUATION_DISTANCE),Bc=Ui(ic,ic.ATTENUATION_COLOR),Lc=Ui(ic,ic.LINE_SCALE),Fc=Ui(ic,ic.LINE_DASH_SIZE),Ic=Ui(ic,ic.LINE_GAP_SIZE),Dc=Ui(ic,ic.LINE_WIDTH),Vc=Ui(ic,ic.LINE_DASH_OFFSET),Uc=Ui(ic,ic.POINT_SIZE),Oc=Ui(ic,ic.DISPERSION),kc=Ui(ic,ic.LIGHT_MAP),Gc=Ui(ic,ic.AO),zc=Zn(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))})),Hc=ki((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class $c extends js{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===$c.VERTEX)s=e.getVertexIndex();else if(r===$c.INSTANCE)s=e.getInstanceIndex();else if(r===$c.DRAW)s=e.getDrawIndex();else if(r===$c.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===$c.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==$c.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=au(this).build(e,t)}return i}}$c.VERTEX="vertex",$c.INSTANCE="instance",$c.SUBGROUP="subgroup",$c.INVOCATION_LOCAL="invocationLocal",$c.INVOCATION_SUBGROUP="invocationSubgroup",$c.DRAW="draw";const Wc=Ui($c,$c.VERTEX),jc=Ui($c,$c.INSTANCE),qc=Ui($c,$c.SUBGROUP),Xc=Ui($c,$c.INVOCATION_SUBGROUP),Kc=Ui($c,$c.INVOCATION_LOCAL),Yc=Ui($c,$c.DRAW);class Qc extends js{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=Vs.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:r,instanceColor:s}=this;let{instanceMatrixNode:i,instanceColorNode:n}=this;if(null===i){if(t<=1e3)i=tl(r.array,"mat4",Math.max(t,1)).element(jc);else{const e=new B(r.array,16,1);this.buffer=e;const t=r.usage===y?Eu:Su,s=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];i=cn(...s)}this.instanceMatrixNode=i}if(s&&null===n){const e=new L(s.array,3),t=s.usage===y?Eu:Su;this.bufferColor=e,n=en(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=i.mul(Vl).xyz;if(Vl.assign(a),e.hasGeometryAttribute("normal")){const e=td(Xl,i);Xl.assign(e)}null!==this.instanceColorNode&&fn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==y&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==y&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}const Zc=Vi(Qc).setParameterLength(2,3);class Jc extends Qc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const eh=Vi(Jc).setParameterLength(1);class th extends js{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=jc:this.batchingIdNode=Yc);const t=ki((([e])=>{const t=qi(ju(Ju(this.batchMesh._indirectTexture),0).x),r=qi(e).mod(t),s=qi(e).div(t);return Ju(this.batchMesh._indirectTexture,Qi(r,s)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(qi(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=qi(ju(Ju(s),0).x),n=ji(r).mul(4).toInt().toVar(),a=n.mod(i),o=n.div(i),u=cn(Ju(s,Qi(a,o)),Ju(s,Qi(a.add(1),o)),Ju(s,Qi(a.add(2),o)),Ju(s,Qi(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=ki((([e])=>{const t=qi(ju(Ju(l),0).x),r=e,s=r.mod(t),i=r.div(t);return Ju(l,Qi(s,i)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);fn("vec3","vBatchColor").assign(t)}const d=dn(u);Vl.assign(u.mul(Vl));const c=Xl.div(en(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Xl.assign(h),e.hasGeometryAttribute("tangent")&&kd.mulAssign(d)}}const rh=Vi(th).setParameterLength(1);class sh extends qs{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 ih=Vi(sh).setParameterLength(2);class nh extends el{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=Es(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=Os.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){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return ih(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Os.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=vu(this.value),this._varying=au(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(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 ah=(e,t=null,r=0)=>Fi(new nh(e,t,r)),oh=new WeakMap;class uh extends js{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Vs.OBJECT,this.skinIndexNode=Hu("skinIndex","uvec4"),this.skinWeightNode=Hu("skinWeight","vec4"),this.bindMatrixNode=_d("bindMatrix","mat4"),this.bindMatrixInverseNode=_d("bindMatrixInverse","mat4"),this.boneMatricesNode=vd("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Vl,this.toPositionNode=Vl,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=oa(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}getSkinnedNormal(e=this.boneMatricesNode,t=Xl){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);let d=oa(s.x.mul(a),s.y.mul(o),s.z.mul(u),s.w.mul(l));return d=n.mul(d).mul(i),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=vd("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Ul)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Bs(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Ul.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Xl.assign(t),e.hasGeometryAttribute("tangent")&&kd.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;oh.get(t)!==e.frameId&&(oh.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const lh=e=>Fi(new uh(e));class dh extends js{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;eNumber(u)?">=":"<")),a)n=`while ( ${u} )`;else{const r={start:o,end:u},s=r.start,i=r.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=h)switch(typeof h){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(d,h);break;case"string":a=l+" "+h;break;default:h.isNode?a=l+" "+p()+" "+h.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else h="int"===d||"uint"===d?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+h;n=`for ( ${e.getVar(d,l)+" = "+s}; ${l+" "+c+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tFi(new dh(Di(e,"int"))).toStack(),hh=()=>Du("break").toStack(),ph=new WeakMap,gh=new s,mh=ki((({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=qi(Wc).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return Ju(e,Qi(u,o)).depth(i).xyz.mul(t)}));class fh extends js{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Zn(1),this.updateType=Vs.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=ph.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 F(m,h,p,a);f.type=I,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=ji(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ju(this.mesh.morphTexture,Qi(qi(e).add(1),qi(jc))).r):t.assign(_d("morphTargetInfluences","float").element(e).toVar()),Hi(t.notEqual(0),(()=>{!0===s&&Vl.addAssign(mh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(0)})),!0===i&&Xl.addAssign(mh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:qi(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 yh=Vi(fh).setParameterLength(1);class bh extends js{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class xh extends bh{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Th extends Ko{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:en().toVar("directDiffuse"),directSpecular:en().toVar("directSpecular"),indirectDiffuse:en().toVar("indirectDiffuse"),indirectSpecular:en().toVar("indirectSpecular")};return{radiance:en().toVar("radiance"),irradiance:en().toVar("irradiance"),iblIrradiance:en().toVar("iblIrradiance"),ambientOcclusion:ji(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 _h=Vi(Th);class vh extends bh{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Nh,Sh;class Eh extends js{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Eh.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Vs.NONE;return this.scope!==Eh.SIZE&&this.scope!==Eh.VIEWPORT||(e=Vs.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Eh.VIEWPORT?null!==t?Sh.copy(t.viewport):(e.getViewport(Sh),Sh.multiplyScalar(e.getPixelRatio())):null!==t?(Nh.width=t.width,Nh.height=t.height):e.getDrawingBufferSize(Nh)}setup(){const e=this.scope;let r=null;return r=e===Eh.SIZE?Zn(Nh||(Nh=new t)):e===Eh.VIEWPORT?Zn(Sh||(Sh=new s)):Yi(Rh.div(Ah)),r}generate(e){if(this.scope===Eh.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(Ah).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}Eh.COORDINATE="coordinate",Eh.VIEWPORT="viewport",Eh.SIZE="size",Eh.UV="uv";const wh=Ui(Eh,Eh.UV),Ah=Ui(Eh,Eh.SIZE),Rh=Ui(Eh,Eh.COORDINATE),Ch=Ui(Eh,Eh.VIEWPORT),Mh=Ch.zw,Ph=Rh.sub(Ch.xy),Bh=Ph.div(Mh),Lh=ki((()=>(console.warn('THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),Ah)),"vec2").once()(),Fh=new t;class Ih extends Yu{static get type(){return"ViewportTextureNode"}constructor(e=wh,t=null,r=null){null===r&&((r=new D).minFilter=V),super(r,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Vs.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Fh);const r=this.value;r.image.width===Fh.width&&r.image.height===Fh.height||(r.image.width=Fh.width,r.image.height=Fh.height,r.needsUpdate=!0);const s=r.generateMipmaps;r.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(r),r.generateMipmaps=s}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Dh=Vi(Ih).setParameterLength(0,3),Vh=Vi(Ih,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Uh=null;class Oh extends Ih{static get type(){return"ViewportDepthTextureNode"}constructor(e=wh,t=null){null===Uh&&(Uh=new U),super(e,t,Uh)}}const kh=Vi(Oh).setParameterLength(0,2);class Gh extends js{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===Gh.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===Gh.DEPTH_BASE)null!==r&&(s=jh().assign(r));else if(t===Gh.DEPTH)s=e.isPerspectiveCamera?Hh(Gl.z,ol,ul):zh(Gl.z,ol,ul);else if(t===Gh.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=$h(r,ol,ul);s=zh(e,ol,ul)}else s=r;else s=zh(Gl.z,ol,ul);return s}}Gh.DEPTH_BASE="depthBase",Gh.DEPTH="depth",Gh.LINEAR_DEPTH="linearDepth";const zh=(e,t,r)=>e.add(t).div(t.sub(r)),Hh=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),$h=(e,t,r)=>t.mul(r).div(r.sub(t).mul(e).sub(r)),Wh=(e,t,r)=>{t=t.max(1e-6).toVar();const s=Wa(e.negate().div(t)),i=Wa(r.div(t));return s.div(i)},jh=Vi(Gh,Gh.DEPTH_BASE),qh=Ui(Gh,Gh.DEPTH),Xh=Vi(Gh,Gh.LINEAR_DEPTH).setParameterLength(0,1),Kh=Xh(kh());qh.assign=e=>jh(e);class Yh extends js{static get type(){return"ClippingNode"}constructor(e=Yh.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===Yh.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===Yh.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return ki((()=>{const r=ji().toVar("distanceToPlane"),s=ji().toVar("distanceToGradient"),i=ji(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=il(t);ch(n,(({i:t})=>{const n=e.element(t);r.assign(Gl.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Uo(s.negate(),s,r))}))}const a=e.length;if(a>0){const t=il(e),n=ji(1).toVar("intersectionClipOpacity");ch(a,(({i:e})=>{const i=t.element(e);r.assign(Gl.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Uo(s.negate(),s,r).oneMinus())})),i.mulAssign(n.oneMinus())}yn.a.mulAssign(i),yn.a.equal(0).discard()}))()}setupDefault(e,t){return ki((()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=il(t);ch(r,(({i:t})=>{const r=e.element(t);Gl.dot(r.xyz).greaterThan(r.w).discard()}))}const s=e.length;if(s>0){const t=il(e),r=Ki(!0).toVar("clipped");ch(s,(({i:e})=>{const s=t.element(e);r.assign(Gl.dot(s.xyz).greaterThan(s.w).and(r))})),r.discard()}}))()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),ki((()=>{const s=il(e),i=nl(t.getClipDistance());ch(r,(({i:e})=>{const t=s.element(e),r=Gl.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)}))}))()}}Yh.ALPHA_TO_COVERAGE="alphaToCoverage",Yh.DEFAULT="default",Yh.HARDWARE="hardware";const Qh=ki((([e])=>Qa(la(1e4,Za(la(17,e.x).add(la(.1,e.y)))).mul(oa(.1,io(Za(la(13,e.y).add(e.x)))))))),Zh=ki((([e])=>Qh(Yi(Qh(e.xy),e.z)))),Jh=ki((([e])=>{const t=To(ao(lo(e.xyz)),ao(co(e.xyz))),r=ji(1).div(ji(.05).mul(t)).toVar("pixScale"),s=Yi(Ha(Xa(Wa(r))),Ha(Ka(Wa(r)))),i=Yi(Zh(Xa(s.x.mul(e.xyz))),Zh(Xa(s.y.mul(e.xyz)))),n=Qa(Wa(r)),a=oa(la(n.oneMinus(),i.x),la(n,i.y)),o=xo(n,n.oneMinus()),u=en(a.mul(a).div(la(2,o).mul(ua(1,o))),a.sub(la(.5,o)).div(ua(1,o)),ua(1,ua(1,a).mul(ua(1,a)).div(la(2,o).mul(ua(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Io(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class ep extends zu{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 tp=(e=0)=>Fi(new ep(e)),rp=ki((([e,t])=>xo(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),sp=ki((([e,t])=>xo(e.div(t.oneMinus()),1))).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),ip=ki((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),np=ki((([e,t])=>Fo(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),_o(.5,e)))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),ap=ki((([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return nn(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"}]}),op=ki((([e])=>nn(e.rgb.mul(e.a),e.a)),{color:"vec4",return:"vec4"}),up=ki((([e])=>(Hi(e.a.equal(0),(()=>nn(0))),nn(e.rgb.div(e.a),e.a))),{color:"vec4",return:"vec4"});class lp extends O{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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+_s(this)}build(e){this.setup(e)}setupObserver(e){return new fs(e)}setup(e){e.context.setupNormal=()=>iu(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=iu(this.setupVertex(e),"VERTEX"),i=this.vertexNode||s;let n;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.add(a);const i=nn(s,yn.a).max(0);n=this.setupOutput(e,i),In.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&In.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=nn(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.samples;this.alphaToCoverage&&t>1?s=Fi(new Yh(Yh.ALPHA_TO_COVERAGE)):e.stack.add(Fi(new Yh))}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.add(Fi(new Yh(Yh.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?Wh(Gl.z,ol,ul):zh(Gl.z,ol,ul))}null!==s&&qh.assign(s).toStack()}setupPositionView(){return Bl.mul(Vl).xyz}setupModelViewProjection(){return ll.mul(Gl)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Hc}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&yh(t).toStack(),!0===t.isSkinnedMesh&&lh(t).toStack(),this.displacementMap){const e=Sd("displacementMap","texture"),t=Sd("displacementScale","float"),r=Sd("displacementBias","float");Vl.addAssign(Xl.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&rh(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&eh(t).toStack(),null!==this.positionNode&&Vl.assign(iu(this.positionNode,"POSITION","vec3")),Vl}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&Ki(this.maskNode).not().discard();let r=this.colorNode?nn(this.colorNode):ac;if(!0===this.vertexColors&&t.hasAttribute("color")&&(r=r.mul(tp())),e.instanceColor){r=fn("vec3","vInstanceColor").mul(r)}if(e.isBatchedMesh&&e._colorsTexture){r=fn("vec3","vBatchColor").mul(r)}yn.assign(r);const s=this.opacityNode?ji(this.opacityNode):lc;yn.a.assign(yn.a.mul(s));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?ji(this.alphaTestNode):nc,yn.a.lessThanEqual(i).discard()),!0===this.alphaHash&&yn.a.lessThan(Jh(Vl)).discard();!1===this.transparent&&this.blending===k&&!1===this.alphaToCoverage?yn.a.assign(1):null===i&&yn.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?en(0):yn.rgb}setupNormal(){return this.normalNode?en(this.normalNode):yc}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Sd("envMap","cubeTexture"):Sd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new vh(kc)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);if(s&&s.isLightingNode&&t.push(s),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Gc;t.push(new xh(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}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=_h(n,t,r,s)}else null!==r&&(a=en(null!==s?Fo(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(bn.assign(en(i||uc)),a=a.add(bn)),a}setupFog(e,t){const r=e.fogNode;return r&&(In.assign(t),t=nn(r)),t}setupPremultipliedAlpha(e,t){return op(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=O.prototype.toJSON.call(this,e),s=vs(this);r.inputNodes={};for(const{property:t,childNode:i}of s)r.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=i(e.textures),s=i(e.images),n=i(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const dp=new G;class cp extends lp{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(dp),this.setValues(e)}}const hp=new z;class pp extends lp{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(hp),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ji(this.offsetNode):Vc,t=this.dashScaleNode?ji(this.dashScaleNode):Lc,r=this.dashSizeNode?ji(this.dashSizeNode):Fc,s=this.gapSizeNode?ji(this.gapSizeNode):Ic;Dn.assign(r),Vn.assign(s);const i=au(Hu("lineDistance").mul(t));(e?i.add(e):i).mod(Dn.add(Vn)).greaterThan(Dn).discard()}}let gp=null;class mp extends Ih{static get type(){return"ViewportSharedTextureNode"}constructor(e=wh,t=null){null===gp&&(gp=new D),super(e,t,gp)}updateReference(){return this}}const fp=Vi(mp).setParameterLength(0,2),yp=new z;class bp extends lp{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(yp),this.useColor=e.vertexColors,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=H,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.useColor,i=this._useDash,n=this._useWorldUnits,a=ki((({start:e,end:t})=>{const r=ll.element(2).element(2),s=ll.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return nn(Fo(e.xyz,t.xyz,s),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=ki((()=>{const e=Hu("instanceStart"),t=Hu("instanceEnd"),r=nn(Bl.mul(nn(e,1))).toVar("start"),s=nn(Bl.mul(nn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?ji(this.dashScaleNode):Lc,t=this.offsetNode?ji(this.offsetNode):Vc,r=Hu("instanceDistanceStart"),s=Hu("instanceDistanceEnd");let i=Dl.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),fn("float","lineDistance").assign(i)}n&&(fn("vec3","worldStart").assign(r.xyz),fn("vec3","worldEnd").assign(s.xyz));const o=Ch.z.div(Ch.w),u=ll.element(2).element(3).equal(-1);Hi(u,(()=>{Hi(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=ll.mul(r),d=ll.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=nn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=Fo(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=fn("vec4","worldPos");o.assign(Dl.y.lessThan(.5).select(r,s));const u=Dc.mul(.5);o.addAssign(nn(Dl.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(nn(Dl.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(nn(a.mul(u),0)),Hi(Dl.y.greaterThan(1).or(Dl.y.lessThan(0)),(()=>{o.subAssign(nn(a.mul(2).mul(u),0))}))),g.assign(ll.mul(o));const l=en().toVar();l.assign(Dl.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=Yi(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(Dl.x.lessThan(0).select(e.negate(),e)),Hi(Dl.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(Dl.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(Dc)),e.assign(e.div(Ch.w)),g.assign(Dl.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(nn(e,0,0)))}return g}))();const o=ki((({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 Yi(h,p)}));if(this.colorNode=ki((()=>{const e=$u();if(i){const t=this.dashSizeNode?ji(this.dashSizeNode):Fc,r=this.gapSizeNode?ji(this.gapSizeNode):Ic;Dn.assign(t),Vn.assign(r);const s=fn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(Dn.add(Vn)).greaterThan(Dn).discard()}const a=ji(1).toVar("alpha");if(n){const e=fn("vec3","worldStart"),s=fn("vec3","worldEnd"),n=fn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:en(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(Dc);if(!i)if(r&&t.samples>1){const e=h.fwidth();a.assign(Uo(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.samples>1){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=ji(s.fwidth()).toVar("dlen");Hi(e.y.abs().greaterThan(1),(()=>{a.assign(Uo(i.oneMinus(),i.add(1),s).oneMinus())}))}else Hi(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=Hu("instanceColorStart"),t=Hu("instanceColorEnd");u=Dl.y.lessThan(.5).select(e,t).mul(ac)}else u=ac;return nn(u,a)}))(),this.transparent){const e=this.opacityNode?ji(this.opacityNode):lc;this.outputNode=nn(this.colorNode.rgb.mul(e).add(fp().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)}}const xp=e=>Fi(e).mul(.5).add(.5),Tp=new $;class _p extends lp{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Tp),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ji(this.opacityNode):lc;yn.assign(pu(nn(xp(Zl),e),W))}}const vp=ki((([e=kl])=>{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 Yi(t,r)}));class Np extends j{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 q(5,5,5),n=vp(kl),a=new lp;a.colorNode=Zu(t,n,0),a.side=S,a.blending=H;const o=new X(i,a),u=new K;u.add(o),t.minFilter===V&&(t.minFilter=Y);const l=new Q(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.currentGenerateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}}const Sp=new WeakMap;class Ep extends Ks{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=bd(null);const t=new A;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Vs.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===Z||r===J){if(Sp.has(e)){const t=Sp.get(e);Ap(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Np(r.height);s.fromEquirectangularTexture(t,e),Ap(s.texture,e.mapping),this._cubeTexture=s.texture,Sp.set(e,s.texture),e.addEventListener("dispose",wp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function wp(e){const t=e.target;t.removeEventListener("dispose",wp);const r=Sp.get(t);void 0!==r&&(Sp.delete(t),r.dispose())}function Ap(e,t){t===Z?e.mapping=R:t===J&&(e.mapping=C)}const Rp=Vi(Ep).setParameterLength(1);class Cp extends bh{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Rp(this.envNode)}}class Mp extends bh{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ji(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Pp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Bp extends Pp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(nn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(nn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(yn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case re:s.rgb.assign(Fo(s.rgb,s.rgb.mul(i.rgb),pc.mul(gc)));break;case te:s.rgb.assign(Fo(s.rgb,i.rgb,pc.mul(gc)));break;case ee:s.rgb.addAssign(i.rgb.mul(pc.mul(gc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Lp=new se;class Fp extends lp{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Lp),this.setValues(e)}setupNormal(){return jl(Yl)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Cp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Mp(kc)),t}setupOutgoingLight(){return yn.rgb}setupLightingModel(){return new Bp}}const Ip=ki((({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))})),Dp=ki((e=>e.diffuseColor.mul(1/Math.PI))),Vp=ki((({dotNH:e})=>Fn.mul(ji(.5)).add(1).mul(ji(1/Math.PI)).mul(e.pow(Fn)))),Up=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(t).clamp(),s=zl.dot(t).clamp(),i=Ip({f0:Bn,f90:1,dotVH:s}),n=ji(.25),a=Vp({dotNH:r});return i.mul(n).mul(a)}));class Op extends Bp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Dp({diffuseColor:yn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(Up({lightDirection:e})).mul(pc))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Dp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const kp=new ie;class Gp extends lp{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(kp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Cp(t):null}setupLightingModel(){return new Op(!1)}}const zp=new ne;class Hp extends lp{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(zp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Cp(t):null}setupLightingModel(){return new Op}setupVariants(){const e=(this.shininessNode?ji(this.shininessNode):oc).max(1e-4);Fn.assign(e);const t=this.specularNode||dc;Bn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const $p=ki((e=>{if(!1===e.geometry.hasAttribute("normal"))return ji(0);const t=Yl.dFdx().abs().max(Yl.dFdy().abs());return t.x.max(t.y).max(t.z)})),Wp=ki((e=>{const{roughness:t}=e,r=$p();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s})),jp=ki((({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(Fa))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),qp=ki((({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(en(e.mul(r),t.mul(s),a).length()),l=a.mul(en(e.mul(i),t.mul(n),o).length());return da(.5,u.add(l)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Xp=ki((({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"}]}),Kp=ji(1/Math.PI),Yp=ki((({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=en(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return Kp.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"}]}),Qp=ki((({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Zl,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(zl).normalize(),d=n.dot(e).clamp(),c=n.dot(zl).clamp(),h=n.dot(l).clamp(),p=zl.dot(l).clamp();let g,m,f=Ip({f0:t,f90:r,dotVH:p});if(Pi(a)&&(f=En.mix(f,i)),Pi(o)){const t=Mn.dot(e),r=Mn.dot(zl),s=Mn.dot(l),i=Pn.dot(e),n=Pn.dot(zl),a=Pn.dot(l);g=qp({alphaT:Rn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=Yp({alphaT:Rn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=jp({alpha:u,dotNL:d,dotNV:c}),m=Xp({alpha:u,dotNH:h});return f.mul(g).mul(m)})),Zp=ki((({roughness:e,dotNV:t})=>{const r=nn(-1,-.0275,-.572,.022),s=nn(1,.0425,1.04,-.04),i=e.mul(r).add(s),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return Yi(-1.04,1.04).mul(n).add(i.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),Jp=ki((e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=Zp({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))})),eg=ki((({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(en(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"}]}),tg=ki((({roughness:e,dotNH:t})=>{const r=e.pow2(),s=ji(1).div(r),i=t.pow2().oneMinus().max(.0078125);return ji(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"}]}),rg=ki((({dotNV:e,dotNL:t})=>ji(1).div(ji(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),sg=ki((({lightDirection:e})=>{const t=e.add(zl).normalize(),r=Zl.dot(e).clamp(),s=Zl.dot(zl).clamp(),i=Zl.dot(t).clamp(),n=tg({roughness:Sn,dotNH:i}),a=rg({dotNV:s,dotNL:r});return Nn.mul(n).mul(a)})),ig=ki((({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=Yi(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"}]}),ng=ki((({f:e})=>{const t=e.length();return To(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),ag=ki((({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,To(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"}]}),og=ki((({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=en().toVar();return Hi(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(dn(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=en(0).toVar();f.addAssign(ag({v1:h,v2:p})),f.addAssign(ag({v1:p,v2:g})),f.addAssign(ag({v1:g,v2:m})),f.addAssign(ag({v1:m,v2:h})),c.assign(en(ng({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"}]}),ug=ki((({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=en().toVar();return Hi(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=en(0).toVar();d.addAssign(ag({v1:n,v2:a})),d.addAssign(ag({v1:a,v2:o})),d.addAssign(ag({v1:o,v2:l})),d.addAssign(ag({v1:l,v2:n})),u.assign(en(ng({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"}]}),lg=1/6,dg=e=>la(lg,la(e,la(e,e.negate().add(3)).sub(3)).add(1)),cg=e=>la(lg,la(e,la(e,la(3,e).sub(6))).add(4)),hg=e=>la(lg,la(e,la(e,la(-3,e).add(3)).add(3)).add(1)),pg=e=>la(lg,Ao(e,3)),gg=e=>dg(e).add(cg(e)),mg=e=>hg(e).add(pg(e)),fg=e=>oa(-1,cg(e).div(dg(e).add(cg(e)))),yg=e=>oa(1,pg(e).div(hg(e).add(pg(e)))),bg=(e,t,r)=>{const s=e.uvNode,i=la(s,t.zw).add(.5),n=Xa(i),a=Qa(i),o=gg(a.x),u=mg(a.x),l=fg(a.x),d=yg(a.x),c=fg(a.y),h=yg(a.y),p=Yi(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Yi(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=Yi(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Yi(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=gg(a.y).mul(oa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=mg(a.y).mul(oa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},xg=ki((([e,t])=>{const r=Yi(e.size(qi(t))),s=Yi(e.size(qi(t.add(1)))),i=da(1,r),n=da(1,s),a=bg(e,nn(i,r),Xa(t)),o=bg(e,nn(n,s),Ka(t));return Qa(t).mix(a,o)})),Tg=ki((([e,t])=>{const r=t.mul(Xu(e));return xg(e,r)})),_g=ki((([e,t,r,s,i])=>{const n=en(Vo(t.negate(),Ya(e),da(1,s))),a=en(ao(i[0].xyz),ao(i[1].xyz),ao(i[2].xyz));return Ya(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"}]}),vg=ki((([e,t])=>e.mul(Io(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Ng=Vh(),Sg=Vh(),Eg=ki((([e,t,r],{material:s})=>{const i=(s.side===S?Ng:Sg).sample(e),n=Wa(Ah.x).mul(vg(t,r));return xg(i,n)})),wg=ki((([e,t,r])=>(Hi(r.notEqual(0),(()=>{const s=$a(t).negate().div(r);return za(s.negate().mul(e))})),en(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Ag=ki((([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=nn().toVar(),f=en().toVar();const i=d.sub(1).mul(g.mul(.025)),n=en(d.sub(i),d,d.add(i));ch({start:0,end:3},(({i:i})=>{const d=n.element(i),g=_g(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(nn(y,1))),x=Yi(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Yi(x.x,x.y.oneMinus()));const T=Eg(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(wg(ao(g),h,p).element(i)))})),m.a.divAssign(3)}else{const i=_g(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(nn(n,1))),y=Yi(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Yi(y.x,y.y.oneMinus())),m=Eg(y,r,d),f=s.mul(wg(ao(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=en(Jp({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return nn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())})),Rg=dn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Cg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Mg=ki((({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=Fo(e,t,Uo(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();Hi(a.lessThan(0),(()=>en(1)));const o=a.sqrt(),u=Cg(n,e),l=Ip({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=ji(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return en(1).add(t).div(en(1).sub(t))})(i.clamp(0,.9999)),g=Cg(p,n.toVec3()),m=Ip({f0:g,f90:1,dotVH:o}),f=en(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=en(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(en(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return ch({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=en(54856e-17,44201e-17,52481e-17),i=en(1681e3,1795300,2208400),n=en(43278e5,93046e5,66121e5),a=ji(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=en(o.x.add(a),o.y,o.z).div(1.0685e-7),Rg.mul(o)})(ji(e).mul(y),ji(e).mul(b)).mul(2);v.addAssign(N.mul(t))})),v.max(en(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"}]}),Pg=ki((({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.pow2(),n=Xo(r.lessThan(.25),ji(-339.2).mul(i).add(ji(161.4).mul(r)).sub(25.9),ji(-8.48).mul(i).add(ji(14.3).mul(r)).sub(9.95)),a=Xo(r.lessThan(.25),ji(44).mul(i).sub(ji(23.7).mul(r)).add(3.26),ji(1.97).mul(i).sub(ji(3.27).mul(r)).add(.72));return Xo(r.lessThan(.25),0,ji(.1).mul(r).sub(.025)).add(n.mul(s).add(a).exp()).mul(1/Math.PI).saturate()})),Bg=en(.04),Lg=ji(1);class Fg extends Pp{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}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=en().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=en().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=en().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=en().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=en().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Zl.dot(zl).clamp();this.iridescenceFresnel=Mg({outsideIOR:ji(1),eta2:wn,cosTheta1:e,thinFilmThickness:An,baseF0:Bn}),this.iridescenceF0=eg({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Ol,r=gl.sub(Ol).normalize(),s=Jl,i=e.context;i.backdrop=Ag(s,r,xn,yn,Bn,Ln,t,El,cl,ll,On,Gn,Hn,zn,this.dispersion?$n:null),i.backdropAlpha=kn,yn.a.mulAssign(Fo(1,i.backdrop.a,kn))}super.start(e)}computeMultiscattering(e,t,r){const s=Zl.dot(zl).clamp(),i=Zp({roughness:xn,dotNV:s}),n=(this.iridescenceF0?En.mix(Bn,this.iridescenceF0):Bn).mul(i.x).add(r.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=Bn.add(Bn.oneMinus().mul(.047619)),u=n.mul(o).div(a.mul(o).oneMinus());e.addAssign(n),t.addAssign(u.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Zl.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(s.mul(sg({lightDirection:e}))),!0===this.clearcoat){const r=ed.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(Qp({lightDirection:e,f0:Bg,f90:Lg,roughness:vn,normalView:ed})))}r.directDiffuse.addAssign(s.mul(Dp({diffuseColor:yn.rgb}))),r.directSpecular.addAssign(s.mul(Qp({lightDirection:e,f0:Bn,f90:1,roughness:xn,iridescence:this.iridescence,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=Zl,h=zl,p=Gl.toVar(),g=ig({N:c,V:h,roughness:xn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=dn(en(m.x,0,m.y),en(0,1,0),en(m.z,0,m.w)).toVar(),b=Bn.mul(f.x).add(Bn.oneMinus().mul(f.y)).toVar();i.directSpecular.addAssign(e.mul(b).mul(og({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(yn).mul(og({N:c,V:h,P:p,mInv:dn(1,0,0,0,1,0,0,0,1),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;r.indirectDiffuse.addAssign(t.mul(Dp({diffuseColor:yn})))}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Nn,Pg({normal:Zl,viewDir:zl,roughness:Sn}))),!0===this.clearcoat){const e=ed.dot(zl).clamp(),t=Jp({dotNV:e,specularColor:Bg,specularF90:Lg,roughness:vn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=en().toVar("singleScattering"),n=en().toVar("multiScattering"),a=r.mul(1/Math.PI);this.computeMultiscattering(i,n,Ln);const o=i.add(n),u=yn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(t.mul(i)),s.indirectSpecular.addAssign(n.mul(a)),s.indirectDiffuse.addAssign(u.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Zl.dot(zl).clamp().add(t),i=xn.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=ed.dot(zl).clamp(),r=Ip({dotVH:e,f0:Bg,f90:Lg}),s=t.mul(_n.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(_n));t.assign(s)}if(!0===this.sheen){const e=Nn.r.max(Nn.g).max(Nn.b).mul(.157).oneMinus(),r=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(r)}}}const Ig=ji(1),Dg=ji(-2),Vg=ji(.8),Ug=ji(-1),Og=ji(.4),kg=ji(2),Gg=ji(.305),zg=ji(3),Hg=ji(.21),$g=ji(4),Wg=ji(4),jg=ji(16),qg=ki((([e])=>{const t=en(io(e)).toVar(),r=ji(-1).toVar();return Hi(t.x.greaterThan(t.z),(()=>{Hi(t.x.greaterThan(t.y),(()=>{r.assign(Xo(e.x.greaterThan(0),0,3))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})).Else((()=>{Hi(t.z.greaterThan(t.y),(()=>{r.assign(Xo(e.z.greaterThan(0),2,5))})).Else((()=>{r.assign(Xo(e.y.greaterThan(0),1,4))}))})),r})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Xg=ki((([e,t])=>{const r=Yi().toVar();return Hi(t.equal(0),(()=>{r.assign(Yi(e.z,e.y).div(io(e.x)))})).ElseIf(t.equal(1),(()=>{r.assign(Yi(e.x.negate(),e.z.negate()).div(io(e.y)))})).ElseIf(t.equal(2),(()=>{r.assign(Yi(e.x.negate(),e.y).div(io(e.z)))})).ElseIf(t.equal(3),(()=>{r.assign(Yi(e.z.negate(),e.y).div(io(e.x)))})).ElseIf(t.equal(4),(()=>{r.assign(Yi(e.x.negate(),e.z).div(io(e.y)))})).Else((()=>{r.assign(Yi(e.x,e.y).div(io(e.z)))})),la(.5,r.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Kg=ki((([e])=>{const t=ji(0).toVar();return Hi(e.greaterThanEqual(Vg),(()=>{t.assign(Ig.sub(e).mul(Ug.sub(Dg)).div(Ig.sub(Vg)).add(Dg))})).ElseIf(e.greaterThanEqual(Og),(()=>{t.assign(Vg.sub(e).mul(kg.sub(Ug)).div(Vg.sub(Og)).add(Ug))})).ElseIf(e.greaterThanEqual(Gg),(()=>{t.assign(Og.sub(e).mul(zg.sub(kg)).div(Og.sub(Gg)).add(kg))})).ElseIf(e.greaterThanEqual(Hg),(()=>{t.assign(Gg.sub(e).mul($g.sub(zg)).div(Gg.sub(Hg)).add(zg))})).Else((()=>{t.assign(ji(-2).mul(Wa(la(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Yg=ki((([e,t])=>{const r=e.toVar();r.assign(la(2,r).sub(1));const s=en(r,1).toVar();return Hi(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"}]}),Qg=ki((([e,t,r,s,i,n])=>{const a=ji(r),o=en(t),u=Io(Kg(a),Dg,n),l=Qa(u),d=Xa(u),c=en(Zg(e,o,d,s,i,n)).toVar();return Hi(l.notEqual(0),(()=>{const t=en(Zg(e,o,d.add(1),s,i,n)).toVar();c.assign(Fo(c,t,l))})),c})),Zg=ki((([e,t,r,s,i,n])=>{const a=ji(r).toVar(),o=en(t),u=ji(qg(o)).toVar(),l=ji(To(Wg.sub(a),0)).toVar();a.assign(To(a,Wg));const d=ji(Ha(a)).toVar(),c=Yi(Xg(o,u).mul(d.sub(2)).add(1)).toVar();return Hi(u.greaterThan(2),(()=>{c.y.addAssign(d),u.subAssign(3)})),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(la(3,jg))),c.y.addAssign(la(4,Ha(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(Yi(),Yi())})),Jg=ki((({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Ja(s),l=r.mul(u).add(i.cross(r).mul(Za(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return Zg(e,l,t,n,a,o)})),em=ki((({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=en(Xo(t,r,wo(r,s))).toVar();Hi(h.equal(en(0)),(()=>{h.assign(en(s.z,0,s.x.negate()))})),h.assign(Ya(h));const p=en().toVar();return p.addAssign(i.element(0).mul(Jg({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),ch({start:qi(1),end:e},(({i:e})=>{Hi(e.greaterThanEqual(n),(()=>{hh()}));const t=ji(a.mul(ji(e))).toVar();p.addAssign(i.element(e).mul(Jg({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(Jg({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))})),nn(p,1)})),tm=[.125,.215,.35,.446,.526,.582],rm=20,sm=new ae(-1,1,1,-1,0,1),im=new oe(90,1),nm=new e;let am=null,om=0,um=0;const lm=(1+Math.sqrt(5))/2,dm=1/lm,cm=[new r(-lm,dm,0),new r(lm,dm,0),new r(-dm,0,lm),new r(dm,0,lm),new r(0,lm,-dm),new r(0,lm,dm),new r(-1,1,-1),new r(1,1,-1),new r(-1,1,1),new r(1,1,1)],hm=new r,pm=new WeakMap,gm=[3,1,5,0,4,2],mm=Yg($u(),Hu("faceIndex")).normalize(),fm=en(mm.x,mm.y,mm.z);class ym{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=hm,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}am=this._renderer.getRenderTarget(),om=this._renderer.getActiveCubeFace(),um=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!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=_m(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=vm(),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===R||e.mapping===C?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?u=tm[o-e+4-1]:0===o&&(u=0),s.push(u);const l=1/(a-2),d=-l,c=1+l,h=[d,d,c,d,c,c,d,d,c,c,d,c],p=6,g=6,m=3,f=2,y=1,b=new Float32Array(m*g*p),x=new Float32Array(f*g*p),T=new Float32Array(y*g*p);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=gm[e];b.set(s,m*g*i),x.set(h,f*g*i);const n=[i,i,i,i,i,i];T.set(n,y*g*i)}const _=new pe;_.setAttribute("position",new ge(b,m)),_.setAttribute("uv",new ge(x,f)),_.setAttribute("faceIndex",new ge(T,y)),t.push(_),i.push(new X(_,null)),n>4&&n--}return{lodPlanes:t,sizeLods:r,sigmas:s,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,s){const i=il(new Array(rm).fill(0)),n=Zn(new r(0,1,0)),a=Zn(0),o=ji(rm),u=Zn(0),l=Zn(1),d=Zu(null),c=Zn(0),h=ji(1/t),p=ji(1/s),g=ji(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:fm,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Tm("blur");return f.fragmentNode=em({...m,latitudinal:u.equal(1)}),pm.set(f,m),f}(t,e.width,e.height)}}async _compileMaterial(e){const t=new X(this._lodPlanes[0],e);await this._renderer.compile(t,sm)}_sceneToCubeUV(e,t,r,s,i){const n=im;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(nm),u.autoClear=!1;let d=this._backgroundBox;if(null===d){const e=new se({name:"PMREM.Background",side:S,depthWrite:!1,depthTest:!1});d=new X(new q,e)}let c=!1;const h=e.background;h?h.isColor&&(d.material.color.copy(h),e.background=null,c=!0):(d.material.color.copy(nm),c=!0),u.setRenderTarget(s),u.clear(),c&&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;xm(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=h}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===R||e.mapping===C;s?null===this._cubemapMaterial&&(this._cubemapMaterial=_m(e)):null===this._equirectMaterial&&(this._equirectMaterial=vm(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;xm(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,sm)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let t=1;trm&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${g} samples when the maximum is set to 20`);const m=[];let f=0;for(let e=0;ey-4?s-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(l,sm)}}function bm(e,t){const r=new ue(e,t,{magFilter:Y,minFilter:Y,generateMipmaps:!1,type:ce,format:de,colorSpace:le});return r.texture.mapping=he,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function xm(e,t,r,s,i){e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i)}function Tm(e){const t=new lp;return t.depthTest=!1,t.depthWrite=!1,t.blending=H,t.name=`PMREM_${e}`,t}function _m(e){const t=Tm("cubemap");return t.fragmentNode=bd(e,fm),t}function vm(e){const t=Tm("equirect");return t.fragmentNode=Zu(e,vp(fm),0),t}const Nm=new WeakMap;function Sm(e,t,r){const s=function(e){let t=Nm.get(e);void 0===t&&(t=new WeakMap,Nm.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 Em extends Ks{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 x;s.isRenderTargetTexture=!0,this._texture=Zu(s),this._width=Zn(0),this._height=Zn(0),this._maxMip=Zn(0),this.updateBeforeType=Vs.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:Sm(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ym(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=dd.mul(en(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),Qg(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const wm=Vi(Em).setParameterLength(1,3),Am=new WeakMap;class Rm extends bh{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 e=r.isTextureNode?r.value:t[r.property];let s=Am.get(e);void 0===s&&(s=wm(e),Am.set(e,s)),r=s}const s=!0===t.useAnisotropy||t.anisotropy>0?Yd:Zl,i=r.context(Cm(xn,s)).mul(ld),n=r.context(Mm(Jl)).mul(Math.PI).mul(ld),a=Cu(i),o=Cu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(Cm(vn,ed)).mul(ld),t=Cu(e);u.addAssign(t)}}}const Cm=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=zl.negate().reflect(t),r=e.mul(e).mix(r,t).normalize(),r=r.transformDirection(cl)),r),getTextureLevel:()=>e}},Mm=e=>({getUV:()=>e,getTextureLevel:()=>ji(1)}),Pm=new me;class Bm extends lp{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(Pm),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Rm(t):null}setupLightingModel(){return new Fg}setupSpecular(){const e=Fo(en(.04),yn.rgb,Tn);Bn.assign(e),Ln.assign(1)}setupVariants(){const e=this.metalnessNode?ji(this.metalnessNode):fc;Tn.assign(e);let t=this.roughnessNode?ji(this.roughnessNode):mc;t=Wp({roughness:t}),xn.assign(t),this.setupSpecular(),yn.assign(nn(yn.rgb.mul(e.oneMinus()),yn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Lm=new fe;class Fm extends Bm{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(Lm),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?ji(this.iorNode):Mc;On.assign(e),Bn.assign(Fo(xo(Ro(On.sub(1).div(On.add(1))).mul(hc),en(1)).mul(cc),yn.rgb,Tn)),Ln.assign(Fo(cc,1,Tn))}setupLightingModel(){return new Fg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ji(this.clearcoatNode):bc,t=this.clearcoatRoughnessNode?ji(this.clearcoatRoughnessNode):xc;_n.assign(e),vn.assign(Wp({roughness:t}))}if(this.useSheen){const e=this.sheenNode?en(this.sheenNode):vc,t=this.sheenRoughnessNode?ji(this.sheenRoughnessNode):Nc;Nn.assign(e),Sn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ji(this.iridescenceNode):Ec,t=this.iridescenceIORNode?ji(this.iridescenceIORNode):wc,r=this.iridescenceThicknessNode?ji(this.iridescenceThicknessNode):Ac;En.assign(e),wn.assign(t),An.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?Yi(this.anisotropyNode):Sc).toVar();Cn.assign(e.length()),Hi(Cn.equal(0),(()=>{e.assign(Yi(1,0))})).Else((()=>{e.divAssign(Yi(Cn)),Cn.assign(Cn.saturate())})),Rn.assign(Cn.pow2().mix(xn.pow2(),1)),Mn.assign(Xd[0].mul(e.x).add(Xd[1].mul(e.y))),Pn.assign(Xd[1].mul(e.x).sub(Xd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ji(this.transmissionNode):Rc,t=this.thicknessNode?ji(this.thicknessNode):Cc,r=this.attenuationDistanceNode?ji(this.attenuationDistanceNode):Pc,s=this.attenuationColorNode?en(this.attenuationColorNode):Bc;if(kn.assign(e),Gn.assign(t),zn.assign(r),Hn.assign(s),this.useDispersion){const e=this.dispersionNode?ji(this.dispersionNode):Oc;$n.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?en(this.clearcoatNormalNode):Tc}setup(e){e.context.setupClearcoatNormal=()=>iu(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.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 Im extends Fg{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(Zl.mul(a)).normalize(),h=ji(zl.dot(c.negate()).saturate().pow(l).mul(d)),p=en(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Dm extends Fm{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=ji(.1),this.thicknessAmbientNode=ji(0),this.thicknessAttenuationNode=ji(.1),this.thicknessPowerNode=ji(2),this.thicknessScaleNode=ji(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Im(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 Vm=ki((({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=Yi(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Sd("gradientMap","texture").context({getUV:()=>i});return en(e.r)}{const e=i.fwidth().mul(.5);return Fo(en(.7),en(1),Uo(ji(.7).sub(e.x),ji(.7).add(e.x),i.x))}}));class Um extends Pp{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Vm({normal:ql,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Dp({diffuseColor:yn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Dp({diffuseColor:yn}))),s.indirectDiffuse.mulAssign(t)}}const Om=new ye;class km extends lp{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Om),this.setValues(e)}setupLightingModel(){return new Um}}const Gm=ki((()=>{const e=en(zl.z,0,zl.x.negate()).normalize(),t=zl.cross(e);return Yi(e.dot(Zl),t.dot(Zl)).mul(.495).add(.5)})).once(["NORMAL","VERTEX"])().toVar("matcapUV"),zm=new be;class Hm extends lp{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(zm),this.setValues(e)}setupVariants(e){const t=Gm;let r;r=e.material.matcap?Sd("matcap","texture").context({getUV:()=>t}):en(Fo(.2,.8,t.y)),yn.rgb.mulAssign(r.rgb)}}class $m extends Ks{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode: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=cn(nn(1,0,0,0),nn(0,Ja(e.x),Za(e.x).negate(),0),nn(0,Za(e.x),Ja(e.x),0),nn(0,0,0,1)),i=cn(nn(Ja(e.y),0,Za(e.y),0),nn(0,1,0,0),nn(Za(e.y).negate(),0,Ja(e.y),0),nn(0,0,0,1)),n=cn(nn(Ja(e.z),Za(e.z).negate(),0,0),nn(Za(e.z),Ja(e.z),0,0),nn(0,0,1,0),nn(0,0,0,1));return s.mul(i).mul(n).mul(nn(r,1)).xyz}}}const Wm=Vi($m).setParameterLength(2),jm=new xe;class qm extends lp{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(jm),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,s=this.sizeAttenuation,{positionNode:i,rotationNode:n,scaleNode:a}=this,o=Bl.mul(en(i||0));let u=Yi(El[0].xyz.length(),El[1].xyz.length());if(null!==a&&(u=u.mul(Yi(a))),!1===s)if(r.isPerspectiveCamera)u=u.mul(o.z.negate());else{const e=ji(2).div(ll.element(1).element(1));u=u.mul(e.mul(2))}let l=Dl.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>Fi(new mu(e,t,r)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=ji(n||_c),c=Wm(l,d);return nn(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 Xm=new Te;class Km extends qm{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(Xm),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Bl.mul(en(e||Vl)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:r,scaleNode:s,sizeNode:i}=this,n=Dl.xy.toVar(),a=Ch.z.div(Ch.w);if(r&&r.isNode){const e=ji(r);n.assign(Wm(n,e))}let o=null!==i?Yi(i):Uc;return!0===this.sizeAttenuation&&(o=o.mul(o.div(Gl.z.negate()))),s&&s.isNode&&(o=o.mul(Yi(s))),n.mulAssign(o.mul(2)),n.assign(n.div(Ch.z)),n.y.assign(n.y.mul(a)),n.assign(n.mul(t.w)),t.addAssign(nn(n,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class Ym extends Pp{constructor(){super(),this.shadowNode=ji(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){yn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(yn.rgb)}}const Qm=new _e;class Zm extends lp{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Qm),this.setValues(e)}setupLightingModel(){return new Ym}}const Jm=mn("vec3"),ef=mn("vec3"),tf=mn("vec3");class rf extends Pp{constructor(){super()}start(e){const{material:t,context:r}=e,s=mn("vec3"),i=mn("vec3");Hi(gl.sub(Ol).length().greaterThan(Cl.mul(2)),(()=>{s.assign(gl),i.assign(Ol)})).Else((()=>{s.assign(Ol),i.assign(gl)}));const n=i.sub(s),a=Zn("int").onRenderUpdate((({material:e})=>e.steps)),o=n.length().div(a).toVar(),u=n.normalize().toVar(),l=ji(0).toVar(),d=en(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(o)),ch(a,(()=>{const i=s.add(u.mul(l)),n=cl.mul(nn(i,1)).xyz;let a;null!==t.depthNode&&(ef.assign(Xh(Hh(n.z,ol,ul))),r.sceneDepthNode=Xh(t.depthNode).toVar()),r.positionWorld=i,r.shadowPositionWorld=i,r.positionView=n,Jm.assign(0),t.scatteringNode&&(a=t.scatteringNode({positionRay:i})),super.start(e),a&&Jm.mulAssign(a);const c=Jm.mul(.01).negate().mul(o).exp();d.mulAssign(c),l.addAssign(o)})),tf.addAssign(d.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?Hi(r.greaterThanEqual(ef),(()=>{Jm.addAssign(e)})):Jm.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(ug({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(tf)}}class sf extends lp{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=S,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new rf}}class nf{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,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,null!==this._animationLoop&&this._animationLoop(t,r)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class af{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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)}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.version),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&&(r+=e.uuid+","),r+=e.receiveShadow+",",bs(r)}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=Ts(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ts(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const lf=[];class df{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);lf[0]=e,lf[1]=t,lf[2]=n,lf[3]=i;let l=u.get(lf);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(lf,l)):(l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),lf.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new af)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new uf(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class cf{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 hf=1,pf=2,gf=3,mf=4,ff=16;class yf extends cf{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===hf?this.backend.createAttribute(e):t===pf?this.backend.createIndexAttribute(e):t===gf?this.backend.createStorageAttribute(e):t===mf&&this.backend.createIndirectStorageAttribute(e),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version{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)};t.addEventListener("dispose",r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,gf):this.updateAttribute(e,hf);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,pf);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,mf)}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}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=xf(t),e.set(t,r)):r.version!==bf(t)&&(this.attributes.delete(r),r=xf(t),e.set(t,r)),s=r}return s}}class _f{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,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):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class vf{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Nf extends vf{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Sf extends vf{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Ef=0;class wf{constructor(e,t,r,s=null,i=null){this.id=Ef++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class Af extends cf{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend: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 wf(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.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 wf(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new wf(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.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}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 Sf(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 Nf(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)}_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 Rf extends cf{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))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?mf:gf;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(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?mf:gf;this.attributes.update(e,r)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(s=!0);const o=t.update(),u=t.texture;o&&this.textures.updateTexture(u);const l=r.get(u);if(void 0!==l.externalTexture||e.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===r.isWebGPUBackend&&void 0===l.texture&&void 0===l.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,u,t.textureNode.value,s),this.textures.updateTexture(u),s=!0),!0===u.isStorageTexture){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)}}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function Cf(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 Mf(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 Pf(e){return(e.transmission>0||e.transmissionNode)&&e.side===E&&!1===e.forceSinglePass}class Bf{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?(Pf(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?(Pf(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||Cf),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Mf),this.transparent.length>1&&this.transparent.sort(t||Mf)}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 U,l.format=e.stencilBuffer?we:Ae,l.type=e.stencilBuffer?Re:T,l.image.width=o,l.image.height=u,l.image.depth=a.depth,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{e.removeEventListener("dispose",t);for(let e=0;e0){const s=e.image;if(void 0===s)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)console.warn("THREE.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),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version}if(!0!==r.initialized){r.initialized=!0,r.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}r.version=e.version}getSize(e,t=zf){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),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.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class $f extends e{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Wf extends gn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class jf extends js{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const r=new Li(t);return this._currentCond=Xo(e,r),this.add(this._currentCond)}ElseIf(e,t){const r=new Li(t),s=Xo(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Li(e),this}Switch(e){return this._expressionNode=Fi(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let r=0;r"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=0;for(const r of this.membersLayout){const s=r.type,i=Rs(s)*e,n=t%8,a=n%Cs(s),o=n+a;t+=a,0!==o&&8-oe.name===t));return r?r.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.addInclude(this)}generate(e){return this.getNodeType(e)}}class Kf extends js{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structLayoutNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structLayoutNode.getNodeType(e)}getMemberType(e,t){return this.structLayoutNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structLayoutNode.membersLayout,this.values)}`,this),t.name}}class Yf extends js{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t{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)})),ry=(e,t)=>Ao(la(4,e.mul(ua(1,e))),t),sy=ki((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),iy=ki((([e])=>en(sy(e.z.add(sy(e.y.mul(1)))),sy(e.z.add(sy(e.x.mul(1)))),sy(e.y.add(sy(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ny=ki((([e,t,r])=>{const s=en(e).toVar(),i=ji(1.4).toVar(),n=ji(0).toVar(),a=en(s).toVar();return ch({start:ji(0),end:ji(3),type:"float",condition:"<="},(()=>{const e=en(iy(a.mul(2))).toVar();s.addAssign(e.add(r.mul(ji(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=ji(sy(s.z.add(sy(s.x.add(sy(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 ay extends js{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null,this.global=!0}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let r=this._candidateFnCall;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._candidateFnCall=r=s(...t)}return r}}const oy=Vi(ay),uy=e=>(...t)=>oy(e,...t),ly=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.time)),dy=Zn(0).setGroup(Kn).onRenderUpdate((e=>e.deltaTime)),cy=Zn(0,"uint").setGroup(Kn).onRenderUpdate((e=>e.frameId)),hy=ki((([e,t,r=Yi(.5)])=>Wm(e.sub(r),t).add(r))),py=ki((([e,t,r=Yi(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))})),gy=ki((({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=El.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=El;const i=cl.mul(s);return Pi(t)&&(i[0][0]=El[0].length(),i[0][1]=0,i[0][2]=0),Pi(r)&&(i[1][0]=0,i[1][1]=El[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,ll.mul(i).mul(Vl)})),my=ki((([e=null])=>{const t=Xh();return Xh(kh(e)).sub(t).lessThan(0).select(wh,e)}));class fy extends js{static get type(){return"SpriteSheetUVNode"}constructor(e,t=$u(),r=ji(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=r}setup(){const{frameNode:e,uvNode:t,countNode:r}=this,{width:s,height:i}=r,n=e.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=r.reciprocal(),l=Yi(a,o);return t.add(l).mul(u)}}const yy=Vi(fy).setParameterLength(3),by=ki((([e,t=null,r=null,s=ji(1),i=Vl,n=Xl])=>{let a=n.abs().normalize();a=a.div(a.dot(en(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=Zu(d,o).mul(a.x),g=Zu(c,u).mul(a.y),m=Zu(h,l).mul(a.z);return oa(p,g,m)})),xy=new Me,Ty=new r,_y=new r,vy=new r,Ny=new a,Sy=new r(0,0,-1),Ey=new s,wy=new r,Ay=new r,Ry=new s,Cy=new t,My=new ue,Py=wh.flipX();My.depthTexture=new U(1,1);let By=!1;class Ly extends Yu{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||My.texture,Py),this._reflectorBaseNode=e.reflector||new Fy(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=Fi(new Ly({defaultTexture:My.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._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class Fy extends js{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new Pe,resolution:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1}=t;this.textureNode=e,this.target=r,this.resolution=s,this.generateMipmaps=i,this.bounces=n,this.depth=a,this.updateBeforeType=n?Vs.RENDER:Vs.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolution;t.getDrawingBufferSize(Cy),e.setSize(Math.round(Cy.width*r),Math.round(Cy.height*r))}setup(e){return this._updateResolution(My,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 ue(0,0,{type:ce}),!0===this.generateMipmaps&&(t.texture.minFilter=Be,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new U),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&By)return!1;By=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(Cy),this._updateResolution(o,s),_y.setFromMatrixPosition(n.matrixWorld),vy.setFromMatrixPosition(r.matrixWorld),Ny.extractRotation(n.matrixWorld),Ty.set(0,0,1),Ty.applyMatrix4(Ny),wy.subVectors(_y,vy);let u=!1;if(!0===wy.dot(Ty)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(By=!1);u=!0}wy.reflect(Ty).negate(),wy.add(_y),Ny.extractRotation(r.matrixWorld),Sy.set(0,0,-1),Sy.applyMatrix4(Ny),Sy.add(vy),Ay.subVectors(_y,Sy),Ay.reflect(Ty).negate(),Ay.add(_y),a.coordinateSystem=r.coordinateSystem,a.position.copy(wy),a.up.set(0,1,0),a.up.applyMatrix4(Ny),a.up.reflect(Ty),a.lookAt(Ay),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),xy.setFromNormalAndCoplanarPoint(Ty,_y),xy.applyMatrix4(a.matrixWorldInverse),Ey.set(xy.normal.x,xy.normal.y,xy.normal.z,xy.constant);const l=a.projectionMatrix;Ry.x=(Math.sign(Ey.x)+l.elements[8])/l.elements[0],Ry.y=(Math.sign(Ey.y)+l.elements[9])/l.elements[5],Ry.z=-1,Ry.w=(1+l.elements[10])/l.elements[14],Ey.multiplyScalar(1/Ey.dot(Ry));l.elements[2]=Ey.x,l.elements[6]=Ey.y,l.elements[10]=s.coordinateSystem===d?Ey.z-0:Ey.z+1-0,l.elements[14]=Ey.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const c=s.getRenderTarget(),h=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0,u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),s.setMRT(h),s.setRenderTarget(c),s.autoClear=p,i.visible=!0,By=!1,this.forceUpdate=!1}}const Iy=new ae(-1,1,1,-1,0,1);class Dy extends pe{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Le([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Le(t,2))}}const Vy=new Dy;class Uy extends X{constructor(e=null){super(Vy,e),this.camera=Iy,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,Iy)}render(e){e.render(this,Iy)}}const Oy=new t;class ky extends Yu{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:ce}){const i=new ue(t,r,s);super(i.texture,$u()),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 Uy(new lp),this.updateBeforeType=Vs.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(Oy),s=r.width*t,i=r.height*t;s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}this._quadMesh.material.fragmentNode=this._rttNode;const t=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){const e=new Yu(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const Gy=(e,...t)=>Fi(new ky(Fi(e),...t)),zy=ki((([e,t,r],s)=>{let i;s.renderer.coordinateSystem===d?(e=Yi(e.x,e.y.oneMinus()).mul(2).sub(1),i=nn(en(e,t),1)):i=nn(en(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=nn(r.mul(i));return n.xyz.div(n.w)})),Hy=ki((([e,t])=>{const r=t.mul(nn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return Yi(s.x,s.y.oneMinus())})),$y=ki((([e,t,r])=>{const s=ju(Ju(t)),i=Qi(e.mul(s)).toVar(),n=Ju(t,i).toVar(),a=Ju(t,i.sub(Qi(2,0))).toVar(),o=Ju(t,i.sub(Qi(1,0))).toVar(),u=Ju(t,i.add(Qi(1,0))).toVar(),l=Ju(t,i.add(Qi(2,0))).toVar(),d=Ju(t,i.add(Qi(0,2))).toVar(),c=Ju(t,i.add(Qi(0,1))).toVar(),h=Ju(t,i.sub(Qi(0,1))).toVar(),p=Ju(t,i.sub(Qi(0,2))).toVar(),g=io(ua(ji(2).mul(o).sub(a),n)).toVar(),m=io(ua(ji(2).mul(u).sub(l),n)).toVar(),f=io(ua(ji(2).mul(c).sub(d),n)).toVar(),y=io(ua(ji(2).mul(h).sub(p),n)).toVar(),b=zy(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(zy(e.sub(Yi(ji(1).div(s.x),0)),o,r)),b.negate().add(zy(e.add(Yi(ji(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(zy(e.add(Yi(0,ji(1).div(s.y))),c,r)),b.negate().add(zy(e.sub(Yi(0,ji(1).div(s.y))),h,r)));return Ya(wo(x,T))}));class Wy extends js{static get type(){return"SampleNode"}constructor(e){super(),this.callback=e,this.isSampleNode=!0}setup(){return this.sample($u())}sample(e){return this.callback(e)}}class jy extends L{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class qy extends ge{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class Xy extends js{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Ky=Ui(Xy),Yy=new w,Qy=new a;class Zy extends js{static get type(){return"SceneNode"}constructor(e=Zy.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,r=null!==this.scene?this.scene:e.scene;let s;return t===Zy.BACKGROUND_BLURRINESS?s=_d("backgroundBlurriness","float",r):t===Zy.BACKGROUND_INTENSITY?s=_d("backgroundIntensity","float",r):t===Zy.BACKGROUND_ROTATION?s=Zn("mat4").label("backgroundRotation").setGroup(Kn).onRenderUpdate((()=>{const e=r.background;return null!==e&&e.isTexture&&e.mapping!==Fe?(Yy.copy(r.backgroundRotation),Yy.x*=-1,Yy.y*=-1,Yy.z*=-1,Qy.makeRotationFromEuler(Yy)):Qy.identity(),Qy})):console.error("THREE.SceneNode: Unknown scope:",t),s}}Zy.BACKGROUND_BLURRINESS="backgroundBlurriness",Zy.BACKGROUND_INTENSITY="backgroundIntensity",Zy.BACKGROUND_ROTATION="backgroundRotation";const Jy=Ui(Zy,Zy.BACKGROUND_BLURRINESS),eb=Ui(Zy,Zy.BACKGROUND_INTENSITY),tb=Ui(Zy,Zy.BACKGROUND_ROTATION);class rb extends Yu{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.isStorageTextureNode=!0,this.access=Os.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}generate(e,t){let r;return r=null!==this.storeNode?this.generateStore(e):super.generate(e,t),r}toReadWrite(){return this.setAccess(Os.READ_WRITE)}toReadOnly(){return this.setAccess(Os.READ_ONLY)}toWriteOnly(){return this.setAccess(Os.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,"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(e,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e}}const sb=Vi(rb).setParameterLength(1,3),ib=ki((({texture:e,uv:t})=>{const r=1e-4,s=en().toVar();return Hi(t.x.lessThan(r),(()=>{s.assign(en(1,0,0))})).ElseIf(t.y.lessThan(r),(()=>{s.assign(en(0,1,0))})).ElseIf(t.z.lessThan(r),(()=>{s.assign(en(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{s.assign(en(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{s.assign(en(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{s.assign(en(0,0,-1))})).Else((()=>{const r=.01,i=e.sample(t.add(en(-.01,0,0))).r.sub(e.sample(t.add(en(r,0,0))).r),n=e.sample(t.add(en(0,-.01,0))).r.sub(e.sample(t.add(en(0,r,0))).r),a=e.sample(t.add(en(0,0,-.01))).r.sub(e.sample(t.add(en(0,0,r))).r);s.assign(en(i,n,a))})),s.normalize()}));class nb extends Yu{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return en(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!e.isFlipY()||!0!==r.isRenderTargetTexture&&!0!==r.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(qi(ju(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return ib({texture:this,uv:e})}}const ab=Vi(nb).setParameterLength(1,3);class ob extends Td{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 ub=new WeakMap;class lb extends Ks{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=Vs.OBJECT,this.updateAfterType=Vs.OBJECT,this.previousModelWorldMatrix=Zn(new a),this.previousProjectionMatrix=Zn(new a).setGroup(Kn),this.previousCameraViewMatrix=Zn(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=cb(r);this.previousModelWorldMatrix.value.copy(s);const i=db(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}){cb(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?ll:Zn(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(Bl).mul(Vl),s=this.previousProjectionMatrix.mul(t).mul(Ul),i=r.xy.div(r.w),n=s.xy.div(s.w);return ua(i,n)}}function db(e){let t=ub.get(e);return void 0===t&&(t={},ub.set(e,t)),t}function cb(e,t=0){const r=db(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const hb=Ui(lb),pb=ki((([e])=>yb(e.rgb))),gb=ki((([e,t=ji(1)])=>t.mix(yb(e.rgb),e.rgb))),mb=ki((([e,t=ji(1)])=>{const r=oa(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 Fo(e.rgb,s,i)})),fb=ki((([e,t=ji(1)])=>{const r=en(.57735,.57735,.57735),s=t.cos();return en(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(Eo(r,e.rgb).mul(s.oneMinus())))))})),yb=(e,t=en(c.getLuminanceCoefficients(new r)))=>Eo(e,t),bb=ki((([e,t=en(1),s=en(0),i=en(1),n=ji(1),a=en(c.getLuminanceCoefficients(new r,le))])=>{const o=e.rgb.dot(en(a)),u=To(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return Hi(u.r.greaterThan(0),(()=>{u.r.assign(l.r)})),Hi(u.g.greaterThan(0),(()=>{u.g.assign(l.g)})),Hi(u.b.greaterThan(0),(()=>{u.b.assign(l.b)})),u.assign(o.add(u.sub(o).mul(n))),nn(u.rgb,e.a)}));class xb extends Ks{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const Tb=Vi(xb).setParameterLength(2),_b=new t;class vb extends Yu{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Nb extends vb{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r}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}}class Sb extends Ks{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 U;i.isRenderTargetTexture=!0,i.name="depth";const n=new ue(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Zn(0),this._cameraFar=Zn(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=Vs.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}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=Fi(new Nb(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=Fi(new Nb(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=$h(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=zh(i,r,s)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Sb.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),_b.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(_b)),this._pixelRatio=i,this.setSize(_b.width,_b.height);const a=t.getRenderTarget(),o=t.getMRT(),u=s.layers.mask;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);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(r,s),t.setRenderTarget(a),t.setMRT(o),s.layers.mask=u}setSize(e,t){this._width=e,this._height=t;const r=this._width*this._pixelRatio*this._resolution,s=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(r,s)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Sb.COLOR="color",Sb.DEPTH="depth";class Eb extends Sb{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(Sb.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap}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 lp;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=S;const t=Xl.negate(),r=ll.mul(Bl),s=ji(1),i=r.mul(nn(Vl,1)),n=r.mul(nn(Vl.add(t),1)),a=Ya(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=nn(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 wb=ki((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ab=ki((([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"}]}),Rb=ki((([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"}]}),Cb=ki((([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)})),Mb=ki((([e,t])=>{const r=dn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=dn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=Cb(e),(e=s.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Pb=dn(en(1.6605,-.1246,-.0182),en(-.5876,1.1329,-.1006),en(-.0728,-.0083,1.1187)),Bb=dn(en(.6274,.0691,.0164),en(.3293,.9195,.088),en(.0433,.0113,.8956)),Lb=ki((([e])=>{const t=en(e).toVar(),r=en(t.mul(t)).toVar(),s=en(r.mul(r)).toVar();return ji(15.5).mul(s.mul(r)).sub(la(40.14,s.mul(t))).add(la(31.96,s).sub(la(6.868,r.mul(t))).add(la(.4298,r).add(la(.1191,t).sub(.00232))))})),Fb=ki((([e,t])=>{const r=en(e).toVar(),s=dn(en(.856627153315983,.137318972929847,.11189821299995),en(.0951212405381588,.761241990602591,.0767994186031903),en(.0482516061458583,.101439036467562,.811302368396859)),i=dn(en(1.1271005818144368,-.1413297634984383,-.14132976349843826),en(-.11060664309660323,1.157823702216272,-.11060664309660294),en(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ji(-12.47393),a=ji(4.026069);return r.mulAssign(t),r.assign(Bb.mul(r)),r.assign(s.mul(r)),r.assign(To(r,1e-10)),r.assign(Wa(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Io(r,0,1)),r.assign(Lb(r)),r.assign(i.mul(r)),r.assign(Ao(To(en(0),r),en(2.2))),r.assign(Pb.mul(r)),r.assign(Io(r,0,1)),r})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ib=ki((([e,t])=>{const r=ji(.76),s=ji(.15);e=e.mul(t);const i=xo(e.r,xo(e.g,e.b)),n=Xo(i.lessThan(.08),i.sub(la(6.25,i.mul(i))),.04);e.subAssign(n);const a=To(e.r,To(e.g,e.b));Hi(a.lessThan(r),(()=>e));const o=ua(1,r),u=ua(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=ua(1,da(1,s.mul(a.sub(u)).add(1)));return Fo(e,en(u),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Db extends js{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 Vb=Vi(Db).setParameterLength(1,3);class Ub extends Db{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}getNodeType(e){return this.getNodeFunction(e).type}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 Ob=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};class kb extends js{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new o,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:ji()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Ls(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?Fs(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const Gb=Vi(kb).setParameterLength(1);class zb extends Map{get(e,t=null,...r){if(this.has(e))return super.get(e);if(null!==t){const s=t(...r);return this.set(e,s),s}}}class Hb{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const $b=new zb;class Wb extends js{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new zb,this._output=Gb(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const r=this._outputs;return void 0===r[e]?r[e]=Gb(t):r[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const r=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),r[e]=t,r[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),r[e]=t,r[e].events.addEventListener("refresh",this.onRefresh)):void 0===r[e]?(r[e]=Gb(t),r[e].events.addEventListener("refresh",this.onRefresh)):r[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const r=this.getObject()[e];if("function"==typeof r)return r(...t)}async callAsync(e,...t){const r=this.getObject()[e];if("function"==typeof r)return"AsyncFunction"===r.constructor.name?await r(...t):r(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new Hb(this),t=$b.get("THREE"),r=$b.get("TSL"),s=this.getMethod(),i=[e,this._local,$b,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,r];this._object=s(...i);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:ji()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",r="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],r),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[bs(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const r in this.parameters)t.push(this.parameters[r].getCacheKey(e));return xs(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const jb=Vi(Wb).setParameterLength(1,2);function qb(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||Gl.z).negate()}const Xb=ki((([e,t],r)=>{const s=qb(r);return Uo(e,t,s)})),Kb=ki((([e],t)=>{const r=qb(t);return e.mul(e,r,r).negate().exp().oneMinus()})),Yb=ki((([e,t])=>nn(t.toFloat().mix(In.rgb,e.toVec3()),In.a)));let Qb=null,Zb=null;class Jb extends js{static get type(){return"RangeNode"}constructor(e=ji(),t=ji()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Ms(this.minNode.value)),r=e.getTypeLength(Ms(this.maxNode.value));return t>r?t:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.minNode.value,n=this.maxNode.value,a=e.getTypeLength(Ms(i)),o=e.getTypeLength(Ms(n));Qb=Qb||new s,Zb=Zb||new s,Qb.setScalar(0),Zb.setScalar(0),1===a?Qb.setScalar(i):i.isColor?Qb.set(i.r,i.g,i.b,1):Qb.set(i.x,i.y,i.z||0,i.w||0),1===o?Zb.setScalar(n):n.isColor?Zb.set(n.r,n.g,n.b,1):Zb.set(n.x,n.y,n.z||0,n.w||0);const l=4,d=l*t.count,c=new Float32Array(d);for(let e=0;eFi(new tx(e,t)),sx=rx("numWorkgroups","uvec3"),ix=rx("workgroupId","uvec3"),nx=rx("globalId","uvec3"),ax=rx("localId","uvec3"),ox=rx("subgroupSize","uint");const ux=Vi(class extends js{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class lx extends qs{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 dx extends js{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e}label(e){return this.name=e,this}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return Fi(new lx(this,e))}generate(e){return e.getScopedArray(this.name||`${this.scope}Array_${this.id}`,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class cx extends js{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)}getNodeType(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(!(1===r.length&&!0===r[0].isStackNode))return void 0===t.constNode&&(t.constNode=Du(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}cx.ATOMIC_LOAD="atomicLoad",cx.ATOMIC_STORE="atomicStore",cx.ATOMIC_ADD="atomicAdd",cx.ATOMIC_SUB="atomicSub",cx.ATOMIC_MAX="atomicMax",cx.ATOMIC_MIN="atomicMin",cx.ATOMIC_AND="atomicAnd",cx.ATOMIC_OR="atomicOr",cx.ATOMIC_XOR="atomicXor";const hx=Vi(cx),px=(e,t,r)=>hx(e,t,r).toStack();let gx;function mx(e){gx=gx||new WeakMap;let t=gx.get(e);return void 0===t&&gx.set(e,t={}),t}function fx(e){const t=mx(e);return t.shadowMatrix||(t.shadowMatrix=Zn("mat4").setGroup(Kn).onRenderUpdate((t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix))))}function yx(e,t=Ol){const r=fx(e).mul(t);return r.xyz.div(r.w)}function bx(e){const t=mx(e);return t.position||(t.position=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld))))}function xx(e){const t=mx(e);return t.targetPosition||(t.targetPosition=Zn(new r).setGroup(Kn).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld))))}function Tx(e){const t=mx(e);return t.viewPosition||(t.viewPosition=Zn(new r).setGroup(Kn).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}const _x=e=>cl.transformDirection(bx(e).sub(xx(e))),vx=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},Nx=new WeakMap,Sx=[];class Ex extends js{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=mn("vec3","totalDiffuse"),this.totalSpecularNode=mn("vec3","totalSpecular"),this.outgoingLightNode=mn("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(Fi(e));else{let s=null;if(null!==r&&(s=vx(e.id,r)),null===s){const r=i.getLightNodeClass(e.constructor);if(null===r){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let s=null;Nx.has(e)?s=Nx.get(e):(s=Fi(new r(e)),Nx.set(e,s)),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=en(null!==l?l.mix(g,u):u),s.material.transparent=!0),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 wx extends js{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Vs.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Ax.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ol)}}const Ax=mn("vec3","shadowPositionWorld");function Rx(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 Cx(e,t){return t=Rx(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function Mx(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 Px(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function Bx(e,t){return t=Px(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function Lx(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function Fx(e,t,r){return r=Bx(t,r=Cx(e,r))}function Ix(e,t,r){Mx(e,r),Lx(t,r)}var Dx=Object.freeze({__proto__:null,resetRendererAndSceneState:Fx,resetRendererState:Cx,resetSceneState:Bx,restoreRendererAndSceneState:Ix,restoreRendererState:Mx,restoreSceneState:Lx,saveRendererAndSceneState:function(e,t,r={}){return r=Px(t,r=Rx(e,r))},saveRendererState:Rx,saveSceneState:Px});const Vx=new WeakMap,Ux=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=Zu(e,t.xy).label("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)})),Ox=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=_d("radius","float",r).setGroup(Kn),o=Yi(1).div(n),u=o.x.negate().mul(a),l=o.y.negate().mul(a),d=o.x.mul(a),c=o.y.mul(a),h=u.div(2),p=l.div(2),g=d.div(2),m=c.div(2);return oa(i(t.xy.add(Yi(u,l)),t.z),i(t.xy.add(Yi(0,l)),t.z),i(t.xy.add(Yi(d,l)),t.z),i(t.xy.add(Yi(h,p)),t.z),i(t.xy.add(Yi(0,p)),t.z),i(t.xy.add(Yi(g,p)),t.z),i(t.xy.add(Yi(u,0)),t.z),i(t.xy.add(Yi(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(Yi(g,0)),t.z),i(t.xy.add(Yi(d,0)),t.z),i(t.xy.add(Yi(h,m)),t.z),i(t.xy.add(Yi(0,m)),t.z),i(t.xy.add(Yi(g,m)),t.z),i(t.xy.add(Yi(u,c)),t.z),i(t.xy.add(Yi(0,c)),t.z),i(t.xy.add(Yi(d,c)),t.z)).mul(1/17)})),kx=ki((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=Zu(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=_d("mapSize","vec2",r).setGroup(Kn),a=Yi(1).div(n),o=a.x,u=a.y,l=t.xy,d=Qa(l.mul(n).add(.5));return l.subAssign(d.mul(a)),oa(i(l,t.z),i(l.add(Yi(o,0)),t.z),i(l.add(Yi(0,u)),t.z),i(l.add(a),t.z),Fo(i(l.add(Yi(o.negate(),0)),t.z),i(l.add(Yi(o.mul(2),0)),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u)),t.z),i(l.add(Yi(o.mul(2),u)),t.z),d.x),Fo(i(l.add(Yi(0,u.negate())),t.z),i(l.add(Yi(0,u.mul(2))),t.z),d.y),Fo(i(l.add(Yi(o,u.negate())),t.z),i(l.add(Yi(o,u.mul(2))),t.z),d.y),Fo(Fo(i(l.add(Yi(o.negate(),u.negate())),t.z),i(l.add(Yi(o.mul(2),u.negate())),t.z),d.x),Fo(i(l.add(Yi(o.negate(),u.mul(2))),t.z),i(l.add(Yi(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)})),Gx=ki((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{const s=ji(1).toVar();let i=Zu(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=_o(t.z,i.x);return Hi(n.notEqual(ji(1)),(()=>{const e=t.z.sub(i.x),r=To(0,i.y.mul(i.y));let a=r.div(r.add(e.mul(e)));a=Io(ua(a,.3).div(.95-.3)),s.assign(Io(To(n,a)))})),s})),zx=ki((([e,t,r])=>{let s=Ol.sub(e).length();return s=s.sub(t).div(r.sub(t)),s=s.saturate(),s})),Hx=e=>{let t=Vx.get(e);if(void 0===t){const r=e.isPointLight?(e=>{const t=e.shadow.camera,r=_d("near","float",t).setGroup(Kn),s=_d("far","float",t).setGroup(Kn),i=xl(e);return zx(i,r,s)})(e):null;t=new lp,t.colorNode=nn(0,0,0,1),t.depthNode=r,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,Vx.set(e,t)}return t},$x=new af,Wx=[],jx=(e,t,r,s)=>{Wx[0]=e,Wx[1]=t;let i=$x.get(Wx);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===Ie)&&(s&&(Bs(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,$x.set(Wx,i)),Wx[0]=null,Wx[1]=null,i},qx=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanVertical"),a=ji(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));ch({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(Rh.xy,Yi(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=ja(a.sub(n.mul(n)));return Yi(n,l)})),Xx=ki((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=ji(0).toVar("meanHorizontal"),a=ji(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ji(1)).select(ji(0),ji(2).div(e.sub(1))),u=e.lessThanEqual(ji(1)).select(ji(0),ji(-1));ch({start:qi(0),end:qi(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(ji(e).mul(o));let d=s.sample(oa(Rh.xy,Yi(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(oa(d.y.mul(d.y),d.x.mul(d.x)))})),n.divAssign(e),a.divAssign(e);const l=ja(a.sub(n.mul(n)));return Yi(n,l)})),Kx=[Ux,Ox,kx,Gx];let Yx;const Qx=new Uy;class Zx extends wx{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture: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,ji(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=_d("bias","float",r).setGroup(Kn);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,s.coordinateSystem===d&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=_d("near","float",r.camera).setGroup(Kn),s=_d("far","float",r.camera).setGroup(Kn);n=Wh(e.negate(),t,s)}return a=en(a.x,a.y.oneMinus(),n.add(i)),a}getShadowFilterFn(e){return Kx[e]}setupRenderTarget(e,t){const r=new U(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=De;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}=e,{light:r,shadow:s}=this,i=t.shadowMap.type,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(s,e);if(s.camera.updateProjectionMatrix(),i===Ie&&!0!==s.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}));let t=Zu(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=Zu(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const i=_d("blurSamples","float",s).setGroup(Kn),o=_d("radius","float",s).setGroup(Kn),u=_d("mapSize","vec2",s).setGroup(Kn);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new lp);l.fragmentNode=qx({samples:i,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new lp),l.fragmentNode=Xx({samples:i,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=_d("intensity","float",s).setGroup(Kn),u=_d("normalBias","float",s).setGroup(Kn),l=fx(r).mul(Ax.add(Jl.mul(u))),d=this.setupShadowCoord(e,l),c=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const h=i===Ie&&!0!==s.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:a.texture,depthTexture:h,shadowCoord:d,shadow:s,depthLayer:this.depthLayer});let g=Zu(a.texture,d);n.isArrayTexture&&(g=g.depth(this.depthLayer));const m=Fo(1,p.rgb.mix(g,1),o.mul(g.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return ki((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth),i.render(n,t.camera)}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");Yx=Fx(i,n,Yx),n.overrideMaterial=Hx(r),i.setRenderObjectFunction(jx(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===Ie&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,Ix(i,n,Yx)}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),Qx.material=this.vsmMaterialVertical,Qx.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Qx.material=this.vsmMaterialHorizontal,Qx.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let 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 Jx=(e,t)=>Fi(new Zx(e,t)),eT=new e,tT=ki((([e,t])=>{const r=e.toVar(),s=io(r),i=da(1,To(s.x,To(s.y,s.z)));s.mulAssign(i),r.mulAssign(i.mul(t.mul(2).oneMinus()));const n=Yi(r.xy).toVar(),a=t.mul(1.5).oneMinus();return Hi(s.z.greaterThanEqual(a),(()=>{Hi(r.z.greaterThan(0),(()=>{n.x.assign(ua(4,r.x))}))})).ElseIf(s.x.greaterThanEqual(a),(()=>{const e=no(r.x);n.x.assign(r.z.mul(e).add(e.mul(2)))})).ElseIf(s.y.greaterThanEqual(a),(()=>{const e=no(r.y);n.x.assign(r.x.add(e.mul(2)).add(2)),n.y.assign(r.z.mul(e).sub(2))})),Yi(.125,.25).mul(n).add(Yi(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),rT=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s})=>Zu(e,tT(t,s.y)).compare(r))),sT=ki((({depthTexture:e,bd3D:t,dp:r,texelSize:s,shadow:i})=>{const n=_d("radius","float",i).setGroup(Kn),a=Yi(-1,1).mul(n).mul(s.y);return Zu(e,tT(t.add(a.xyy),s.y)).compare(r).add(Zu(e,tT(t.add(a.yyy),s.y)).compare(r)).add(Zu(e,tT(t.add(a.xyx),s.y)).compare(r)).add(Zu(e,tT(t.add(a.yyx),s.y)).compare(r)).add(Zu(e,tT(t,s.y)).compare(r)).add(Zu(e,tT(t.add(a.xxy),s.y)).compare(r)).add(Zu(e,tT(t.add(a.yxy),s.y)).compare(r)).add(Zu(e,tT(t.add(a.xxx),s.y)).compare(r)).add(Zu(e,tT(t.add(a.yxx),s.y)).compare(r)).mul(1/9)})),iT=ki((({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s})=>{const i=r.xyz.toVar(),n=i.length(),a=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.near)),o=Zn("float").setGroup(Kn).onRenderUpdate((()=>s.camera.far)),u=_d("bias","float",s).setGroup(Kn),l=Zn(s.mapSize).setGroup(Kn),d=ji(1).toVar();return Hi(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),(()=>{const r=n.sub(a).div(o.sub(a)).toVar();r.addAssign(u);const c=i.normalize(),h=Yi(1).div(l.mul(Yi(4,2)));d.assign(e({depthTexture:t,bd3D:c,dp:r,texelSize:h,shadow:s}))})),d})),nT=new s,aT=new t,oT=new t;class uT extends Zx{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Ue?rT:sT}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n}){return iT({filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.getFrameExtents();oT.copy(t.mapSize),oT.multiply(a),r.setSize(oT.width,oT.height),aT.copy(t.mapSize);const o=i.autoClear,u=i.getClearColor(eT),l=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const d=t.getViewportCount();for(let e=0;eFi(new uT(e,t));class dT extends bh{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Zn(this.color).setGroup(Kn),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vs.FRAME}getHash(){return this.light.uuid}getLightVector(e){return Tx(this.light).sub(e.context.positionView||Gl)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return Jx(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?Fi(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}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 cT=ki((({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)})),hT=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=cT({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class pT extends dT{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(2).setGroup(Kn)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return lT(this.light)}setupDirect(e){return hT({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const gT=ki((([e=$u()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()})),mT=ki((([e=$u()],{renderer:t,material:r})=>{const s=Lo(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.samples>1){const e=ji(s.fwidth()).toVar();i=Uo(e.oneMinus(),e.add(1),s).oneMinus()}else i=Xo(s.greaterThan(1),0,1);return i})),fT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Ki(e).toVar();return Xo(n,i,s)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),yT=ki((([e,t])=>{const r=Ki(t).toVar(),s=ji(e).toVar();return Xo(r,s.negate(),s)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),bT=ki((([e])=>{const t=ji(e).toVar();return qi(Xa(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),xT=ki((([e,t])=>{const r=ji(e).toVar();return t.assign(bT(r)),r.sub(ji(t))})),TT=uy([ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=ji(s).toVar(),l=ji(r).toVar(),d=ji(t).toVar(),c=ji(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]}),ki((([e,t,r,s,i,n])=>{const a=ji(n).toVar(),o=ji(i).toVar(),u=en(s).toVar(),l=en(r).toVar(),d=en(t).toVar(),c=en(e).toVar(),h=ji(ua(1,o)).toVar();return ua(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"}]})]),_T=uy([ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=ji(o).toVar(),m=ji(a).toVar(),f=ji(n).toVar(),y=ji(i).toVar(),b=ji(s).toVar(),x=ji(r).toVar(),T=ji(t).toVar(),_=ji(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]}),ki((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=ji(d).toVar(),h=ji(l).toVar(),p=ji(u).toVar(),g=en(o).toVar(),m=en(a).toVar(),f=en(n).toVar(),y=en(i).toVar(),b=en(s).toVar(),x=en(r).toVar(),T=en(t).toVar(),_=en(e).toVar(),v=ji(ua(1,p)).toVar(),N=ji(ua(1,h)).toVar();return ji(ua(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"}]})]),vT=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=Xi(e).toVar(),a=Xi(n.bitAnd(Xi(7))).toVar(),o=ji(fT(a.lessThan(Xi(4)),i,s)).toVar(),u=ji(la(2,fT(a.lessThan(Xi(4)),s,i))).toVar();return yT(o,Ki(a.bitAnd(Xi(1)))).add(yT(u,Ki(a.bitAnd(Xi(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),NT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=Xi(e).toVar(),u=Xi(o.bitAnd(Xi(15))).toVar(),l=ji(fT(u.lessThan(Xi(8)),a,n)).toVar(),d=ji(fT(u.lessThan(Xi(4)),n,fT(u.equal(Xi(12)).or(u.equal(Xi(14))),a,i))).toVar();return yT(l,Ki(u.bitAnd(Xi(1)))).add(yT(d,Ki(u.bitAnd(Xi(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"}]}),ST=uy([vT,NT]),ET=ki((([e,t,r])=>{const s=ji(r).toVar(),i=ji(t).toVar(),n=rn(e).toVar();return en(ST(n.x,i,s),ST(n.y,i,s),ST(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"}]}),wT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=ji(t).toVar(),o=rn(e).toVar();return en(ST(o.x,a,n,i),ST(o.y,a,n,i),ST(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"}]}),AT=uy([ET,wT]),RT=ki((([e])=>{const t=ji(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),CT=ki((([e])=>{const t=ji(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),MT=uy([RT,ki((([e])=>{const t=en(e).toVar();return la(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),PT=uy([CT,ki((([e])=>{const t=en(e).toVar();return la(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),BT=ki((([e,t])=>{const r=qi(t).toVar(),s=Xi(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(qi(32).sub(r)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),LT=ki((([e,t,r])=>{e.subAssign(r),e.bitXorAssign(BT(r,qi(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(BT(e,qi(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(BT(t,qi(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(BT(r,qi(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(BT(e,qi(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(BT(t,qi(4))),t.addAssign(e)})),FT=ki((([e,t,r])=>{const s=Xi(r).toVar(),i=Xi(t).toVar(),n=Xi(e).toVar();return s.bitXorAssign(i),s.subAssign(BT(i,qi(14))),n.bitXorAssign(s),n.subAssign(BT(s,qi(11))),i.bitXorAssign(n),i.subAssign(BT(n,qi(25))),s.bitXorAssign(i),s.subAssign(BT(i,qi(16))),n.bitXorAssign(s),n.subAssign(BT(s,qi(4))),i.bitXorAssign(n),i.subAssign(BT(n,qi(14))),s.bitXorAssign(i),s.subAssign(BT(i,qi(24))),s})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),IT=ki((([e])=>{const t=Xi(e).toVar();return ji(t).div(ji(Xi(qi(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),DT=ki((([e])=>{const t=ji(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"}]}),VT=uy([ki((([e])=>{const t=qi(e).toVar(),r=Xi(Xi(1)).toVar(),s=Xi(Xi(qi(3735928559)).add(r.shiftLeft(Xi(2))).add(Xi(13))).toVar();return FT(s.add(Xi(t)),s,s)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(Xi(2)).toVar(),n=Xi().toVar(),a=Xi().toVar(),o=Xi().toVar();return n.assign(a.assign(o.assign(Xi(qi(3735928559)).add(i.shiftLeft(Xi(2))).add(Xi(13))))),n.addAssign(Xi(s)),a.addAssign(Xi(r)),FT(n,a,o)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(Xi(3)).toVar(),o=Xi().toVar(),u=Xi().toVar(),l=Xi().toVar();return o.assign(u.assign(l.assign(Xi(qi(3735928559)).add(a.shiftLeft(Xi(2))).add(Xi(13))))),o.addAssign(Xi(n)),u.addAssign(Xi(i)),l.addAssign(Xi(s)),FT(o,u,l)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),ki((([e,t,r,s])=>{const i=qi(s).toVar(),n=qi(r).toVar(),a=qi(t).toVar(),o=qi(e).toVar(),u=Xi(Xi(4)).toVar(),l=Xi().toVar(),d=Xi().toVar(),c=Xi().toVar();return l.assign(d.assign(c.assign(Xi(qi(3735928559)).add(u.shiftLeft(Xi(2))).add(Xi(13))))),l.addAssign(Xi(o)),d.addAssign(Xi(a)),c.addAssign(Xi(n)),LT(l,d,c),l.addAssign(Xi(i)),FT(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"}]}),ki((([e,t,r,s,i])=>{const n=qi(i).toVar(),a=qi(s).toVar(),o=qi(r).toVar(),u=qi(t).toVar(),l=qi(e).toVar(),d=Xi(Xi(5)).toVar(),c=Xi().toVar(),h=Xi().toVar(),p=Xi().toVar();return c.assign(h.assign(p.assign(Xi(qi(3735928559)).add(d.shiftLeft(Xi(2))).add(Xi(13))))),c.addAssign(Xi(l)),h.addAssign(Xi(u)),p.addAssign(Xi(o)),LT(c,h,p),c.addAssign(Xi(a)),h.addAssign(Xi(n)),FT(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"}]})]),UT=uy([ki((([e,t])=>{const r=qi(t).toVar(),s=qi(e).toVar(),i=Xi(VT(s,r)).toVar(),n=rn().toVar();return n.x.assign(i.bitAnd(qi(255))),n.y.assign(i.shiftRight(qi(8)).bitAnd(qi(255))),n.z.assign(i.shiftRight(qi(16)).bitAnd(qi(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),ki((([e,t,r])=>{const s=qi(r).toVar(),i=qi(t).toVar(),n=qi(e).toVar(),a=Xi(VT(n,i,s)).toVar(),o=rn().toVar();return o.x.assign(a.bitAnd(qi(255))),o.y.assign(a.shiftRight(qi(8)).bitAnd(qi(255))),o.z.assign(a.shiftRight(qi(16)).bitAnd(qi(255))),o})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),OT=uy([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(xT(t.x,r)).toVar(),n=ji(xT(t.y,s)).toVar(),a=ji(DT(i)).toVar(),o=ji(DT(n)).toVar(),u=ji(TT(ST(VT(r,s),i,n),ST(VT(r.add(qi(1)),s),i.sub(1),n),ST(VT(r,s.add(qi(1))),i,n.sub(1)),ST(VT(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return MT(u)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(xT(t.x,r)).toVar(),a=ji(xT(t.y,s)).toVar(),o=ji(xT(t.z,i)).toVar(),u=ji(DT(n)).toVar(),l=ji(DT(a)).toVar(),d=ji(DT(o)).toVar(),c=ji(_T(ST(VT(r,s,i),n,a,o),ST(VT(r.add(qi(1)),s,i),n.sub(1),a,o),ST(VT(r,s.add(qi(1)),i),n,a.sub(1),o),ST(VT(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),ST(VT(r,s,i.add(qi(1))),n,a,o.sub(1)),ST(VT(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),ST(VT(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),ST(VT(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return PT(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),kT=uy([ki((([e])=>{const t=Yi(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=ji(xT(t.x,r)).toVar(),n=ji(xT(t.y,s)).toVar(),a=ji(DT(i)).toVar(),o=ji(DT(n)).toVar(),u=en(TT(AT(UT(r,s),i,n),AT(UT(r.add(qi(1)),s),i.sub(1),n),AT(UT(r,s.add(qi(1))),i,n.sub(1)),AT(UT(r.add(qi(1)),s.add(qi(1))),i.sub(1),n.sub(1)),a,o)).toVar();return MT(u)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi().toVar(),s=qi().toVar(),i=qi().toVar(),n=ji(xT(t.x,r)).toVar(),a=ji(xT(t.y,s)).toVar(),o=ji(xT(t.z,i)).toVar(),u=ji(DT(n)).toVar(),l=ji(DT(a)).toVar(),d=ji(DT(o)).toVar(),c=en(_T(AT(UT(r,s,i),n,a,o),AT(UT(r.add(qi(1)),s,i),n.sub(1),a,o),AT(UT(r,s.add(qi(1)),i),n,a.sub(1),o),AT(UT(r.add(qi(1)),s.add(qi(1)),i),n.sub(1),a.sub(1),o),AT(UT(r,s,i.add(qi(1))),n,a,o.sub(1)),AT(UT(r.add(qi(1)),s,i.add(qi(1))),n.sub(1),a,o.sub(1)),AT(UT(r,s.add(qi(1)),i.add(qi(1))),n,a.sub(1),o.sub(1)),AT(UT(r.add(qi(1)),s.add(qi(1)),i.add(qi(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return PT(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),GT=uy([ki((([e])=>{const t=ji(e).toVar(),r=qi(bT(t)).toVar();return IT(VT(r))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar();return IT(VT(r,s))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar();return IT(VT(r,s,i))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar(),n=qi(bT(t.w)).toVar();return IT(VT(r,s,i,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),zT=uy([ki((([e])=>{const t=ji(e).toVar(),r=qi(bT(t)).toVar();return en(IT(VT(r,qi(0))),IT(VT(r,qi(1))),IT(VT(r,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),ki((([e])=>{const t=Yi(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar();return en(IT(VT(r,s,qi(0))),IT(VT(r,s,qi(1))),IT(VT(r,s,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ki((([e])=>{const t=en(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar();return en(IT(VT(r,s,i,qi(0))),IT(VT(r,s,i,qi(1))),IT(VT(r,s,i,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),ki((([e])=>{const t=nn(e).toVar(),r=qi(bT(t.x)).toVar(),s=qi(bT(t.y)).toVar(),i=qi(bT(t.z)).toVar(),n=qi(bT(t.w)).toVar();return en(IT(VT(r,s,i,n,qi(0))),IT(VT(r,s,i,n,qi(1))),IT(VT(r,s,i,n,qi(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),HT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=ji(0).toVar(),l=ji(1).toVar();return ch(a,(()=>{u.addAssign(l.mul(OT(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"}]}),$T=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en(0).toVar(),l=ji(1).toVar();return ch(a,(()=>{u.addAssign(l.mul(kT(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"}]}),WT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar();return Yi(HT(o,a,n,i),HT(o.add(en(qi(19),qi(193),qi(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"}]}),jT=ki((([e,t,r,s])=>{const i=ji(s).toVar(),n=ji(r).toVar(),a=qi(t).toVar(),o=en(e).toVar(),u=en($T(o,a,n,i)).toVar(),l=ji(HT(o.add(en(qi(19),qi(193),qi(17))),a,n,i)).toVar();return nn(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"}]}),qT=uy([ki((([e,t,r,s,i,n,a])=>{const o=qi(a).toVar(),u=ji(n).toVar(),l=qi(i).toVar(),d=qi(s).toVar(),c=qi(r).toVar(),h=qi(t).toVar(),p=Yi(e).toVar(),g=en(zT(Yi(h.add(d),c.add(l)))).toVar(),m=Yi(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Yi(Yi(ji(h),ji(c)).add(m)).toVar(),y=Yi(f.sub(p)).toVar();return Hi(o.equal(qi(2)),(()=>io(y.x).add(io(y.y)))),Hi(o.equal(qi(3)),(()=>To(io(y.x),io(y.y)))),Eo(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"}]}),ki((([e,t,r,s,i,n,a,o,u])=>{const l=qi(u).toVar(),d=ji(o).toVar(),c=qi(a).toVar(),h=qi(n).toVar(),p=qi(i).toVar(),g=qi(s).toVar(),m=qi(r).toVar(),f=qi(t).toVar(),y=en(e).toVar(),b=en(zT(en(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=en(en(ji(f),ji(m),ji(g)).add(b)).toVar(),T=en(x.sub(y)).toVar();return Hi(l.equal(qi(2)),(()=>io(T.x).add(io(T.y)).add(io(T.z)))),Hi(l.equal(qi(3)),(()=>To(io(T.x),io(T.y),io(T.z)))),Eo(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"}]})]),XT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(xT(n.x,a),xT(n.y,o)).toVar(),l=ji(1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(qT(u,e,t,a,o,i,s)).toVar();l.assign(xo(l,r))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),KT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(xT(n.x,a),xT(n.y,o)).toVar(),l=Yi(1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(qT(u,e,t,a,o,i,s)).toVar();Hi(r.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(r)})).ElseIf(r.lessThan(l.y),(()=>{l.y.assign(r)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),YT=ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=Yi(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=Yi(xT(n.x,a),xT(n.y,o)).toVar(),l=en(1e6,1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{const r=ji(qT(u,e,t,a,o,i,s)).toVar();Hi(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)}))}))})),Hi(s.equal(qi(0)),(()=>{l.assign(ja(l))})),l})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),QT=uy([XT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(xT(n.x,a),xT(n.y,o),xT(n.z,u)).toVar(),d=ji(1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{ch({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(qT(l,e,t,r,a,o,u,i,s)).toVar();d.assign(xo(d,n))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),ZT=uy([KT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(xT(n.x,a),xT(n.y,o),xT(n.z,u)).toVar(),d=Yi(1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{ch({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(qT(l,e,t,r,a,o,u,i,s)).toVar();Hi(n.lessThan(d.x),(()=>{d.y.assign(d.x),d.x.assign(n)})).ElseIf(n.lessThan(d.y),(()=>{d.y.assign(n)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),JT=uy([YT,ki((([e,t,r])=>{const s=qi(r).toVar(),i=ji(t).toVar(),n=en(e).toVar(),a=qi().toVar(),o=qi().toVar(),u=qi().toVar(),l=en(xT(n.x,a),xT(n.y,o),xT(n.z,u)).toVar(),d=en(1e6,1e6,1e6).toVar();return ch({start:-1,end:qi(1),name:"x",condition:"<="},(({x:e})=>{ch({start:-1,end:qi(1),name:"y",condition:"<="},(({y:t})=>{ch({start:-1,end:qi(1),name:"z",condition:"<="},(({z:r})=>{const n=ji(qT(l,e,t,r,a,o,u,i,s)).toVar();Hi(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)}))}))}))})),Hi(s.equal(qi(0)),(()=>{d.assign(ja(d))})),d})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),e_=ki((([e])=>{const t=e.y,r=e.z,s=en().toVar();return Hi(t.lessThan(1e-4),(()=>{s.assign(en(r,r,r))})).Else((()=>{let i=e.x;i=i.sub(Xa(i)).mul(6).toVar();const n=qi(go(i)),a=i.sub(ji(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());Hi(n.equal(qi(0)),(()=>{s.assign(en(r,l,o))})).ElseIf(n.equal(qi(1)),(()=>{s.assign(en(u,r,o))})).ElseIf(n.equal(qi(2)),(()=>{s.assign(en(o,r,l))})).ElseIf(n.equal(qi(3)),(()=>{s.assign(en(o,u,r))})).ElseIf(n.equal(qi(4)),(()=>{s.assign(en(l,o,r))})).Else((()=>{s.assign(en(r,o,u))}))})),s})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),t_=ki((([e])=>{const t=en(e).toVar(),r=ji(t.x).toVar(),s=ji(t.y).toVar(),i=ji(t.z).toVar(),n=ji(xo(r,xo(s,i))).toVar(),a=ji(To(r,To(s,i))).toVar(),o=ji(a.sub(n)).toVar(),u=ji().toVar(),l=ji().toVar(),d=ji().toVar();return d.assign(a),Hi(a.greaterThan(0),(()=>{l.assign(o.div(a))})).Else((()=>{l.assign(0)})),Hi(l.lessThanEqual(0),(()=>{u.assign(0)})).Else((()=>{Hi(r.greaterThanEqual(a),(()=>{u.assign(s.sub(i).div(o))})).ElseIf(s.greaterThanEqual(a),(()=>{u.assign(oa(2,i.sub(r).div(o)))})).Else((()=>{u.assign(oa(4,r.sub(s).div(o)))})),u.mulAssign(1/6),Hi(u.lessThan(0),(()=>{u.addAssign(1)}))})),en(u,l,d)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),r_=ki((([e])=>{const t=en(e).toVar(),r=sn(ma(t,en(.04045))).toVar(),s=en(t.div(12.92)).toVar(),i=en(Ao(To(t.add(en(.055)),en(0)).div(1.055),en(2.4))).toVar();return Fo(s,i,r)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),s_=(e,t)=>{e=ji(e),t=ji(t);const r=Yi(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Uo(e.sub(r),e.add(r),t)},i_=(e,t,r,s)=>Fo(e,t,r[s].clamp()),n_=(e,t,r,s,i)=>Fo(e,t,s_(r,s[i])),a_=ki((([e,t,r])=>{const s=Ya(e).toVar(),i=ua(ji(.5).mul(t.sub(r)),Ol).div(s).toVar(),n=ua(ji(-.5).mul(t.sub(r)),Ol).div(s).toVar(),a=en().toVar();a.x=s.x.greaterThan(ji(0)).select(i.x,n.x),a.y=s.y.greaterThan(ji(0)).select(i.y,n.y),a.z=s.z.greaterThan(ji(0)).select(i.z,n.z);const o=xo(a.x,a.y,a.z).toVar();return Ol.add(s.mul(o)).toVar().sub(r)})),o_=ki((([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(la(r,r).sub(la(s,s)))),n}));var u_=Object.freeze({__proto__:null,BRDF_GGX:Qp,BRDF_Lambert:Dp,BasicPointShadowFilter:rT,BasicShadowFilter:Ux,Break:hh,Const:tu,Continue:()=>Du("continue").toStack(),DFGApprox:Zp,D_GGX:Xp,Discard:Vu,EPSILON:Fa,F_Schlick:Ip,Fn:ki,INFINITY:Ia,If:Hi,Loop:ch,NodeAccess:Os,NodeShaderStage:Ds,NodeType:Us,NodeUpdateType:Vs,PCFShadowFilter:Ox,PCFSoftShadowFilter:kx,PI:Da,PI2:Va,PointShadowFilter:sT,Return:()=>Du("return").toStack(),Schlick_to_F0:eg,ScriptableNodeResources:$b,ShaderNode:Li,Stack:$i,Switch:(...e)=>ni.Switch(...e),TBNViewMatrix:Xd,VSMShadowFilter:Gx,V_GGX_SmithCorrelated:jp,Var:eu,abs:io,acesFilmicToneMapping:Mb,acos:ro,add:oa,addMethodChaining:oi,addNodeElement:function(e){console.warn("THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:Fb,all:Ua,alphaT:Rn,and:ba,anisotropy:Cn,anisotropyB:Pn,anisotropyT:Mn,any:Oa,append:e=>(console.warn("THREE.TSL: append() has been renamed to Stack()."),$i(e)),array:ea,arrayBuffer:e=>Fi(new si(e,"ArrayBuffer")),asin:to,assign:ra,atan:so,atan2:$o,atomicAdd:(e,t)=>px(cx.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>px(cx.ATOMIC_AND,e,t),atomicFunc:px,atomicLoad:e=>px(cx.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>px(cx.ATOMIC_MAX,e,t),atomicMin:(e,t)=>px(cx.ATOMIC_MIN,e,t),atomicOr:(e,t)=>px(cx.ATOMIC_OR,e,t),atomicStore:(e,t)=>px(cx.ATOMIC_STORE,e,t),atomicSub:(e,t)=>px(cx.ATOMIC_SUB,e,t),atomicXor:(e,t)=>px(cx.ATOMIC_XOR,e,t),attenuationColor:Hn,attenuationDistance:zn,attribute:Hu,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new qy(e,r,s);return ah(i,t,e)},backgroundBlurriness:Jy,backgroundIntensity:eb,backgroundRotation:tb,batch:rh,bentNormalView:Yd,billboarding:gy,bitAnd:va,bitNot:Na,bitOr:Sa,bitXor:Ea,bitangentGeometry:$d,bitangentLocal:Wd,bitangentView:jd,bitangentWorld:qd,bitcast:yo,blendBurn:rp,blendColor:ap,blendDodge:sp,blendOverlay:np,blendScreen:ip,blur:em,bool:Ki,buffer:tl,bufferAttribute:vu,bumpMap:rc,burn:(...e)=>(console.warn('THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.'),rp(e)),bvec2:Ji,bvec3:sn,bvec4:un,bypass:Pu,cache:Cu,call:ia,cameraFar:ul,cameraIndex:al,cameraNear:ol,cameraNormalMatrix:pl,cameraPosition:gl,cameraProjectionMatrix:ll,cameraProjectionMatrixInverse:dl,cameraViewMatrix:cl,cameraWorldMatrix:hl,cbrt:Bo,cdl:bb,ceil:Ka,checker:gT,cineonToneMapping:Rb,clamp:Io,clearcoat:_n,clearcoatNormalView:ed,clearcoatRoughness:vn,code:Vb,color:Wi,colorSpaceToWorking:pu,colorToDirection:e=>Fi(e).mul(2).sub(1),compute:Au,computeSkinning:(e,t=null)=>{const r=new uh(e);return r.positionNode=ah(new L(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(jc).toVar(),r.skinIndexNode=ah(new L(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(jc).toVar(),r.skinWeightNode=ah(new L(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(jc).toVar(),r.bindMatrixNode=Zn(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=Zn(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=tl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,Fi(r)},context:Yo,convert:pn,convertColorSpace:(e,t,r)=>Fi(new cu(Fi(e),t,r)),convertToTexture:(e,...t)=>e.isTextureNode?e:e.isPassNode?e.getTextureNode():Gy(e,...t),cos:Ja,cross:wo,cubeTexture:bd,cubeTextureBase:yd,cubeToUV:tT,dFdx:lo,dFdy:co,dashSize:Dn,debug:Gu,decrement:Pa,decrementBefore:Ca,defaultBuildStages:Gs,defaultShaderStages:ks,defined:Pi,degrees:Ga,deltaTime:dy,densityFog:function(e,t){return console.warn('THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),Yb(e,Kb(t))},densityFogFactor:Kb,depth:qh,depthPass:(e,t,r)=>Fi(new Sb(Sb.DEPTH,e,t,r)),difference:So,diffuseColor:yn,directPointLight:hT,directionToColor:xp,directionToFaceDirection:jl,dispersion:$n,distance:No,div:da,dodge:(...e)=>(console.warn('THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.'),sp(e)),dot:Eo,drawIndex:Yc,dynamicBufferAttribute:Nu,element:hn,emissive:bn,equal:ha,equals:bo,equirectUV:vp,exp:za,exp2:Ha,expression:Du,faceDirection:Wl,faceForward:Oo,faceforward:Wo,float:ji,floor:Xa,fog:Yb,fract:Qa,frameGroup:Xn,frameId:cy,frontFacing:$l,fwidth:mo,gain:(e,t)=>e.lessThan(.5)?ry(e.mul(2),t).div(2):ua(1,ry(la(ua(1,e),2),t).div(2)),gapSize:Vn,getConstNodeType:Bi,getCurrentStack:zi,getDirection:Yg,getDistanceAttenuation:cT,getGeometryRoughness:$p,getNormalFromDepth:$y,getParallaxCorrectNormal:a_,getRoughness:Wp,getScreenPosition:Hy,getShIrradianceAt:o_,getShadowMaterial:Hx,getShadowRenderObjectFunction:jx,getTextureIndex:Zf,getViewPosition:zy,globalId:nx,glsl:(e,t)=>Vb(e,t,"glsl"),glslFn:(e,t)=>Ob(e,t,"glsl"),grayscale:pb,greaterThan:ma,greaterThanEqual:ya,hash:ty,highpModelNormalViewMatrix:Il,highpModelViewMatrix:Fl,hue:fb,increment:Ma,incrementBefore:Ra,instance:Zc,instanceIndex:jc,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=ws("float")):(r=As(t),s=ws(t));const i=new jy(e,r,s);return ah(i,t,e)},instancedBufferAttribute:Su,instancedDynamicBufferAttribute:Eu,instancedMesh:eh,int:qi,inverseSqrt:qa,inversesqrt:jo,invocationLocalIndex:Kc,invocationSubgroupIndex:Xc,ior:On,iridescence:En,iridescenceIOR:wn,iridescenceThickness:An,ivec2:Qi,ivec3:tn,ivec4:an,js:(e,t)=>Vb(e,t,"js"),label:Qo,length:ao,lengthSq:Lo,lessThan:ga,lessThanEqual:fa,lightPosition:bx,lightProjectionUV:yx,lightShadowMatrix:fx,lightTargetDirection:_x,lightTargetPosition:xx,lightViewPosition:Tx,lightingContext:_h,lights:(e=[])=>Fi(new Ex).setLights(e),linearDepth:Xh,linearToneMapping:wb,localId:ax,log:$a,log2:Wa,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul($a(r.div(t)));return ji(Math.E).pow(s).mul(t).negate()},luminance:yb,mat2:ln,mat3:dn,mat4:cn,matcapUV:Gm,materialAO:Gc,materialAlphaTest:nc,materialAnisotropy:Sc,materialAnisotropyVector:zc,materialAttenuationColor:Bc,materialAttenuationDistance:Pc,materialClearcoat:bc,materialClearcoatNormal:Tc,materialClearcoatRoughness:xc,materialColor:ac,materialDispersion:Oc,materialEmissive:uc,materialEnvIntensity:ld,materialEnvRotation:dd,materialIOR:Mc,materialIridescence:Ec,materialIridescenceIOR:wc,materialIridescenceThickness:Ac,materialLightMap:kc,materialLineDashOffset:Vc,materialLineDashSize:Fc,materialLineGapSize:Ic,materialLineScale:Lc,materialLineWidth:Dc,materialMetalness:fc,materialNormal:yc,materialOpacity:lc,materialPointSize:Uc,materialReference:Sd,materialReflectivity:gc,materialRefractionRatio:ud,materialRotation:_c,materialRoughness:mc,materialSheen:vc,materialSheenRoughness:Nc,materialShininess:oc,materialSpecular:dc,materialSpecularColor:hc,materialSpecularIntensity:cc,materialSpecularStrength:pc,materialThickness:Cc,materialTransmission:Rc,max:To,maxMipLevel:Xu,mediumpModelViewMatrix:Ll,metalness:Tn,min:xo,mix:Fo,mixElement:Go,mod:ca,modInt:Ba,modelDirection:Sl,modelNormalMatrix:Ml,modelPosition:wl,modelRadius:Cl,modelScale:Al,modelViewMatrix:Bl,modelViewPosition:Rl,modelViewProjection:Hc,modelWorldMatrix:El,modelWorldMatrixInverse:Pl,morphReference:yh,mrt:ey,mul:la,mx_aastep:s_,mx_cell_noise_float:(e=$u())=>GT(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>ji(e).sub(r).mul(t).add(r),mx_fractal_noise_float:(e=$u(),t=3,r=2,s=.5,i=1)=>HT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec2:(e=$u(),t=3,r=2,s=.5,i=1)=>WT(e,qi(t),r,s).mul(i),mx_fractal_noise_vec3:(e=$u(),t=3,r=2,s=.5,i=1)=>$T(e,qi(t),r,s).mul(i),mx_fractal_noise_vec4:(e=$u(),t=3,r=2,s=.5,i=1)=>jT(e,qi(t),r,s).mul(i),mx_hsvtorgb:e_,mx_noise_float:(e=$u(),t=1,r=0)=>OT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=$u(),t=1,r=0)=>kT(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=$u(),t=1,r=0)=>{e=e.convert("vec2|vec3");return nn(kT(e),OT(e.add(Yi(19,73)))).mul(t).add(r)},mx_ramplr:(e,t,r=$u())=>i_(e,t,r,"x"),mx_ramptb:(e,t,r=$u())=>i_(e,t,r,"y"),mx_rgbtohsv:t_,mx_safepower:(e,t=1)=>(e=ji(e)).abs().pow(t).mul(e.sign()),mx_splitlr:(e,t,r,s=$u())=>n_(e,t,r,s,"x"),mx_splittb:(e,t,r,s=$u())=>n_(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:r_,mx_transform_uv:(e=1,t=0,r=$u())=>r.mul(e).add(t),mx_worley_noise_float:(e=$u(),t=1)=>QT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec2:(e=$u(),t=1)=>ZT(e.convert("vec2|vec3"),t,qi(1)),mx_worley_noise_vec3:(e=$u(),t=1)=>JT(e.convert("vec2|vec3"),t,qi(1)),negate:oo,neutralToneMapping:Ib,nodeArray:Di,nodeImmutable:Ui,nodeObject:Fi,nodeObjects:Ii,nodeProxy:Vi,normalFlat:Kl,normalGeometry:ql,normalLocal:Xl,normalMap:Zd,normalView:Zl,normalViewGeometry:Yl,normalWorld:Jl,normalWorldGeometry:Ql,normalize:Ya,not:Ta,notEqual:pa,numWorkgroups:sx,objectDirection:yl,objectGroup:Yn,objectPosition:xl,objectRadius:vl,objectScale:Tl,objectViewPosition:_l,objectWorldMatrix:bl,oneMinus:uo,or:xa,orthographicDepthToViewZ:(e,t,r)=>t.sub(r).mul(e).sub(t),oscSawtooth:(e=ly)=>e.fract(),oscSine:(e=ly)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=ly)=>e.fract().round(),oscTriangle:(e=ly)=>e.add(.5).fract().mul(2).sub(1).abs(),output:In,outputStruct:Qf,overlay:(...e)=>(console.warn('THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),np(e)),overloadingFn:uy,parabola:ry,parallaxDirection:Kd,parallaxUV:(e,t)=>e.sub(Kd.mul(t)),parameter:(e,t)=>Fi(new Wf(e,t)),pass:(e,t,r)=>Fi(new Sb(Sb.COLOR,e,t,r)),passTexture:(e,t)=>Fi(new vb(e,t)),pcurve:(e,t,r)=>Ao(da(Ao(e,t),oa(Ao(e,t),Ao(ua(1,e),r))),1/t),perspectiveDepthToViewZ:$h,pmremTexture:wm,pointShadow:lT,pointUV:Ky,pointWidth:Un,positionGeometry:Dl,positionLocal:Vl,positionPrevious:Ul,positionView:Gl,positionViewDirection:zl,positionWorld:Ol,positionWorldDirection:kl,posterize:Tb,pow:Ao,pow2:Ro,pow3:Co,pow4:Mo,premultiplyAlpha:op,property:mn,radians:ka,rand:ko,range:ex,rangeFog:function(e,t,r){return console.warn('THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),Yb(e,Xb(t,r))},rangeFogFactor:Xb,reciprocal:po,reference:_d,referenceBuffer:vd,reflect:vo,reflectVector:pd,reflectView:cd,reflector:e=>Fi(new Ly(e)),refract:Vo,refractVector:gd,refractView:hd,reinhardToneMapping:Ab,remap:Lu,remapClamp:Fu,renderGroup:Kn,renderOutput:Ou,rendererReference:yu,rotate:Wm,rotateUV:hy,roughness:xn,round:ho,rtt:Gy,sRGBTransferEOTF:uu,sRGBTransferOETF:lu,sample:e=>Fi(new Wy(e)),sampler:e=>(!0===e.isNode?e:Zu(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:Zu(e)).convert("samplerComparison"),saturate:Do,saturation:gb,screen:(...e)=>(console.warn('THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.'),ip(e)),screenCoordinate:Rh,screenSize:Ah,screenUV:wh,scriptable:jb,scriptableValue:Gb,select:Xo,setCurrentStack:Gi,shaderStages:zs,shadow:Jx,shadowPositionWorld:Ax,shapeCircle:mT,sharedUniformGroup:qn,sheen:Nn,sheenRoughness:Sn,shiftLeft:wa,shiftRight:Aa,shininess:Fn,sign:no,sin:Za,sinc:(e,t)=>Za(Da.mul(t.mul(e).sub(1))).div(Da.mul(t.mul(e).sub(1))),skinning:lh,smoothstep:Uo,smoothstepElement:zo,specularColor:Bn,specularF90:Ln,spherizeUV:py,split:(e,t)=>Fi(new Zs(Fi(e),t)),spritesheetUV:yy,sqrt:ja,stack:qf,step:_o,stepElement:Ho,storage:ah,storageBarrier:()=>ux("storage").toStack(),storageObject:(e,t,r)=>(console.warn('THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),ah(e,t,r).setPBO(!0)),storageTexture:sb,string:(e="")=>Fi(new si(e,"string")),struct:(e,t=null)=>{const r=new Xf(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;eux("texture").toStack(),textureBicubic:Tg,textureBicubicLevel:xg,textureCubeUV:Qg,textureLoad:Ju,textureSize:ju,textureStore:(e,t,r)=>{const s=sb(e,t,r);return null!==r&&s.toStack(),s},thickness:Gn,time:ly,timerDelta:(e=1)=>(console.warn('TSL: timerDelta() is deprecated. Use "deltaTime" instead.'),dy.mul(e)),timerGlobal:(e=1)=>(console.warn('TSL: timerGlobal() is deprecated. Use "time" instead.'),ly.mul(e)),timerLocal:(e=1)=>(console.warn('TSL: timerLocal() is deprecated. Use "time" instead.'),ly.mul(e)),toneMapping:xu,toneMappingExposure:Tu,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>Fi(new Eb(t,r,Fi(s),Fi(i),Fi(n))),transformDirection:Po,transformNormal:td,transformNormalToView:rd,transformedClearcoatNormalView:nd,transformedNormalView:sd,transformedNormalWorld:id,transmission:kn,transpose:fo,triNoise3D:ny,triplanarTexture:(...e)=>by(...e),triplanarTextures:by,trunc:go,uint:Xi,uniform:Zn,uniformArray:il,uniformCubeTexture:(e=md)=>yd(e),uniformGroup:jn,uniformTexture:(e=Ku)=>Zu(e),unpremultiplyAlpha:up,userData:(e,t,r)=>Fi(new ob(e,t,r)),uv:$u,uvec2:Zi,uvec3:rn,uvec4:on,varying:au,varyingProperty:fn,vec2:Yi,vec3:en,vec4:nn,vectorComponents:Hs,velocity:hb,vertexColor:tp,vertexIndex:Wc,vertexStage:ou,vibrance:mb,viewZToLogarithmicDepth:Wh,viewZToOrthographicDepth:zh,viewZToPerspectiveDepth:Hh,viewport:Ch,viewportCoordinate:Ph,viewportDepthTexture:kh,viewportLinearDepth:Kh,viewportMipTexture:Vh,viewportResolution:Lh,viewportSafeUV:my,viewportSharedTexture:fp,viewportSize:Mh,viewportTexture:Dh,viewportUV:Bh,wgsl:(e,t)=>Vb(e,t,"wgsl"),wgslFn:(e,t)=>Ob(e,t,"wgsl"),workgroupArray:(e,t)=>Fi(new dx("Workgroup",e,t)),workgroupBarrier:()=>ux("workgroup").toStack(),workgroupId:ix,workingToColorSpace:hu,xor:_a});const l_=new $f;class d_ extends cf{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(l_),l_.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(l_),l_.a=1,n=!0;else if(!0===i.isNode){const o=this.get(e),u=i;l_.copy(s._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=Yo(nn(u).mul(eb),{getUV:()=>tb.mul(Ql),getTextureLevel:()=>Jy});let h=Hc;h=h.setZ(h.w);const p=new lp;function g(){i.removeEventListener("dispose",g),l.material.dispose(),l.geometry.dispose()}p.name="Background.material",p.side=S,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=h,p.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new X(new Oe(1,32,32),p),l.frustumCulled=!1,l.name="Background.mesh",l.onBeforeRender=function(e,t,r){this.matrixWorld.copyPosition(r.matrixWorld)},i.addEventListener("dispose",g)}const d=u.getCacheKey();o.backgroundCacheKey!==d&&(o.backgroundMeshNode.node=nn(u).mul(eb),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=d),t.unshift(l,l.geometry,l.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?l_.set(0,0,0,1):"alpha-blend"===a&&l_.set(0,0,0,0),!0===s.autoClear||!0===n){const m=r.clearColorValue;m.r=l_.r,m.g=l_.g,m.b=l_.b,m.a=l_.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),r.depthClearValue=s._clearDepth,r.stencilClearValue=s._clearStencil,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 c_=0;class h_{constructor(e="",t=[],r=0,s=[]){this.name=e,this.bindings=t,this.index=r,this.bindingsReference=s,this.id=c_++}}class p_{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 h_(t.name,[],t.index,t);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class g_{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class m_{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class f_{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class y_ extends f_{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class b_{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let x_=0;class T_{constructor(e=null){this.id=x_++,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 __{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class v_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class N_ extends v_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class S_ extends v_{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class E_ extends v_{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class w_ extends v_{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class A_ extends v_{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class R_ extends v_{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class C_ extends v_{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class M_ extends v_{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class P_ extends N_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class B_ extends S_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class L_ extends E_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class F_ extends w_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class I_ extends A_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class D_ extends R_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class V_ extends C_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class U_ extends M_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const O_=new WeakMap,k_=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),G_=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class z_{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.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=qf(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new T_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=O_.get(this.renderer);return void 0===e&&(e=new af,O_.set(this.renderer,e)),e}createRenderTarget(e,t,r){return new ue(e,t,r)}createCubeRenderTarget(e,t){return new Np(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=this.getBindGroupsCache(),s=[];let i,n=!0;for(const e of t)s.push(e),n=n&&!0!==e.groupNode.shared;return n?(i=r.get(s),void 0===i&&(i=new h_(e,s,this.bindingsIndexes[e].group,s),r.set(s,i))):i=new h_(e,s,this.bindingsIndexes[e].group,s),i}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 zs)for(const s in r[e]){const i=r[e][s];(t[s]||(t[s]=[])).push(...i)}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")}( ${G_(n.r)}, ${G_(n.g)}, ${G_(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 g_(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===_)return"int";if(t===T)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=Es(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return k_.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 ze||!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")}addStack(){return this.stack=qf(this.stack),this.stacks.push(zi()||this.stack),Gi(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Gi(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);let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new g_("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}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 e=this.structs.index++;null===r&&(r="StructType"+e),n=new __(r,t),this.structs[s].push(n),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 m_(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,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=this.getArrayCount(e);o=new f_(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 y_(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,console.warn(`THREE.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 b_("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 Ub,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 Wf(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,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 T_,this.stack=qf();for(const r of Gs)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(){console.warn("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(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e){let t="";const r=this.vars[e];if(void 0!==r)for(const e of r)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("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(){console.warn("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}build(){const{object:e,material:t,renderer:r}=this;if(null!==t){let e=r.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new lp),e.build(this)}else this.addFlow("compute",e);for(const e of Gs){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of zs){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}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new P_(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new B_(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new L_(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new F_(e);if("color"===t)return new I_(e);if("mat2"===t)return new D_(e);if("mat3"===t)return new V_(e);if("mat4"===t)return new U_(e);throw new Error(`Uniform "${t}" not declared.`)}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${He} - Node System\n`}*[Symbol.iterator](){}}class H_{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(r,this.renderId)}else t===Vs.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===Vs.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.frameId&&!1!==e.update(this)&&t.set(r,this.frameId)}else if(t===Vs.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.renderId&&!1!==e.update(this)&&t.set(r,this.renderId)}else t===Vs.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 $_{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}$_.isNodeFunctionInput=!0;class W_ extends dT{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:_x(this.light),lightColor:e}}}const j_=new a,q_=new a;let X_=null;class K_ extends dT{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Zn(new r).setGroup(Kn),this.halfWidth=Zn(new r).setGroup(Kn),this.updateType=Vs.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;q_.identity(),j_.copy(t.matrixWorld),j_.premultiply(r),q_.extractRotation(j_),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(q_),this.halfHeight.value.applyMatrix4(q_)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=Zu(X_.LTC_FLOAT_1),r=Zu(X_.LTC_FLOAT_2)):(t=Zu(X_.LTC_HALF_1),r=Zu(X_.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:Tx(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){X_=e}}class Y_ extends dT{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Zn(0).setGroup(Kn),this.penumbraCosNode=Zn(0).setGroup(Kn),this.cutoffDistanceNode=Zn(0).setGroup(Kn),this.decayExponentNode=Zn(0).setGroup(Kn),this.colorNode=Zn(this.color).setGroup(Kn)}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 Uo(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=yx(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(_x(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=cT({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=Zu(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 Q_ extends Y_{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=Zu(r,Yi(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}const Z_=ki((([e,t])=>{const r=e.abs().sub(t);return ao(To(r,0)).add(xo(To(r.x,r.y),0))}));class J_ extends Y_{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=this.penumbraCosNode,r=this.getLightCoord(e),s=r.xyz.div(r.w),i=Z_(s.xy.sub(Yi(.5)),Yi(.5)),n=da(-1,ua(1,ro(t)).sub(1));return Do(i.mul(-2).mul(n))}}class ev extends dT{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class tv extends dT{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=bx(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Zn(new e).setGroup(Kn)}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=Jl.dot(s).mul(.5).add(.5),n=Fo(r,t,i);e.context.irradiance.addAssign(n)}}class rv extends dT{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=il(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=o_(Jl,this.lightProbe);e.context.irradiance.addAssign(t)}}class sv{parseFunction(){console.warn("Abstract function.")}}class iv{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){console.warn("Abstract function.")}}iv.isNodeFunction=!0;const nv=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,av=/[a-z_0-9]+/gi,ov="#pragma main";class uv extends iv{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(ov),r=-1!==t?e.slice(t+12):e,s=r.match(nv);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=av.exec(i));)n.push(a);const o=[];let u=0;for(;u0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,(()=>{if(!0===r.isCubeTexture||r.mapping===Z||r.mapping===J||r.mapping===he){if(e.backgroundBlurriness>0||r.mapping===he)return wm(r);{let e;return e=!0===r.isCubeTexture?bd(r):Zu(r),Rp(e)}}if(!0===r.isTexture)return Zu(r,wh.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&console.error("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=_d("color","color",r).setGroup(Kn),t=_d("density","float",r).setGroup(Kn);return Yb(e,Kb(t))}if(r.isFog){const e=_d("color","color",r).setGroup(Kn),t=_d("near","float",r).setGroup(Kn),s=_d("far","float",r).setGroup(Kn);return Yb(e,Xb(t,s))}console.error("THREE.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?bd(r):!0===r.isTexture?Zu(r):void console.error("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}hasOutputChange(e){return dv.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,r=this.getOutputCacheKey(),s=e.isArrayTexture?ab(e,en(wh,nl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Zu(e,wh).renderOutput(t.toneMapping,t.currentColorSpace);return dv.set(e,r),s}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 H_,this.nodeBuilderCache=new Map,this.cacheLib={}}}const gv=new Me;class mv{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;i0,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 Nv(i.framebufferWidth,i.framebufferHeight,{format:de,type:Ce,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),n.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,i.layers.mask=n.layers.mask|a.layers.mask;const o=e.parent,u=i.cameras;Av(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 Pv(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 Bv(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(e,t,this._renderTarget),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(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 pv(this,r),this._animation=new nf(this._nodes,this.info),this._attributes=new yf(r),this._background=new d_(this,this._nodes),this._geometries=new Tf(this._attributes,this.info),this._textures=new Hf(this,r,this.info),this._pipelines=new Af(r,this._nodes),this._bindings=new Rf(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new df(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Ff(this.lighting),this._bundles=new bv,this._renderContexts=new Gf,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}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._compilationPromises,u=!0===e.isScene?e:Lv;null===r&&(r=e);const l=this._renderTarget,d=this._renderContexts.get(r,t,l),c=this._activeMipmapLevel,h=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,s.renderId++,s.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new mv),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,d.clippingContext),r!==e&&r.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);d.textures=e.textures,d.depthTexture=e.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(u,p,d);const g=p.opaque,m=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,y),!0===this.transparent&&m.length>0&&this._renderTransparents(m,f,t,u,y),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=Fl,this.overrideNodes.modelNormalViewMatrix=Il):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===Fl&&this.overrideNodes.modelNormalViewMatrix===Il}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i),u=this.backend.get(o);void 0===u.renderContexts&&(u.renderContexts=new Set);const l=s.version!==u.version,d=!1===u.renderContexts.has(a)||l;if(u.renderContexts.add(a),d){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>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=T,p.viewport=!1===p.viewportValue.equals(Iv),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Iv),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new mv),p.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const _=t.isArrayCamera?Vv:Dv;t.isArrayCamera||(Uv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_.setFromProjectionMatrix(Uv,g));const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,p.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=h,p.depth=h.depthBuffer,p.stencil=h.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=d,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._background.update(u,v,p),p.camera=t,this.backend.beginRender(p);const{bundles:N,lightsNode:S,transparentDoublePass:E,transparent:w,opaque:A}=v;return N.length>0&&this._renderBundles(N,u,S),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,S),!0===this.transparent&&w.length>0&&this._renderTransparents(w,E,t,u,S),this.backend.finishRender(p),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==s&&(this.setRenderTarget(l,d,c),this._renderOutput(h)),u.onAfterRender(this,e,t,h),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,r);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.getForClear(s),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,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){!1===this._initialized&&await this.init(),this.clear(e,t,r)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:p}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:le}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,r=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const s=this.backend,i=this._pipelines,n=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(const t of o){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),n.delete(t),a.delete(t)};t.addEventListener("dispose",e);const r=t.onInitFunction;null!==r&&r.call(t,{renderer:this})}a.updateForCompute(t),n.updateForCompute(t);const r=n.getForCompute(t),o=i.getForCompute(t,r);s.compute(e,t,r,o)}s.finishCompute(e),t.renderId=r}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=Ov.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Ov.copy(t).floor()}else t=Ov.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)}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)}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?Vv:Dv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&Ov.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Uv);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,Ov.z,null,i)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?Vv:Dv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Ov.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(Uv)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=S;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=je;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=E}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(c=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(d=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(l=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&i.side===E&&!1===i.forceSinglePass?(i.side=S,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=je,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=E):this._handleObjectFunction(e,i,t,r,a,n,o,u),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==d&&(t.overrideMaterial.colorNode=d),e.onAfterRender(this,t,r,s,i,n)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n;const l=this._nodes.needsRefresh(u);if(l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u)}_createObjectPipeline(e,t,r,s,i,n,a,o){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)}get compile(){return this.compileAsync}}class Gv{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class zv extends Gv{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(ff-e%ff)%ff;var e}get buffer(){return this._buffer}update(){return!0}}class Hv extends zv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let $v=0;class Wv extends Hv{constructor(e,t){super("UniformBuffer_"+$v++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class jv extends Hv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r0?s:"";t=`${e.name} {\n\t${r} ${i.name}[${n}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,n=!0}const a=i.node.precision;if(null!==a&&(t=tN[a]+" "+t),n){t="\t"+t;const e=i.groupNode.name;(s[e]||(s[e]=[])).push(t)}else t="uniform "+t,r.push(t)}let i="";for(const t in s){const r=s[t];i+=this._getGLSLUniformStruct(e+"_"+t,r.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==_){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+=`${sN[s.interpolationType]||s.interpolationType} ${iN[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+=`${sN[e.interpolationType]||e.interpolationType} ${iN[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`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,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=rN[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)}rN[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];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r}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 Qv(i.name,i.node,s),u.push(a);else if("cubeTexture"===t)a=new Zv(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new Jv(i.name,i.node,s),u.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new Wv(e,s);t.name=e.name,u.push(t),a=t}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let n=e[o];void 0===n&&(n=new Xv(r+"_"+o,s),e[o]=n,u.push(n)),a=this.getNodeUniform(i,t),n.addUniform(a)}n.uniformGPU=a}return i}}let oN=null,uN=null;class lN{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void pt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void pt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return oN=oN||new t,this.renderer.getDrawingBufferSize(oN)}setScissorTest(){}getClearColor(){const e=this.renderer;return uN=uN||new $f,e.getClearColor(uN),uN.getRGB(uN),uN}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${He} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let dN,cN,hN=0;class pN{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 gN{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(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===_,id:hN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new pN(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;e1?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 yN,bN,xN,TN=!1;class _N{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===TN&&(this._init(),TN=!0)}_init(){const e=this.gl;yN={[Nr]:e.REPEAT,[vr]:e.CLAMP_TO_EDGE,[_r]:e.MIRRORED_REPEAT},bN={[v]:e.NEAREST,[Sr]:e.NEAREST_MIPMAP_NEAREST,[Ge]:e.NEAREST_MIPMAP_LINEAR,[Y]:e.LINEAR,[ke]:e.LINEAR_MIPMAP_NEAREST,[V]:e.LINEAR_MIPMAP_LINEAR},xN={[Pr]:e.NEVER,[Mr]:e.ALWAYS,[De]:e.LESS,[Cr]:e.LEQUAL,[Rr]:e.EQUAL,[Ar]:e.GEQUAL,[wr]:e.GREATER,[Er]: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=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(r===n.FLOAT&&(o=n.R32F),r===n.HALF_FLOAT&&(o=n.R16F),r===n.UNSIGNED_BYTE&&(o=n.R8),r===n.UNSIGNED_SHORT&&(o=n.R16),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.R8UI),r===n.UNSIGNED_SHORT&&(o=n.R16UI),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RG&&(r===n.FLOAT&&(o=n.RG32F),r===n.HALF_FLOAT&&(o=n.RG16F),r===n.UNSIGNED_BYTE&&(o=n.RG8),r===n.UNSIGNED_SHORT&&(o=n.RG16),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RG8UI),r===n.UNSIGNED_SHORT&&(o=n.RG16UI),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RGB){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGB32F),r===n.HALF_FLOAT&&(o=n.RGB16F),r===n.UNSIGNED_BYTE&&(o=n.RGB8),r===n.UNSIGNED_SHORT&&(o=n.RGB16),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8:n.RGB8),r===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),r===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5)}if(t===n.RGB_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGB8UI),r===n.UNSIGNED_SHORT&&(o=n.RGB16UI),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=i?Br:c.getTransfer(s);r===n.FLOAT&&(o=n.RGBA32F),r===n.HALF_FLOAT&&(o=n.RGBA16F),r===n.UNSIGNED_BYTE&&(o=n.RGBA8),r===n.UNSIGNED_SHORT&&(o=n.RGBA16),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8_ALPHA8:n.RGBA8),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),r===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(r===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),r===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),r===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&r===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,n=c.getPrimaries(c.workingColorSpace),a=t.colorSpace===b?null:c.getPrimaries(t.colorSpace),o=t.colorSpace===b||n===a?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),r.texParameteri(e,r.TEXTURE_WRAP_S,yN[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,yN[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,yN[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,bN[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,l=t.minFilter===Y&&u?V:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,bN[l]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,xN[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===v)return;if(t.minFilter!==Ge&&t.minFilter!==V)return;if(t.type===I&&!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.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,isDefault:!0})}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.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,{textureGPU:i,glTextureType:n,glFormat:a,glType:o}=s.get(t),{width:u,height:l}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(n,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(n,0,0,0,u,l,a,o,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,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();o.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),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}}function vN(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 NN{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 SN{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const EN={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class wN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const 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){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,r]of this.queryStates)if("ended"===r){const r=this.queries[t];e.push(this.resolveQuery(r))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let 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){console.error("Error checking query:",e),t(this.lastValue)}};n()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}const CN=new t;class MN extends lN{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.samples>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 NN(this),this.capabilities=new SN(this),this.attributeUtils=new gN(this),this.textureUtils=new _N(this),this.bufferRenderer=new wN(this),this.state=new mN(this),this.utils=new fN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return l}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,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&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new RN(this.gl,t,2048));const r=this.timestampQueryPool[t];null!==r.allocateQueriesForContext(e)&&r.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize(CN);t.viewport(0,0,e,r)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}this.initTimestampQuery(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;e0&&!1===this._useMultisampledExtension(o)){const i=s.framebuffers[e.getCacheKey()];let n=t.COLOR_BUFFER_BIT;o.resolveDepthBuffer&&(o.depthBuffer&&(n|=t.DEPTH_BUFFER_BIT),o.stencilBuffer&&o.resolveStencilBuffer&&(n|=t.STENCIL_BUFFER_BIT));const a=s.msaaFrameBuffer,u=s.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,a),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),d)for(let e=0;e{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(pt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):pt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?b.renderInstances(_,x,T):b.render(_,x)};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()}));t.push(i)}else 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");console.error("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&&console.warn("THREE.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})}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;eEN[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=Vf(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;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,0)}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&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const PN="point-list",BN="line-list",LN="line-strip",FN="triangle-list",IN="triangle-strip",DN="never",VN="less",UN="equal",ON="less-equal",kN="greater",GN="not-equal",zN="greater-equal",HN="always",$N="store",WN="load",jN="clear",qN="ccw",XN="none",KN="front",YN="back",QN="uint16",ZN="uint32",JN="r8unorm",eS="r8snorm",tS="r8uint",rS="r8sint",sS="r16uint",iS="r16sint",nS="r16float",aS="rg8unorm",oS="rg8snorm",uS="rg8uint",lS="rg8sint",dS="r32uint",cS="r32sint",hS="r32float",pS="rg16uint",gS="rg16sint",mS="rg16float",fS="rgba8unorm",yS="rgba8unorm-srgb",bS="rgba8snorm",xS="rgba8uint",TS="rgba8sint",_S="bgra8unorm",vS="bgra8unorm-srgb",NS="rgb9e5ufloat",SS="rgb10a2unorm",ES="rgb10a2unorm",wS="rg32uint",AS="rg32sint",RS="rg32float",CS="rgba16uint",MS="rgba16sint",PS="rgba16float",BS="rgba32uint",LS="rgba32sint",FS="rgba32float",IS="depth16unorm",DS="depth24plus",VS="depth24plus-stencil8",US="depth32float",OS="depth32float-stencil8",kS="bc1-rgba-unorm",GS="bc1-rgba-unorm-srgb",zS="bc2-rgba-unorm",HS="bc2-rgba-unorm-srgb",$S="bc3-rgba-unorm",WS="bc3-rgba-unorm-srgb",jS="bc4-r-unorm",qS="bc4-r-snorm",XS="bc5-rg-unorm",KS="bc5-rg-snorm",YS="bc6h-rgb-ufloat",QS="bc6h-rgb-float",ZS="bc7-rgba-unorm",JS="bc7-rgba-srgb",eE="etc2-rgb8unorm",tE="etc2-rgb8unorm-srgb",rE="etc2-rgb8a1unorm",sE="etc2-rgb8a1unorm-srgb",iE="etc2-rgba8unorm",nE="etc2-rgba8unorm-srgb",aE="eac-r11unorm",oE="eac-r11snorm",uE="eac-rg11unorm",lE="eac-rg11snorm",dE="astc-4x4-unorm",cE="astc-4x4-unorm-srgb",hE="astc-5x4-unorm",pE="astc-5x4-unorm-srgb",gE="astc-5x5-unorm",mE="astc-5x5-unorm-srgb",fE="astc-6x5-unorm",yE="astc-6x5-unorm-srgb",bE="astc-6x6-unorm",xE="astc-6x6-unorm-srgb",TE="astc-8x5-unorm",_E="astc-8x5-unorm-srgb",vE="astc-8x6-unorm",NE="astc-8x6-unorm-srgb",SE="astc-8x8-unorm",EE="astc-8x8-unorm-srgb",wE="astc-10x5-unorm",AE="astc-10x5-unorm-srgb",RE="astc-10x6-unorm",CE="astc-10x6-unorm-srgb",ME="astc-10x8-unorm",PE="astc-10x8-unorm-srgb",BE="astc-10x10-unorm",LE="astc-10x10-unorm-srgb",FE="astc-12x10-unorm",IE="astc-12x10-unorm-srgb",DE="astc-12x12-unorm",VE="astc-12x12-unorm-srgb",UE="clamp-to-edge",OE="repeat",kE="mirror-repeat",GE="linear",zE="nearest",HE="zero",$E="one",WE="src",jE="one-minus-src",qE="src-alpha",XE="one-minus-src-alpha",KE="dst",YE="one-minus-dst",QE="dst-alpha",ZE="one-minus-dst-alpha",JE="src-alpha-saturated",ew="constant",tw="one-minus-constant",rw="add",sw="subtract",iw="reverse-subtract",nw="min",aw="max",ow=0,uw=15,lw="keep",dw="zero",cw="replace",hw="invert",pw="increment-clamp",gw="decrement-clamp",mw="increment-wrap",fw="decrement-wrap",yw="storage",bw="read-only-storage",xw="write-only",Tw="read-only",_w="read-write",vw="non-filtering",Nw="comparison",Sw="float",Ew="unfilterable-float",ww="depth",Aw="sint",Rw="uint",Cw="2d",Mw="3d",Pw="2d",Bw="2d-array",Lw="cube",Fw="3d",Iw="all",Dw="vertex",Vw="instance",Uw={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class Ow extends Gv{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class kw extends Ow{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){this.texture=this.textureNode.value}}class Gw extends zv{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let zw=0;class Hw extends Gw{constructor(e,t){super("StorageBuffer_"+zw++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Os.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class $w extends cf{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:GE}),this.flipYSampler=e.createSampler({minFilter:zE}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:IN,stripIndexFormat:ZN},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:IN,stripIndexFormat:ZN},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.getTransferPipeline(s),o=this.getFlipYPipeline(s),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:Pw,baseArrayLayer:r}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:Pw,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,r)=>{const s=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:r,loadOp:jN,storeOp:$N,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(a,l,d),h(o,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,r=0){const s=this.get(e);void 0===s.useCount&&(s.useCount=0,s.layers=[]);const i=s.layers[r]||this._mipmapCreateBundles(e,t,r),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,i),this.device.queue.submit([n.finish()]),0!==s.useCount&&(s.layers[r]=i),s.useCount++}_mipmapCreateBundles(e,t,r){const s=this.getTransferPipeline(t.format),i=s.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:Pw,baseArrayLayer:r});const a=[];for(let o=1;o1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,Yw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,Qw={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 Zw extends iv{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(Kw);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=Yw.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 Jw extends sv{parseFunction(e){return new Zw(e)}}const eA="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},tA={[Os.READ_ONLY]:"read",[Os.WRITE_ONLY]:"write",[Os.READ_WRITE]:"read_write"},rA={[Nr]:"repeat",[vr]:"clamp",[_r]:"mirror"},sA={vertex:eA?eA.VERTEX:1,fragment:eA?eA.FRAGMENT:2,compute:eA?eA.COMPUTE:4},iA={instance:!0,swizzleAssign:!1,storageBuffer:!0},nA={"^^":"tsl_xor"},aA={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"},oA={},uA={tsl_xor:new Db("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Db("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Db("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Db("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Db("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Db("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Db("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Db("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 Db("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 Db("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Db("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 Db("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Db("\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")},lA={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"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(uA.pow_float=new Db("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),uA.pow_vec2=new Db("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[uA.pow_float]),uA.pow_vec3=new Db("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[uA.pow_float]),uA.pow_vec4=new Db("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[uA.pow_float]),lA.pow_float="tsl_pow_float",lA.pow_vec2="tsl_pow_vec2",lA.pow_vec3="tsl_pow_vec3",lA.pow_vec4="tsl_pow_vec4");let dA="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(dA+="diagnostic( off, derivative_uniformity );\n");class cA extends z_{constructor(e,t){super(e,t,new Jw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==b}_generateTextureSample(e,t,r,s,i=this.shaderStage){return"fragment"===i?s?`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this._generateTextureSampleLevel(e,t,r,"0",s)}_generateVideoSample(e,t,r=this.shaderStage){if("fragment"===r)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${r} shader.`)}_generateTextureSampleLevel(e,t,r,s,i){return!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,s):this.generateTextureLod(e,t,r,i,s)}generateWrapFunction(e){const t=`tsl_coord_${rA[e.wrapS]}S_${rA[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let r=oA[t];if(void 0===r){const s=[],i=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===Nr?(s.push(uA.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===vr?(s.push(uA.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===_r?(s.push(uA.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",oA[t]=r=new Db(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.globalCache);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.isData3DTexture?"vec3":"vec2",n=u||e.isVideoTexture||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new Zo(new Iu(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(s.arrayLayerCount=new Zo(new Iu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new Zo(new Iu("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${r} ), ${this.generateTextureDimension(e,t,s)}, u32( ${s} ) )`}generateTextureLod(e,t,r,s,i="0u"){const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i),o=e.isData3DTexture?"vec3":"vec2",u=`${o}( ${n}( ${r} ) * ${o}( ${a} ) )`;return this.generateTextureLoad(e,t,u,s,i)}generateTextureLoad(e,t,r,s,i="0u"){let n;return!0===e.isVideoTexture?n=`textureLoad( ${t}, ${r} )`:s?n=`textureLoad( ${t}, ${r}, ${s}, u32( ${i} ) )`:(n=`textureLoad( ${t}, ${r}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(n+=".x")),n}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}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===I||!1===this.isSampleCompare(e)&&e.minFilter===v&&e.magFilter===v||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,r,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,"0",i):this._generateTextureSample(e,t,r,s,i),n}generateTextureGrad(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return!0===e.isDepthTexture&&!0===e.isArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,r,s,i,n=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,r,n):this._generateTextureSampleLevel(e,t,r,s,i),a}generateTextureBias(e,t,r,s,i,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===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=nA[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Os.READ_ONLY:e.access}getStorageAccess(e,t){return tA[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||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);if("texture"===t||"storageTexture"===t?s=new Qv(i.name,i.node,o,n):"cubeTexture"===t?s=new Zv(i.name,i.node,o,n):"texture3D"===t&&(s=new Jv(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.setVisibility(sA[r]),!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new kw(`${i.name}_sampler`,i.node,o);e.setVisibility(sA[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?Wv:Hw)(e,o);n.setVisibility(sA[r]),l.push(n),a=n,i.name=s||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let s=e[u];void 0===s&&(s=new Xv(u,o),s.setVisibility(sA[r]),e[u]=s,l.push(s)),a=this.getNodeUniform(i,t),s.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){let s=`var ${t} : `;return s+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),s}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];for(let i=0;ir.value.itemSize;return s&&!i}getUniforms(e){const t=this.uniforms[e],r=[],s=[],i=[],n={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let s;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture)s="texture_cube";else if(!0===t.isDepthTexture)s=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)s="texture_2d_array";else if(!0===t.isVideoTexture)s="texture_external";else if(!0===t.isData3DTexture)s="texture_3d";else if(!0===i.node.isStorageTextureNode){s=`texture_storage_2d<${Xw(t)}, ${this.getStorageAccess(i.node,e)}>`}else{s=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${s};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,r=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===i.type?", "+n:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${u}> ${i.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${o} >`;s.push(this._getWGSLStructBinding(i.name,e,u,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in n){const t=n[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=r.join("\n");return a+=s.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${u}\n`),s+=`${i.code}\n\t`,e===n&&"compute"!==t)if(s+="// result\n\n\t","vertex"===t)s+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)r.returnType=a.getNodeType(this),r.structs+="var output : "+r.returnType+";",s+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar output : OutputStruct;",s+=`output.color = ${i.result};\n\n\treturn output;`}}r.flow=s}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getType(e){return aA[e]||e}isAvailable(e){let t=iA[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),iA[e]=t),t}_getWGSLMethod(e){return void 0!==uA[e]&&this._include(e),lA[e]}_include(e){const t=uA[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${dA}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class hA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=VS:e.depth&&(t=DS),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.samples}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}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?PN:e.isLineSegments||e.isMesh&&!0===t.wireframe?BN:e.isLine?LN:e.isMesh?FN:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ce)return _S;if(e===ce)return PS;throw new Error("Unsupported outputType")}}const pA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),gA=new Map([[ze,["float16"]]]),mA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class fA{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;e1&&(s.multisampled=!0,r.texture.isDepthTexture||(s.sampleType=Ew)),r.texture.isDepthTexture)t.compatibilityMode&&null===r.texture.compareFunction?s.sampleType=Ew:s.sampleType=ww;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const e=r.texture.type;e===_?s.sampleType=Aw:e===T?s.sampleType=Rw:e===I&&(this.backend.hasFeature("float32-filterable")?s.sampleType=Sw:s.sampleType=Ew)}r.isSampledCubeTexture?s.viewDimension=Lw:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?s.viewDimension=Bw:r.isSampledTexture3D&&(s.viewDimension=Fw),e.texture=s}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);s.push(e)}return r.createBindGroupLayout({entries:s})}createBindings(e,t,r,s=0){const{backend:i,bindGroupLayoutCache:n}=this,a=i.get(e);let o,u=n.get(e.bindingsReference);void 0===u&&(u=this.createBindingsLayout(e),n.set(e.bindingsReference,u)),r>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[r]===s&&(o=a.groups[r])),void 0===o&&(o=this.createBindGroup(e,u),r>0&&(a.groups[r]=o,a.versions[r]=s)),a.group=o,a.layout=u}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer;r.queue.writeBuffer(i,0,s,0)}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],n=r.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:s});r.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);if(void 0===e.buffer){const r=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=s.createBuffer({label:"bindingBuffer_"+t.name,size:r,usage:i});e.buffer=n}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t);if(void 0===e.buffer){const s=t.attribute;e.buffer=r.get(s).buffer}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}else if(t.isSampledTexture){const e=r.get(t.texture);let a;if(void 0!==e.externalTexture)a=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount,s=`view-${e.texture.width}-${e.texture.height}-${r}`;if(a=e[s],void 0===a){const i=Iw;let n;n=t.isSampledCubeTexture?Lw:t.isSampledTexture3D?Fw:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Bw:Pw,a=e[s]=e.texture.createView({aspect:i,dimension:n,mipLevelCount:r})}}n.push({binding:i,resource:a})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class bA{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:o}=n,u=this.backend,l=u.device,d=u.utils,c=u.get(n),h=[];for(const t of e.getBindings()){const e=u.get(t);h.push(e.layout)}const p=u.attributeUtils.createShaderVertexBuffers(e);let g;s.blending===H||s.blending===k&&!1===s.transparent||(g=this._getBlending(s));let m={};!0===s.stencilWrite&&(m={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const f=this._getColorWriteMask(s),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:l.createPipelineLayout({bindGroupLayouts:h})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=v,E.depthWriteEnabled=s.depthWrite,E.depthCompare=_),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),S.depthStencil=E),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[s.getCurrentColorFormat(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);a.push(t.layout)}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===qe){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:rw},r={srcFactor:i,dstFactor:n,operation:rw}};if(e.premultipliedAlpha)switch(s){case k:i($E,XE,$E,XE);break;case Bt:i($E,$E,$E,$E);break;case Pt:i(HE,jE,HE,$E);break;case Mt:i(KE,XE,HE,$E)}else switch(s){case k:i(qE,XE,$E,XE);break;case Bt:i(qE,$E,$E,$E);break;case Pt:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mt:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};console.error("THREE.WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Ke:t=HE;break;case wt:t=$E;break;case Et:t=WE;break;case Tt:t=jE;break;case St:t=qE;break;case xt:t=XE;break;case vt:t=KE;break;case bt:t=YE;break;case _t:t=QE;break;case yt:t=ZE;break;case Nt:t=JE;break;case 211:t=ew;break;case 212:t=tw;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case kr:t=DN;break;case Or:t=HN;break;case Ur:t=VN;break;case Vr:t=ON;break;case Dr:t=UN;break;case Ir:t=zN;break;case Fr:t=kN;break;case Lr:t=GN;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case Xr:t=lw;break;case qr:t=dw;break;case jr:t=cw;break;case Wr:t=hw;break;case $r:t=pw;break;case Hr:t=gw;break;case zr:t=mw;break;case Gr:t=fw;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Xe:t=rw;break;case ft:t=sw;break;case mt:t=iw;break;case Yr:t=nw;break;case Kr:t=aw;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;switch(s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?QN:ZN),r.side){case je:s.frontFace=qN,s.cullMode=YN;break;case S:s.frontFace=qN,s.cullMode=KN;break;case E:s.frontFace=qN,s.cullMode=XN;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",r.side)}return s}_getColorWriteMask(e){return!0===e.colorWrite?uw:ow}_getDepthCompare(e){let t;if(!1===e.depthTest)t=HN;else{const r=e.depthFunc;switch(r){case kt:t=DN;break;case Ot:t=HN;break;case Ut:t=VN;break;case Vt:t=ON;break;case Dt:t=UN;break;case It:t=zN;break;case Ft:t=kN;break;case Lt:t=GN;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class xA extends AN{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 pt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,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));let a=0;for(const[,t]of e){const e=n[t],r=n[t+1];a+=Number(r-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class TA extends lN{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new hA(this),this.attributeUtils=new fA(this),this.bindingUtils=new yA(this),this.pipelineUtils=new bA(this),this.textureUtils=new qw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},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(Uw),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;r.lost.then((t=>{const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}));const s=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=r,this.context=s;const i=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(Uw.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i}),this.updateSize()}get coordinateSystem(){return d}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const r=e.colorAttachments[0];this.renderer.samples>0?r.view=this.colorBuffer.createView():r.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;if(void 0===i||s.width!==r.width||s.height!==r.height||s.dimensions!==r.dimensions||s.activeMipmapLevel!==e.activeMipmapLevel||s.activeCubeFace!==e.activeCubeFace||s.samples!==r.samples){i={},s.descriptors=i;const e=()=>{r.removeEventListener("dispose",e),this.delete(r)};!1===r.hasEventListener("dispose",e)&&r.addEventListener("dispose",e)}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:WN}),this.initTimestampQuery(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;ea?(u.x=Math.min(t.dispatchCount,a),u.y=Math.ceil(t.dispatchCount/a)):u.x=t.dispatchCount,i.dispatchWorkgroups(u.x,u.y,u.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:r,material:s,context:i,pipeline:n}=e,a=e.getBindings(),o=this.get(i),u=this.get(n).pipeline,l=e.getIndex(),d=null!==l,c=e.getDrawParameters();if(null===c)return;const h=(t,r)=>{this.pipelineUtils.setPipeline(t,u),r.pipeline=u;const n=r.bindingGroups;for(let e=0,r=a.length;e{if(h(s,i),!0===r.isBatchedMesh){const e=r._multiDrawStarts,i=r._multiDrawCounts,n=r._multiDrawCount,a=r._multiDrawInstances;null!==a&&pt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o1?0:o;!0===d?s.drawIndexed(i[o],n,e[o]/l.array.BYTES_PER_ELEMENT,0,u):s.draw(i[o],n,e[o],u),t.update(r,i[o],n)}}else if(!0===d){const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndexedIndirect(e,0)}else s.drawIndexed(i,n,a,0,0);t.update(r,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndirect(e,0)}else s.draw(i,n,a,0);t.update(r,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),s=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==s.length){const e=this.get(n),r=[],i=new Uint32Array([0,0,0,0]);for(let t=0,n=s.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new MN(e)));super(new t(e),e),this.library=new NA,this.isWebGPURenderer=!0}}class EA extends ds{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class wA{constructor(e,t=nn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new lp;r.name="PostProcessing",this._quadMesh=new Uy(r)}render(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}dispose(){this._quadMesh.material.dispose()}_update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;this._quadMesh.material.fragmentNode=!0===this.outputColorTransform?Ou(this.outputNode,t,r):this.outputNode.context({toneMapping:t,outputColorSpace:r}),this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this._update();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=le;const s=e.xr.enabled;e.xr.enabled=!1,await this._quadMesh.renderAsync(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r}}class AA extends x{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Y,this.minFilter=Y,this.isStorageTexture=!0}}class RA extends qy{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class CA extends cs{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new hs(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):console.error(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]?(console.error("THREE.NodeLoader: Node type not found:",e),ji()):Fi(new this.nodes[e])}}class MA extends ps{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 PA extends gs{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 CA;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 MA;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t