diff --git a/build/three-webgpu.js b/build/three-webgpu.js index 9d5e8d9..21122a6 100644 --- a/build/three-webgpu.js +++ b/build/three-webgpu.js @@ -11,7 +11,7 @@ var THREE = (async function (exports) { * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ - const REVISION = '161dev'; + const REVISION = '162'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; @@ -70,6 +70,7 @@ var THREE = (async function (exports) { const ACESFilmicToneMapping = 4; const CustomToneMapping = 5; const AgXToneMapping = 6; + const NeutralToneMapping = 7; const AttachedBindMode = 'attached'; const DetachedBindMode = 'detached'; @@ -161,10 +162,6 @@ var THREE = (async function (exports) { const TrianglesDrawMode = 0; const TriangleStripDrawMode = 1; const TriangleFanDrawMode = 2; - /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */ - const LinearEncoding = 3000; - /** @deprecated Use SRGBColorSpace in three.js r152+. */ - const sRGBEncoding = 3001; const BasicDepthPacking = 3200; const RGBADepthPacking = 3201; const TangentSpaceNormalMap = 0; @@ -1846,6 +1843,7 @@ var THREE = (async function (exports) { this.uuid = generateUUID(); this.data = data; + this.dataReady = true; this.version = 0; @@ -2003,17 +2001,7 @@ var THREE = (async function (exports) { this.flipY = true; this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - if ( typeof colorSpace === 'string' ) { - - this.colorSpace = colorSpace; - - } else { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - + this.colorSpace = colorSpace; this.userData = {}; @@ -2252,20 +2240,6 @@ var THREE = (async function (exports) { } - get encoding() { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - - set encoding( encoding ) { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - } Texture.DEFAULT_IMAGE = null; @@ -2939,14 +2913,6 @@ var THREE = (async function (exports) { const image = { width: width, height: height, depth: 1 }; - if ( options.encoding !== undefined ) { - - // @deprecated, r152 - warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' ); - options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - options = Object.assign( { generateMipmaps: false, internalFormat: null, @@ -2954,15 +2920,25 @@ var THREE = (async function (exports) { depthBuffer: true, stencilBuffer: false, depthTexture: null, - samples: 0 + samples: 0, + count: 1 }, options ); - this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); - this.texture.isRenderTargetTexture = true; + const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); + + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + + this.textures = []; - this.texture.flipY = false; - this.texture.generateMipmaps = options.generateMipmaps; - this.texture.internalFormat = options.internalFormat; + const count = options.count; + for ( let i = 0; i < count; i ++ ) { + + this.textures[ i ] = texture.clone(); + this.textures[ i ].isRenderTargetTexture = true; + + } this.depthBuffer = options.depthBuffer; this.stencilBuffer = options.stencilBuffer; @@ -2973,6 +2949,18 @@ var THREE = (async function (exports) { } + get texture() { + + return this.textures[ 0 ]; + + } + + set texture( value ) { + + this.textures[ 0 ] = value; + + } + setSize( width, height, depth = 1 ) { if ( this.width !== width || this.height !== height || this.depth !== depth ) { @@ -2981,9 +2969,13 @@ var THREE = (async function (exports) { this.height = height; this.depth = depth; - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = depth; + for ( let i = 0, il = this.textures.length; i < il; i ++ ) { + + this.textures[ i ].image.width = width; + this.textures[ i ].image.height = height; + this.textures[ i ].image.depth = depth; + + } this.dispose(); @@ -3011,8 +3003,14 @@ var THREE = (async function (exports) { this.viewport.copy( source.viewport ); - this.texture = source.texture.clone(); - this.texture.isRenderTargetTexture = true; + this.textures.length = 0; + + for ( let i = 0, il = source.textures.length; i < il; i ++ ) { + + this.textures[ i ] = source.textures[ i ].clone(); + this.textures[ i ].isRenderTargetTexture = true; + + } // ensure image object is not shared, see #20328 @@ -3140,85 +3138,6 @@ var THREE = (async function (exports) { } - class WebGLMultipleRenderTargets extends WebGLRenderTarget { - - constructor( width = 1, height = 1, count = 1, options = {} ) { - - super( width, height, options ); - - this.isWebGLMultipleRenderTargets = true; - - const texture = this.texture; - - this.texture = []; - - for ( let i = 0; i < count; i ++ ) { - - this.texture[ i ] = texture.clone(); - this.texture[ i ].isRenderTargetTexture = true; - - } - - } - - setSize( width, height, depth = 1 ) { - - if ( this.width !== width || this.height !== height || this.depth !== depth ) { - - this.width = width; - this.height = height; - this.depth = depth; - - for ( let i = 0, il = this.texture.length; i < il; i ++ ) { - - this.texture[ i ].image.width = width; - this.texture[ i ].image.height = height; - this.texture[ i ].image.depth = depth; - - } - - this.dispose(); - - } - - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); - - } - - copy( source ) { - - this.dispose(); - - this.width = source.width; - this.height = source.height; - this.depth = source.depth; - - this.scissor.copy( source.scissor ); - this.scissorTest = source.scissorTest; - - this.viewport.copy( source.viewport ); - - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - - if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - - this.texture.length = 0; - - for ( let i = 0, il = source.texture.length; i < il; i ++ ) { - - this.texture[ i ] = source.texture[ i ].clone(); - this.texture[ i ].isRenderTargetTexture = true; - - } - - return this; - - } - - } - class Quaternion { constructor( x = 0, y = 0, z = 0, w = 1 ) { @@ -3810,23 +3729,24 @@ var THREE = (async function (exports) { random() { - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. + // sets this quaternion to a uniform random unit quaternnion - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt( 1 - u1 ); - const sqrtu1 = Math.sqrt( u1 ); + // Ken Shoemake + // Uniform random rotations + // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992. - const u2 = 2 * Math.PI * Math.random(); + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); - const u3 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt( 1 - x0 ); + const r2 = Math.sqrt( x0 ); return this.set( - sqrt1u1 * Math.cos( u2 ), - sqrtu1 * Math.sin( u3 ), - sqrtu1 * Math.cos( u3 ), - sqrt1u1 * Math.sin( u2 ), + r1 * Math.sin( theta1 ), + r1 * Math.cos( theta1 ), + r2 * Math.sin( theta2 ), + r2 * Math.cos( theta2 ), ); } @@ -4594,15 +4514,15 @@ var THREE = (async function (exports) { randomDirection() { - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + // https://mathworld.wolfram.com/SpherePointPicking.html - const u = ( Math.random() - 0.5 ) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt( 1 - u ** 2 ); + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt( 1 - u * u ); - this.x = f * Math.cos( t ); - this.y = f * Math.sin( t ); - this.z = u; + this.x = c * Math.cos( theta ); + this.y = u; + this.z = c * Math.sin( theta ); return this; @@ -6628,25 +6548,25 @@ var THREE = (async function (exports) { position.z = te[ 14 ]; // scale the rotation part - _m1$2.copy( this ); + _m1$4.copy( this ); const invSX = 1 / sx; const invSY = 1 / sy; const invSZ = 1 / sz; - _m1$2.elements[ 0 ] *= invSX; - _m1$2.elements[ 1 ] *= invSX; - _m1$2.elements[ 2 ] *= invSX; + _m1$4.elements[ 0 ] *= invSX; + _m1$4.elements[ 1 ] *= invSX; + _m1$4.elements[ 2 ] *= invSX; - _m1$2.elements[ 4 ] *= invSY; - _m1$2.elements[ 5 ] *= invSY; - _m1$2.elements[ 6 ] *= invSY; + _m1$4.elements[ 4 ] *= invSY; + _m1$4.elements[ 5 ] *= invSY; + _m1$4.elements[ 6 ] *= invSY; - _m1$2.elements[ 8 ] *= invSZ; - _m1$2.elements[ 9 ] *= invSZ; - _m1$2.elements[ 10 ] *= invSZ; + _m1$4.elements[ 8 ] *= invSZ; + _m1$4.elements[ 9 ] *= invSZ; + _m1$4.elements[ 10 ] *= invSZ; - quaternion.setFromRotationMatrix( _m1$2 ); + quaternion.setFromRotationMatrix( _m1$4 ); scale.x = sx; scale.y = sy; @@ -6787,14 +6707,14 @@ var THREE = (async function (exports) { } const _v1$5 = /*@__PURE__*/ new Vector3(); - const _m1$2 = /*@__PURE__*/ new Matrix4(); + const _m1$4 = /*@__PURE__*/ new Matrix4(); const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); const _x = /*@__PURE__*/ new Vector3(); const _y = /*@__PURE__*/ new Vector3(); const _z = /*@__PURE__*/ new Vector3(); - const _matrix$1 = /*@__PURE__*/ new Matrix4(); + const _matrix$2 = /*@__PURE__*/ new Matrix4(); const _quaternion$3 = /*@__PURE__*/ new Quaternion(); class Euler { @@ -7029,9 +6949,9 @@ var THREE = (async function (exports) { setFromQuaternion( q, order, update ) { - _matrix$1.makeRotationFromQuaternion( q ); + _matrix$2.makeRotationFromQuaternion( q ); - return this.setFromRotationMatrix( _matrix$1, order, update ); + return this.setFromRotationMatrix( _matrix$2, order, update ); } @@ -7166,8 +7086,8 @@ var THREE = (async function (exports) { const _v1$4 = /*@__PURE__*/ new Vector3(); const _q1 = /*@__PURE__*/ new Quaternion(); - const _m1$1 = /*@__PURE__*/ new Matrix4(); - const _target = /*@__PURE__*/ new Vector3(); + const _m1$3 = /*@__PURE__*/ new Matrix4(); + const _target$1 = /*@__PURE__*/ new Vector3(); const _position$3 = /*@__PURE__*/ new Vector3(); const _scale$2 = /*@__PURE__*/ new Vector3(); @@ -7180,6 +7100,9 @@ var THREE = (async function (exports) { const _addedEvent = { type: 'added' }; const _removedEvent = { type: 'removed' }; + const _childaddedEvent = { type: 'childadded', child: null }; + const _childremovedEvent = { type: 'childremoved', child: null }; + class Object3D extends EventDispatcher { constructor() { @@ -7416,7 +7339,7 @@ var THREE = (async function (exports) { this.updateWorldMatrix( true, false ); - return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() ); } @@ -7426,11 +7349,11 @@ var THREE = (async function (exports) { if ( x.isVector3 ) { - _target.copy( x ); + _target$1.copy( x ); } else { - _target.set( x, y, z ); + _target$1.set( x, y, z ); } @@ -7442,20 +7365,20 @@ var THREE = (async function (exports) { if ( this.isCamera || this.isLight ) { - _m1$1.lookAt( _position$3, _target, this.up ); + _m1$3.lookAt( _position$3, _target$1, this.up ); } else { - _m1$1.lookAt( _target, _position$3, this.up ); + _m1$3.lookAt( _target$1, _position$3, this.up ); } - this.quaternion.setFromRotationMatrix( _m1$1 ); + this.quaternion.setFromRotationMatrix( _m1$3 ); if ( parent ) { - _m1$1.extractRotation( parent.matrixWorld ); - _q1.setFromRotationMatrix( _m1$1 ); + _m1$3.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$3 ); this.quaternion.premultiply( _q1.invert() ); } @@ -7496,6 +7419,10 @@ var THREE = (async function (exports) { object.dispatchEvent( _addedEvent ); + _childaddedEvent.child = object; + this.dispatchEvent( _childaddedEvent ); + _childaddedEvent.child = null; + } else { console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); @@ -7529,6 +7456,10 @@ var THREE = (async function (exports) { object.dispatchEvent( _removedEvent ); + _childremovedEvent.child = object; + this.dispatchEvent( _childremovedEvent ); + _childremovedEvent.child = null; + } return this; @@ -7563,17 +7494,17 @@ var THREE = (async function (exports) { this.updateWorldMatrix( true, false ); - _m1$1.copy( this.matrixWorld ).invert(); + _m1$3.copy( this.matrixWorld ).invert(); if ( object.parent !== null ) { object.parent.updateWorldMatrix( true, false ); - _m1$1.multiply( object.parent.matrixWorld ); + _m1$3.multiply( object.parent.matrixWorld ); } - object.applyMatrix4( _m1$1 ); + object.applyMatrix4( _m1$3 ); this.add( object ); @@ -8163,7 +8094,7 @@ var THREE = (async function (exports) { const _v0$1 = /*@__PURE__*/ new Vector3(); const _v1$3 = /*@__PURE__*/ new Vector3(); const _v2$2 = /*@__PURE__*/ new Vector3(); - const _v3$1 = /*@__PURE__*/ new Vector3(); + const _v3$2 = /*@__PURE__*/ new Vector3(); const _vab = /*@__PURE__*/ new Vector3(); const _vac = /*@__PURE__*/ new Vector3(); @@ -8235,19 +8166,19 @@ var THREE = (async function (exports) { static containsPoint( point, a, b, c ) { // if the triangle is degenerate then we can't contain a point - if ( this.getBarycoord( point, a, b, c, _v3$1 ) === null ) { + if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) { return false; } - return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); + return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 ); } static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) { - if ( this.getBarycoord( point, p1, p2, p3, _v3$1 ) === null ) { + if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) { target.x = 0; target.y = 0; @@ -8258,9 +8189,9 @@ var THREE = (async function (exports) { } target.setScalar( 0 ); - target.addScaledVector( v1, _v3$1.x ); - target.addScaledVector( v2, _v3$1.y ); - target.addScaledVector( v3, _v3$1.z ); + target.addScaledVector( v1, _v3$2.x ); + target.addScaledVector( v2, _v3$2.y ); + target.addScaledVector( v3, _v3$2.z ); return target; @@ -9273,7 +9204,7 @@ var THREE = (async function (exports) { if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); - if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; @@ -9383,6 +9314,7 @@ var THREE = (async function (exports) { } + if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray(); if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; @@ -9627,6 +9559,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -9661,6 +9594,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -9888,7 +9822,7 @@ var THREE = (async function (exports) { get updateRange() { - console.warn( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 + warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 return this._updateRange; } @@ -10465,19 +10399,9 @@ var THREE = (async function (exports) { } - class Float64BufferAttribute extends BufferAttribute { - - constructor( array, itemSize, normalized ) { - - super( new Float64Array( array ), itemSize, normalized ); - - } - - } - - let _id$2 = 0; + let _id$2$1 = 0; - const _m1 = /*@__PURE__*/ new Matrix4(); + const _m1$2 = /*@__PURE__*/ new Matrix4(); const _obj = /*@__PURE__*/ new Object3D(); const _offset = /*@__PURE__*/ new Vector3(); const _box$2 = /*@__PURE__*/ new Box3(); @@ -10492,7 +10416,7 @@ var THREE = (async function (exports) { this.isBufferGeometry = true; - Object.defineProperty( this, 'id', { value: _id$2 ++ } ); + Object.defineProperty( this, 'id', { value: _id$2$1 ++ } ); this.uuid = generateUUID(); @@ -10643,9 +10567,9 @@ var THREE = (async function (exports) { applyQuaternion( q ) { - _m1.makeRotationFromQuaternion( q ); + _m1$2.makeRotationFromQuaternion( q ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10655,9 +10579,9 @@ var THREE = (async function (exports) { // rotate geometry around world x-axis - _m1.makeRotationX( angle ); + _m1$2.makeRotationX( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10667,9 +10591,9 @@ var THREE = (async function (exports) { // rotate geometry around world y-axis - _m1.makeRotationY( angle ); + _m1$2.makeRotationY( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10679,9 +10603,9 @@ var THREE = (async function (exports) { // rotate geometry around world z-axis - _m1.makeRotationZ( angle ); + _m1$2.makeRotationZ( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10691,9 +10615,9 @@ var THREE = (async function (exports) { // translate geometry - _m1.makeTranslation( x, y, z ); + _m1$2.makeTranslation( x, y, z ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10703,9 +10627,9 @@ var THREE = (async function (exports) { // scale geometry - _m1.makeScale( x, y, z ); + _m1$2.makeScale( x, y, z ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10765,7 +10689,7 @@ var THREE = (async function (exports) { if ( position && position.isGLBufferAttribute ) { - console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this ); this.boundingBox.set( new Vector3( - Infinity, - Infinity, - Infinity ), @@ -10835,7 +10759,7 @@ var THREE = (async function (exports) { if ( position && position.isGLBufferAttribute ) { - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this ); this.boundingSphere.set( new Vector3(), Infinity ); @@ -10952,24 +10876,21 @@ var THREE = (async function (exports) { } - const indices = index.array; - const positions = attributes.position.array; - const normals = attributes.normal.array; - const uvs = attributes.uv.array; - - const nVertices = positions.length / 3; + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; if ( this.hasAttribute( 'tangent' ) === false ) { - this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) ); } - const tangents = this.getAttribute( 'tangent' ).array; + const tangentAttribute = this.getAttribute( 'tangent' ); const tan1 = [], tan2 = []; - for ( let i = 0; i < nVertices; i ++ ) { + for ( let i = 0; i < positionAttribute.count; i ++ ) { tan1[ i ] = new Vector3(); tan2[ i ] = new Vector3(); @@ -10989,13 +10910,13 @@ var THREE = (async function (exports) { function handleTriangle( a, b, c ) { - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + vA.fromBufferAttribute( positionAttribute, a ); + vB.fromBufferAttribute( positionAttribute, b ); + vC.fromBufferAttribute( positionAttribute, c ); - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + uvA.fromBufferAttribute( uvAttribute, a ); + uvB.fromBufferAttribute( uvAttribute, b ); + uvC.fromBufferAttribute( uvAttribute, c ); vB.sub( vA ); vC.sub( vA ); @@ -11028,7 +10949,7 @@ var THREE = (async function (exports) { groups = [ { start: 0, - count: indices.length + count: index.count } ]; } @@ -11043,9 +10964,9 @@ var THREE = (async function (exports) { for ( let j = start, jl = start + count; j < jl; j += 3 ) { handleTriangle( - indices[ j + 0 ], - indices[ j + 1 ], - indices[ j + 2 ] + index.getX( j + 0 ), + index.getX( j + 1 ), + index.getX( j + 2 ) ); } @@ -11057,7 +10978,7 @@ var THREE = (async function (exports) { function handleVertex( v ) { - n.fromArray( normals, v * 3 ); + n.fromBufferAttribute( normalAttribute, v ); n2.copy( n ); const t = tan1[ v ]; @@ -11073,10 +10994,7 @@ var THREE = (async function (exports) { const test = tmp2.dot( tan2[ v ] ); const w = ( test < 0.0 ) ? - 1.0 : 1.0; - tangents[ v * 4 ] = tmp.x; - tangents[ v * 4 + 1 ] = tmp.y; - tangents[ v * 4 + 2 ] = tmp.z; - tangents[ v * 4 + 3 ] = w; + tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w ); } @@ -11089,9 +11007,9 @@ var THREE = (async function (exports) { for ( let j = start, jl = start + count; j < jl; j += 3 ) { - handleVertex( indices[ j + 0 ] ); - handleVertex( indices[ j + 1 ] ); - handleVertex( indices[ j + 2 ] ); + handleVertex( index.getX( j + 0 ) ); + handleVertex( index.getX( j + 1 ) ); + handleVertex( index.getX( j + 2 ) ); } @@ -11920,7 +11838,6 @@ var THREE = (async function (exports) { _uvC$1.fromBufferAttribute( uv1, c ); intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); - intersection.uv2 = intersection.uv1; // @deprecated, r152 } @@ -12271,7 +12188,8 @@ var THREE = (async function (exports) { fragDepth: false, // set to use fragment depth values drawBuffers: false, // set to use draw buffers shaderTextureLOD: false, // set to use shader texture LOD - clipCullDistance: false // set to use vertex shader clipping + clipCullDistance: false, // set to use vertex shader clipping + multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID }; // When rendered geometry doesn't include these attributes but the material does, @@ -12483,6 +12401,11 @@ var THREE = (async function (exports) { } + const _v3$1 = /*@__PURE__*/ new Vector3(); + const _minTarget = /*@__PURE__*/ new Vector2(); + const _maxTarget = /*@__PURE__*/ new Vector2(); + + class PerspectiveCamera extends Camera { constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { @@ -12581,6 +12504,34 @@ var THREE = (async function (exports) { } + /** + * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. + * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle. + */ + getViewBounds( distance, minTarget, maxTarget ) { + + _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + } + + /** + * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. + * Copies the result into the target Vector2, where x is width and y is height. + */ + getViewSize( distance, target ) { + + this.getViewBounds( distance, _minTarget, _maxTarget ); + + return target.subVectors( _maxTarget, _minTarget ); + + } + /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. @@ -12920,14 +12871,6 @@ var THREE = (async function (exports) { const image = { width: size, height: size, depth: 1 }; const images = [ image, image, image, image, image, image ]; - if ( options.encoding !== undefined ) { - - // @deprecated, r152 - warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' ); - options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) @@ -13573,7 +13516,7 @@ var THREE = (async function (exports) { function updateBuffer( buffer, attribute, bufferType ) { const array = attribute.array; - const updateRange = attribute._updateRange; // deprecated + const updateRange = attribute._updateRange; // @deprecated, r159 const updateRanges = attribute.updateRanges; gl.bindBuffer( bufferType, buffer ); @@ -13608,7 +13551,7 @@ var THREE = (async function (exports) { } - // deprecated + // @deprecated, r159 if ( updateRange.count !== - 1 ) { if ( isWebGL2 ) { @@ -13814,7 +13757,7 @@ var THREE = (async function (exports) { var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; - var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif"; var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; @@ -13836,7 +13779,7 @@ var THREE = (async function (exports) { var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; - var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif"; var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; @@ -13870,9 +13813,9 @@ var THREE = (async function (exports) { var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\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}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}"; - var 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, 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"; + var 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"; - var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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"; + var 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"; var 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"; @@ -13900,7 +13843,7 @@ var THREE = (async function (exports) { var 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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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"; - var 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, 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, 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"; + var 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"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; @@ -13940,11 +13883,13 @@ var THREE = (async function (exports) { var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + var 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"; + var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\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"; var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; - var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; @@ -14006,7 +13951,7 @@ var THREE = (async function (exports) { var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; - var 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 OptimizedCineonToneMapping( 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 CustomToneMapping( vec3 color ) { return color; }"; + var 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 OptimizedCineonToneMapping( 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\tfloat startCompression = 0.8 - 0.04;\n\tfloat 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(1, 1, 1), g);\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; var 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.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"; @@ -14026,67 +13971,67 @@ var THREE = (async function (exports) { const vertex$g = "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}"; - const fragment$g = "#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;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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}"; + const fragment$g = "#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}"; const vertex$f = "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}"; const fragment$f = "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}"; - const vertex$e = "#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#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}"; + const vertex$e = "#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}"; - const fragment$e = "#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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#endif\n}"; + const fragment$e = "#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#endif\n}"; - const vertex$d = "#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#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}"; + const vertex$d = "#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}"; - const fragment$d = "#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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}"; + const fragment$d = "#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}"; const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; const fragment$c = "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}"; - const vertex$b = "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}"; + const vertex$b = "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}"; - const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$b = "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}"; - const vertex$a = "#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#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}"; + const vertex$a = "#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}"; - const fragment$a = "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\t#include \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\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}"; + const fragment$a = "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}"; - const vertex$9 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + const vertex$9 = "#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}"; - const fragment$9 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$9 = "#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}"; - const vertex$8 = "#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\tvViewPosition = - mvPosition.xyz;\n}"; + const vertex$8 = "#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}"; - const fragment$8 = "#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\t#include \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\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}"; + const fragment$8 = "#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}"; - const vertex$7 = "#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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + const vertex$7 = "#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}"; - const fragment$7 = "#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\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + const fragment$7 = "#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}"; - const vertex$6 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + const vertex$6 = "#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}"; - const fragment$6 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$6 = "#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}"; - const vertex$5 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + const vertex$5 = "#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}"; - const fragment$5 = "#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_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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$5 = "#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_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}"; - const vertex$4 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + const vertex$4 = "#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}"; - const fragment$4 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$4 = "#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}"; - const vertex$3 = "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\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}"; + const vertex$3 = "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}"; - const fragment$3 = "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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$3 = "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}"; - const vertex$2 = "#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}"; + const vertex$2 = "#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}"; const fragment$2 = "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}"; const vertex$1 = "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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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}"; - const fragment$1 = "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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$1 = "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}"; const ShaderChunk = { alphahash_fragment: alphahash_fragment, @@ -14156,6 +14101,7 @@ var THREE = (async function (exports) { map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphinstance_vertex: morphinstance_vertex, morphcolor_vertex: morphcolor_vertex, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, @@ -14264,6 +14210,7 @@ var THREE = (async function (exports) { envmap: { envMap: { value: null }, + envMapRotation: { value: /*@__PURE__*/ new Matrix3() }, flipEnvMap: { value: - 1 }, reflectivity: { value: 1.0 }, // basic, lambert, phong ior: { value: 1.5 }, // physical @@ -14684,7 +14631,8 @@ var THREE = (async function (exports) { envMap: { value: null }, flipEnvMap: { value: - 1 }, backgroundBlurriness: { value: 0 }, - backgroundIntensity: { value: 1 } + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /*@__PURE__*/ new Matrix3() } }, vertexShader: ShaderChunk.backgroundCube_vert, @@ -14808,6 +14756,8 @@ var THREE = (async function (exports) { }; const _rgb = { r: 0, b: 0, g: 0 }; + const _e1$1 = /*@__PURE__*/ new Euler(); + const _m1$1 = /*@__PURE__*/ new Matrix4(); function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { @@ -14904,10 +14854,24 @@ var THREE = (async function (exports) { } + _e1$1.copy( scene.backgroundRotation ); + + // accommodate left-handed frame + _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1; + + if ( background.isCubeTexture && background.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1$1.y *= - 1; + _e1$1.z *= - 1; + + } + boxMesh.material.uniforms.envMap.value = background; boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) ); boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; if ( currentBackground !== background || @@ -16074,7 +16038,7 @@ var THREE = (async function (exports) { if ( image && image.height > 0 ) { - const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + const renderTarget = new WebGLCubeRenderTarget( image.height ); renderTarget.fromEquirectangularTexture( renderer, texture ); cubemaps.set( texture, renderTarget ); @@ -16372,6 +16336,7 @@ var THREE = (async function (exports) { * Generates a PMREM from an equirectangular texture, which can be either LDR * or HDR. The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. + * The smallest supported equirectangular image size is 64 x 32. */ fromEquirectangular( equirectangular, renderTarget = null ) { @@ -16383,6 +16348,7 @@ var THREE = (async function (exports) { * Generates a PMREM from an cubemap texture, which can be either LDR * or HDR. The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. + * The smallest supported cube size is 16 x 16. */ fromCubemap( cubemap, renderTarget = null ) { @@ -17890,24 +17856,31 @@ var THREE = (async function (exports) { } // + if ( object.isInstancedMesh === true && object.morphTexture !== null ) { - let morphInfluencesSum = 0; + program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures ); - for ( let i = 0; i < objectInfluences.length; i ++ ) { + } else { - morphInfluencesSum += objectInfluences[ i ]; + let morphInfluencesSum = 0; - } + for ( let i = 0; i < objectInfluences.length; i ++ ) { - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); - program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + } program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); - } else { // When object doesn't have morph target influences defined, we treat it as a 0-length array @@ -19456,6 +19429,10 @@ var THREE = (async function (exports) { toneMappingName = 'AgX'; break; + case NeutralToneMapping: + toneMappingName = 'Neutral'; + break; + case CustomToneMapping: toneMappingName = 'Custom'; break; @@ -19473,7 +19450,7 @@ var THREE = (async function (exports) { function generateExtensions( parameters ) { const chunks = [ - ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.alphaToCoverage || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' @@ -19486,7 +19463,8 @@ var THREE = (async function (exports) { function generateVertexExtensions( parameters ) { const chunks = [ - parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '' + parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '', + parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '', ]; return chunks.filter( filterEmptyLine ).join( '\n' ); @@ -19878,6 +19856,7 @@ var THREE = (async function (exports) { parameters.batching ? '#define USE_BATCHING' : '', parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', @@ -20009,6 +19988,12 @@ var THREE = (async function (exports) { '#endif', + '#ifdef USE_INSTANCING_MORPH', + + ' uniform sampler2D morphTexture;', + + '#endif', + 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', @@ -20097,6 +20082,7 @@ var THREE = (async function (exports) { parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', @@ -20298,6 +20284,8 @@ var THREE = (async function (exports) { console.error( 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Material Name: ' + self.name + '\n' + + 'Material Type: ' + self.type + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors @@ -20434,7 +20422,7 @@ var THREE = (async function (exports) { } - let _id$1 = 0; + let _id$1$1 = 0; class WebGLShaderCache { @@ -20548,7 +20536,7 @@ var THREE = (async function (exports) { constructor( code ) { - this.id = _id$1 ++; + this.id = _id$1$1 ++; this.code = code; this.usedTimes = 0; @@ -20561,6 +20549,7 @@ var THREE = (async function (exports) { const _programLayers = new Layers(); const _customShaders = new WebGLShaderCache(); + const _activeChannels = new Set(); const programs = []; const IS_WEBGL2 = capabilities.isWebGL2; @@ -20589,6 +20578,8 @@ var THREE = (async function (exports) { function getChannel( value ) { + _activeChannels.add( value ); + if ( value === 0 ) return 'uv'; return `uv${ value }`; @@ -20709,10 +20700,6 @@ var THREE = (async function (exports) { const HAS_EXTENSIONS = !! material.extensions; - const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1; - const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2; - const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3; - let toneMapping = NoToneMapping; if ( material.toneMapped ) { @@ -20748,9 +20735,11 @@ var THREE = (async function (exports) { batching: IS_BATCHEDMESH, instancing: IS_INSTANCEDMESH, instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ), + alphaToCoverage: !! material.alphaToCoverage, map: HAS_MAP, matcap: HAS_MATCAP, @@ -20796,7 +20785,7 @@ var THREE = (async function (exports) { gradientMap: HAS_GRADIENTMAP, - opaque: material.transparent === false && material.blending === NormalBlending, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, alphaMap: HAS_ALPHAMAP, alphaTest: HAS_ALPHATEST, @@ -20843,9 +20832,6 @@ var THREE = (async function (exports) { vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ), vertexColors: material.vertexColors, vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, - vertexUv1s: HAS_ATTRIBUTE_UV1, - vertexUv2s: HAS_ATTRIBUTE_UV2, - vertexUv3s: HAS_ATTRIBUTE_UV3, pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ), @@ -20907,7 +20893,8 @@ var THREE = (async function (exports) { extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true, extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true, extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true, - extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ), rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ), rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ), @@ -20918,6 +20905,14 @@ var THREE = (async function (exports) { }; + // the usage of getChannel() determines the active texture channels for this shader + + parameters.vertexUv1s = _activeChannels.has( 1 ); + parameters.vertexUv2s = _activeChannels.has( 2 ); + parameters.vertexUv3s = _activeChannels.has( 3 ); + + _activeChannels.clear(); + return parameters; } @@ -21027,38 +21022,40 @@ var THREE = (async function (exports) { _programLayers.enable( 2 ); if ( parameters.instancingColor ) _programLayers.enable( 3 ); - if ( parameters.matcap ) + if ( parameters.instancingMorph ) _programLayers.enable( 4 ); - if ( parameters.envMap ) + if ( parameters.matcap ) _programLayers.enable( 5 ); - if ( parameters.normalMapObjectSpace ) + if ( parameters.envMap ) _programLayers.enable( 6 ); - if ( parameters.normalMapTangentSpace ) + if ( parameters.normalMapObjectSpace ) _programLayers.enable( 7 ); - if ( parameters.clearcoat ) + if ( parameters.normalMapTangentSpace ) _programLayers.enable( 8 ); - if ( parameters.iridescence ) + if ( parameters.clearcoat ) _programLayers.enable( 9 ); - if ( parameters.alphaTest ) + if ( parameters.iridescence ) _programLayers.enable( 10 ); - if ( parameters.vertexColors ) + if ( parameters.alphaTest ) _programLayers.enable( 11 ); - if ( parameters.vertexAlphas ) + if ( parameters.vertexColors ) _programLayers.enable( 12 ); - if ( parameters.vertexUv1s ) + if ( parameters.vertexAlphas ) _programLayers.enable( 13 ); - if ( parameters.vertexUv2s ) + if ( parameters.vertexUv1s ) _programLayers.enable( 14 ); - if ( parameters.vertexUv3s ) + if ( parameters.vertexUv2s ) _programLayers.enable( 15 ); - if ( parameters.vertexTangents ) + if ( parameters.vertexUv3s ) _programLayers.enable( 16 ); - if ( parameters.anisotropy ) + if ( parameters.vertexTangents ) _programLayers.enable( 17 ); - if ( parameters.alphaHash ) + if ( parameters.anisotropy ) _programLayers.enable( 18 ); - if ( parameters.batching ) + if ( parameters.alphaHash ) _programLayers.enable( 19 ); + if ( parameters.batching ) + _programLayers.enable( 20 ); array.push( _programLayers.mask ); _programLayers.disableAll(); @@ -21103,6 +21100,8 @@ var THREE = (async function (exports) { _programLayers.enable( 18 ); if ( parameters.decodeVideoTexture ) _programLayers.enable( 19 ); + if ( parameters.alphaToCoverage ) + _programLayers.enable( 20 ); array.push( _programLayers.mask ); @@ -23161,33 +23160,19 @@ var THREE = (async function (exports) { } - if ( renderTarget.isWebGLMultipleRenderTargets ) { + const textures = renderTarget.textures; - const textures = renderTarget.texture; - - if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - - for ( let i = 0, il = textures.length; i < il; i ++ ) { - - drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; - - } + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - drawBuffers.length = textures.length; + for ( let i = 0, il = textures.length; i < il; i ++ ) { - needsUpdate = true; + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; } - } else { - - if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - - drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0; - - needsUpdate = true; + drawBuffers.length = textures.length; - } + needsUpdate = true; } @@ -23209,10 +23194,14 @@ var THREE = (async function (exports) { gl.drawBuffers( drawBuffers ); - } else { + } else if ( extensions.has( 'WEBGL_draw_buffers' ) === true ) { extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + } else { + + throw new Error( 'THREE.WebGLState: Usage of gl.drawBuffers() require WebGL2 or WEBGL_draw_buffers extension' ); + } } @@ -23999,6 +23988,7 @@ var THREE = (async function (exports) { const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + const _imageDimensions = new Vector2(); const _videoTextures = new WeakMap(); let _canvas; @@ -24036,11 +24026,13 @@ var THREE = (async function (exports) { let scale = 1; + const dimensions = getDimensions( image ); + // handle case if texture exceeds max size - if ( image.width > maxSize || image.height > maxSize ) { + if ( dimensions.width > maxSize || dimensions.height > maxSize ) { - scale = maxSize / Math.max( image.width, image.height ); + scale = maxSize / Math.max( dimensions.width, dimensions.height ); } @@ -24052,12 +24044,13 @@ var THREE = (async function (exports) { if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) || + ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) { const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; - const width = floor( scale * image.width ); - const height = floor( scale * image.height ); + const width = floor( scale * dimensions.width ); + const height = floor( scale * dimensions.height ); if ( _canvas === undefined ) _canvas = createCanvas( width, height ); @@ -24071,7 +24064,7 @@ var THREE = (async function (exports) { const context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, width, height ); - console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' ); return canvas; @@ -24079,7 +24072,7 @@ var THREE = (async function (exports) { if ( 'data' in image ) { - console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' ); } @@ -24095,7 +24088,9 @@ var THREE = (async function (exports) { function isPowerOfTwo$1( image ) { - return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + const dimensions = getDimensions( image ); + + return isPowerOfTwo( dimensions.width ) && isPowerOfTwo( dimensions.height ); } @@ -24162,6 +24157,17 @@ var THREE = (async function (exports) { } + if ( glFormat === _gl.RG_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I; + if ( glType === _gl.INT ) internalFormat = _gl.RG32I; + + } + if ( glFormat === _gl.RGBA ) { const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace ); @@ -24309,18 +24315,7 @@ var THREE = (async function (exports) { function deallocateRenderTarget( renderTarget ) { - const texture = renderTarget.texture; - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); - - if ( textureProperties.__webglTexture !== undefined ) { - - _gl.deleteTexture( textureProperties.__webglTexture ); - - info.memory.textures --; - - } if ( renderTarget.depthTexture ) { @@ -24375,27 +24370,24 @@ var THREE = (async function (exports) { } - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - for ( let i = 0, il = texture.length; i < il; i ++ ) { - - const attachmentProperties = properties.get( texture[ i ] ); + const textures = renderTarget.textures; - if ( attachmentProperties.__webglTexture ) { + for ( let i = 0, il = textures.length; i < il; i ++ ) { - _gl.deleteTexture( attachmentProperties.__webglTexture ); + const attachmentProperties = properties.get( textures[ i ] ); - info.memory.textures --; + if ( attachmentProperties.__webglTexture ) { - } + _gl.deleteTexture( attachmentProperties.__webglTexture ); - properties.remove( texture[ i ] ); + info.memory.textures --; } + properties.remove( textures[ i ] ); + } - properties.remove( texture ); properties.remove( renderTarget ); } @@ -24615,8 +24607,6 @@ var THREE = (async function (exports) { if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 @@ -24624,6 +24614,7 @@ var THREE = (async function (exports) { if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); properties.get( texture ).__currentAnisotropy = texture.anisotropy; @@ -24757,6 +24748,7 @@ var THREE = (async function (exports) { const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format ); const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; const levels = getMipLevels( texture, image, supportsMips ); if ( texture.isDepthTexture ) { @@ -24869,7 +24861,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -24891,7 +24887,11 @@ var THREE = (async function (exports) { } - state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } } else { @@ -24921,7 +24921,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + if ( dataReady ) { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } } else { @@ -24939,7 +24943,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } } else { @@ -24969,7 +24977,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } } else { @@ -24987,7 +24999,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -25011,7 +25027,11 @@ var THREE = (async function (exports) { } - state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } } else { @@ -25029,7 +25049,11 @@ var THREE = (async function (exports) { } - state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } } else { @@ -25074,7 +25098,9 @@ var THREE = (async function (exports) { if ( useTexStorage && allocateMemory ) { - state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + const dimensions = getDimensions( mipmaps[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); } @@ -25084,7 +25110,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } } else { @@ -25102,11 +25132,17 @@ var THREE = (async function (exports) { if ( allocateMemory ) { - state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + const dimensions = getDimensions( image ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); } - state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } } else { @@ -25187,6 +25223,7 @@ var THREE = (async function (exports) { const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; let levels = getMipLevels( texture, image, supportsMips ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); @@ -25215,7 +25252,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } } else { @@ -25233,7 +25274,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -25259,7 +25304,9 @@ var THREE = (async function (exports) { if ( mipmaps.length > 0 ) levels ++; - state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + const dimensions = getDimensions( cubeImage[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height ); } @@ -25269,7 +25316,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } } else { @@ -25284,7 +25335,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } } else { @@ -25298,7 +25353,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } } else { @@ -25312,7 +25371,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } } else { @@ -25459,7 +25522,7 @@ var THREE = (async function (exports) { } else { - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; for ( let i = 0; i < textures.length; i ++ ) { @@ -25623,7 +25686,13 @@ var THREE = (async function (exports) { renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + const textures = renderTarget.textures; + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + if ( ! isMultipleRenderTargets ) { if ( textureProperties.__webglTexture === undefined ) { @@ -25636,10 +25705,6 @@ var THREE = (async function (exports) { } - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - // Setup framebuffer if ( isCube ) { @@ -25688,8 +25753,6 @@ var THREE = (async function (exports) { if ( capabilities.drawBuffers ) { - const textures = renderTarget.texture; - for ( let i = 0, il = textures.length; i < il; i ++ ) { const attachmentProperties = properties.get( textures[ i ] ); @@ -25714,8 +25777,6 @@ var THREE = (async function (exports) { if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - const textures = isMultipleRenderTargets ? texture : [ texture ]; - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); renderTargetProperties.__webglColorRenderbuffer = []; @@ -25788,8 +25849,6 @@ var THREE = (async function (exports) { } else if ( isMultipleRenderTargets ) { - const textures = renderTarget.texture; - for ( let i = 0, il = textures.length; i < il; i ++ ) { const attachment = textures[ i ]; @@ -25868,7 +25927,7 @@ var THREE = (async function (exports) { const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; for ( let i = 0, il = textures.length; i < il; i ++ ) { @@ -25893,14 +25952,14 @@ var THREE = (async function (exports) { if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; const width = renderTarget.width; const height = renderTarget.height; let mask = _gl.COLOR_BUFFER_BIT; const invalidationArray = []; const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; const renderTargetProperties = properties.get( renderTarget ); - const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); // If MRT we need to remove FBO attachments if ( isMultipleRenderTargets ) { @@ -26084,6 +26143,31 @@ var THREE = (async function (exports) { } + function getDimensions( image ) { + + if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) { + + // if intrinsic data are not available, fallback to width/height + + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + + } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) { + + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + + } else { + + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + + } + + return _imageDimensions; + + } + // this.allocateTextureUnit = allocateTextureUnit; @@ -26747,6 +26831,105 @@ var THREE = (async function (exports) { } + const _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + + const _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + + class WebXRDepthSensing { + + constructor() { + + this.texture = null; + this.mesh = null; + + this.depthNear = 0; + this.depthFar = 0; + + } + + init( renderer, depthData, renderState ) { + + if ( this.texture === null ) { + + const texture = new Texture(); + + const texProps = renderer.properties.get( texture ); + texProps.__webglTexture = depthData.texture; + + if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) { + + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + + } + + this.texture = texture; + + } + + } + + render( renderer, cameraXR ) { + + if ( this.texture !== null ) { + + if ( this.mesh === null ) { + + const viewport = cameraXR.cameras[ 0 ].viewport; + const material = new ShaderMaterial( { + extensions: { fragDepth: true }, + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + } ); + + this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material ); + + } + + renderer.render( this.mesh, cameraXR ); + + } + + } + + reset() { + + this.texture = null; + this.mesh = null; + + } + + } + class WebXRManager extends EventDispatcher { constructor( renderer, gl ) { @@ -26770,7 +26953,10 @@ var THREE = (async function (exports) { let glProjLayer = null; let glBaseLayer = null; let xrFrame = null; + + const depthSensing = new WebXRDepthSensing(); const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; let newRenderTarget = null; @@ -26900,6 +27086,8 @@ var THREE = (async function (exports) { _currentDepthNear = null; _currentDepthFar = null; + depthSensing.reset(); + // restore framebuffer/rendering state renderer.setRenderTarget( initialRenderTarget ); @@ -27258,6 +27446,13 @@ var THREE = (async function (exports) { if ( session === null ) return; + if ( depthSensing.texture !== null ) { + + camera.near = depthSensing.depthNear; + camera.far = depthSensing.depthFar; + + } + cameraXR.near = cameraR.near = cameraL.near = camera.near; cameraXR.far = cameraR.far = cameraL.far = camera.far; @@ -27273,6 +27468,15 @@ var THREE = (async function (exports) { _currentDepthNear = cameraXR.near; _currentDepthFar = cameraXR.far; + cameraL.near = _currentDepthNear; + cameraL.far = _currentDepthFar; + cameraR.near = _currentDepthNear; + cameraR.far = _currentDepthFar; + + cameraL.updateProjectionMatrix(); + cameraR.updateProjectionMatrix(); + camera.updateProjectionMatrix(); + } const parent = camera.parent; @@ -27374,6 +27578,12 @@ var THREE = (async function (exports) { }; + this.hasDepthSensing = function () { + + return depthSensing.texture !== null; + + }; + // Animation Loop let onAnimationFrameCallback = null; @@ -27466,6 +27676,22 @@ var THREE = (async function (exports) { } + // + + const enabledFeatures = session.enabledFeatures; + + if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) { + + const depthData = glBinding.getDepthInformation( views[ 0 ] ); + + if ( depthData && depthData.isValid && depthData.texture ) { + + depthSensing.init( renderer, depthData, session.renderState ); + + } + + } + } // @@ -27483,6 +27709,8 @@ var THREE = (async function (exports) { } + depthSensing.render( renderer, cameraXR ); + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); if ( frame.detectedPlanes ) { @@ -27511,6 +27739,9 @@ var THREE = (async function (exports) { } + const _e1 = /*@__PURE__*/ new Euler(); + const _m1 = /*@__PURE__*/ new Matrix4(); + function WebGLMaterials( renderer, properties ) { function refreshTransformUniform( map, uniform ) { @@ -27719,12 +27950,30 @@ var THREE = (async function (exports) { } - const envMap = properties.get( material ).envMap; + const materialProperties = properties.get( material ); + + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; if ( envMap ) { uniforms.envMap.value = envMap; + _e1.copy( envMapRotation ); + + // accommodate left-handed frame + _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1; + + if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1.y *= - 1; + _e1.z *= - 1; + + } + + uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) ); + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; uniforms.reflectivity.value = material.reflectivity; @@ -28892,7 +29141,7 @@ var THREE = (async function (exports) { } - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() ); }; @@ -28914,7 +29163,7 @@ var THREE = (async function (exports) { } - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() ); }; @@ -29610,7 +29859,11 @@ var THREE = (async function (exports) { // - background.render( currentRenderList, scene ); + if ( xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false ) { + + background.render( currentRenderList, scene ); + + } // render scene @@ -30011,6 +30264,7 @@ var THREE = (async function (exports) { materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; materialProperties.fog = scene.fog; materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation; if ( programs === undefined ) { @@ -30123,6 +30377,7 @@ var THREE = (async function (exports) { materialProperties.batching = parameters.batching; materialProperties.instancing = parameters.instancing; materialProperties.instancingColor = parameters.instancingColor; + materialProperties.instancingMorph = parameters.instancingMorph; materialProperties.skinning = parameters.skinning; materialProperties.morphTargets = parameters.morphTargets; materialProperties.morphNormals = parameters.morphNormals; @@ -30233,6 +30488,14 @@ var THREE = (async function (exports) { needsProgramChange = true; + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) { + + needsProgramChange = true; + } else if ( materialProperties.envMap !== envMap ) { needsProgramChange = true; @@ -30561,20 +30824,16 @@ var THREE = (async function (exports) { const renderTargetProperties = properties.get( renderTarget ); renderTargetProperties.__hasExternalTextures = true; - if ( renderTargetProperties.__hasExternalTextures ) { + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { - if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - // The multisample_render_to_texture extension doesn't work properly if there - // are midframe flushes and an external depth buffer. Disable use of the extension. - if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - - console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); - renderTargetProperties.__useRenderToTexture = false; - - } + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; } @@ -30834,8 +31093,8 @@ var THREE = (async function (exports) { } - const width = sourceBox.max.x - sourceBox.min.x + 1; - const height = sourceBox.max.y - sourceBox.min.y + 1; + const width = Math.round( sourceBox.max.x - sourceBox.min.x ); + const height = Math.round( sourceBox.max.y - sourceBox.min.y ); const depth = sourceBox.max.z - sourceBox.min.z + 1; const glFormat = utils.convert( dstTexture.format ); const glType = utils.convert( dstTexture.type ); @@ -30882,9 +31141,8 @@ var THREE = (async function (exports) { } else { - if ( srcTexture.isCompressedArrayTexture ) { + if ( dstTexture.isCompressedArrayTexture ) { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); } else { @@ -30973,20 +31231,6 @@ var THREE = (async function (exports) { } - get outputEncoding() { // @deprecated, r152 - - console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); - return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - - set outputEncoding( encoding ) { // @deprecated, r152 - - console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); - this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; - - } - get useLegacyLights() { // @deprecated, r155 console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' ); @@ -31090,6 +31334,8 @@ var THREE = (async function (exports) { this.backgroundBlurriness = 0; this.backgroundIntensity = 1; + this.backgroundRotation = new Euler(); + this.environmentRotation = new Euler(); this.overrideMaterial = null; @@ -31111,6 +31357,8 @@ var THREE = (async function (exports) { this.backgroundBlurriness = source.backgroundBlurriness; this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy( source.backgroundRotation ); + this.environmentRotation.copy( source.environmentRotation ); if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); @@ -31128,6 +31376,9 @@ var THREE = (async function (exports) { if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + data.object.backgroundRotation = this.backgroundRotation.toArray(); + data.object.environmentRotation = this.environmentRotation.toArray(); + return data; } @@ -31164,7 +31415,7 @@ var THREE = (async function (exports) { get updateRange() { - console.warn( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 + warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 return this._updateRange; } @@ -31379,6 +31630,26 @@ var THREE = (async function (exports) { } + getComponent( index, component ) { + + let value = this.array[ index * this.data.stride + this.offset + component ]; + + if ( this.normalized ) value = denormalize( value, this.array ); + + return value; + + } + + setComponent( index, component, value ) { + + if ( this.normalized ) value = normalize$1( value, this.array ); + + this.data.array[ index * this.data.stride + this.offset + component ] = value; + + return this; + + } + setX( index, x ) { if ( this.normalized ) x = normalize$1( x, this.array ); @@ -32651,6 +32922,7 @@ var THREE = (async function (exports) { this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); this.instanceColor = null; + this.morphTexture = null; this.count = count; @@ -32756,6 +33028,24 @@ var THREE = (async function (exports) { } + getMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const array = this.morphTexture.source.data.data; + + const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum + + const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + objectInfluences[ i ] = array[ dataIndex + i ]; + + } + + } + raycast( raycaster, intersects ) { const matrixWorld = this.matrixWorld; @@ -32826,6 +33116,38 @@ var THREE = (async function (exports) { } + setMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const len = objectInfluences.length + 1; // morphBaseInfluence + all influences + + if ( this.morphTexture === null ) { + + this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType ); + + } + + const array = this.morphTexture.source.data.data; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + const dataIndex = len * index; + + array[ dataIndex ] = morphBaseInfluence; + + array.set( objectInfluences, dataIndex + 1 ); + + } + updateMorphTargets() { } @@ -32896,7 +33218,7 @@ var THREE = (async function (exports) { } const ID_ATTR_NAME = 'batchId'; - const _matrix = /*@__PURE__*/ new Matrix4(); + const _matrix$1 = /*@__PURE__*/ new Matrix4(); const _invMatrixWorld = /*@__PURE__*/ new Matrix4(); const _identityMatrix = /*@__PURE__*/ new Matrix4(); const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4(); @@ -33119,8 +33441,8 @@ var THREE = (async function (exports) { if ( active[ i ] === false ) continue; - this.getMatrixAt( i, _matrix ); - this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix$1 ); boundingBox.union( _box$1 ); } @@ -33144,8 +33466,8 @@ var THREE = (async function (exports) { if ( active[ i ] === false ) continue; - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); boundingSphere.union( _sphere$2 ); } @@ -33735,7 +34057,7 @@ var THREE = (async function (exports) { .multiply( this.matrixWorld ); _frustum$1.setFromProjectionMatrix( _projScreenMatrix$2, - renderer.isWebGPURenderer ? WebGPUCoordinateSystem : WebGLCoordinateSystem + renderer.coordinateSystem ); } @@ -33752,8 +34074,8 @@ var THREE = (async function (exports) { if ( visibility[ i ] && active[ i ] ) { // get the bounds in world space - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); // determine whether the batched geometry is within the frustum let culled = false; @@ -33810,8 +34132,8 @@ var THREE = (async function (exports) { if ( perObjectFrustumCulled ) { // get the bounds in world space - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); culled = ! _frustum$1.intersectsSphere( _sphere$2 ); } @@ -34940,9 +35262,9 @@ var THREE = (async function (exports) { } - getPoint( t, optionalTarget ) { + getPoint( t, optionalTarget = new Vector2() ) { - const point = optionalTarget || new Vector2(); + const point = optionalTarget; const twoPi = Math.PI * 2; let deltaAngle = this.aEndAngle - this.aStartAngle; @@ -37402,7 +37724,7 @@ var THREE = (async function (exports) { const _v0 = /*@__PURE__*/ new Vector3(); const _v1$1 = /*@__PURE__*/ new Vector3(); - const _normal = /*@__PURE__*/ new Vector3(); + const _normal$2 = /*@__PURE__*/ new Vector3(); const _triangle = /*@__PURE__*/ new Triangle(); class EdgesGeometry extends BufferGeometry { @@ -37454,7 +37776,7 @@ var THREE = (async function (exports) { a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); - _triangle.getNormal( _normal ); + _triangle.getNormal( _normal$2 ); // create hashes for the edge from the vertices hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; @@ -37485,7 +37807,7 @@ var THREE = (async function (exports) { // if we found a sibling edge add it into the vertex array if // it meets the angle threshold and delete the edge from the map. - if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + if ( _normal$2.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { vertices.push( v0.x, v0.y, v0.z ); vertices.push( v1.x, v1.y, v1.z ); @@ -37501,7 +37823,7 @@ var THREE = (async function (exports) { index0: indexArr[ j ], index1: indexArr[ jNext ], - normal: _normal.clone(), + normal: _normal$2.clone(), }; @@ -37707,7 +38029,7 @@ var THREE = (async function (exports) { } - if ( last && equals( last, last.next ) ) { + if ( last && equals$1( last, last.next ) ) { removeNode( last ); last = last.next; @@ -37730,7 +38052,7 @@ var THREE = (async function (exports) { again = false; - if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { removeNode( p ); p = end = p.prev; @@ -37915,7 +38237,7 @@ var THREE = (async function (exports) { const a = p.prev, b = p.next.next; - if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { triangles.push( a.i / dim | 0 ); triangles.push( p.i / dim | 0 ); @@ -38238,7 +38560,7 @@ var THREE = (async function (exports) { return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case } @@ -38250,7 +38572,7 @@ var THREE = (async function (exports) { } // check if two points are equal - function equals( p1, p2 ) { + function equals$1( p1, p2 ) { return p1.x === p2.x && p1.y === p2.y; @@ -40599,6 +40921,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.envMapIntensity = 1.0; this.wireframe = false; @@ -40654,6 +40977,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.envMapIntensity = source.envMapIntensity; this.wireframe = source.wireframe; @@ -40931,6 +41255,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -40984,6 +41309,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -41195,6 +41521,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -41246,6 +41573,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -44088,10 +44416,6 @@ var THREE = (async function (exports) { texture.colorSpace = texData.colorSpace; - } else if ( texData.encoding !== undefined ) { // @deprecated, r152 - - texture.encoding = texData.encoding; - } if ( texData.flipY !== undefined ) { @@ -45327,6 +45651,7 @@ var THREE = (async function (exports) { if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation ); if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; @@ -46307,7 +46632,6 @@ var THREE = (async function (exports) { if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat; if ( data.type !== undefined ) texture.type = data.type; if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace; - if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152 if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); @@ -46446,6 +46770,8 @@ var THREE = (async function (exports) { if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation ); + if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation ); break; @@ -50756,7 +51082,7 @@ var THREE = (async function (exports) { } - let _id$3 = 0; + let _id$4 = 0; class UniformsGroup$1 extends EventDispatcher { @@ -50766,7 +51092,7 @@ var THREE = (async function (exports) { this.isUniformsGroup = true; - Object.defineProperty( this, 'id', { value: _id$3 ++ } ); + Object.defineProperty( this, 'id', { value: _id$4 ++ } ); this.name = ''; @@ -50954,6 +51280,8 @@ var THREE = (async function (exports) { } + const _matrix = /*@__PURE__*/ new Matrix4(); + class Raycaster { constructor( origin, direction, near = 0, far = Infinity ) { @@ -51006,9 +51334,20 @@ var THREE = (async function (exports) { } + setFromXRController( controller ) { + + _matrix.identity().extractRotation( controller.matrixWorld ); + + this.ray.origin.setFromMatrixPosition( controller.matrixWorld ); + this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix ); + + return this; + + } + intersectObject( object, recursive = true, intersects = [] ) { - intersectObject( object, this, intersects, recursive ); + intersect( object, this, intersects, recursive ); intersects.sort( ascSort ); @@ -51020,7 +51359,7 @@ var THREE = (async function (exports) { for ( let i = 0, l = objects.length; i < l; i ++ ) { - intersectObject( objects[ i ], this, intersects, recursive ); + intersect( objects[ i ], this, intersects, recursive ); } @@ -51038,7 +51377,7 @@ var THREE = (async function (exports) { } - function intersectObject( object, raycaster, intersects, recursive ) { + function intersect( object, raycaster, intersects, recursive ) { if ( object.layers.test( raycaster.layers ) ) { @@ -51052,7 +51391,7 @@ var THREE = (async function (exports) { for ( let i = 0, l = children.length; i < l; i ++ ) { - intersectObject( children[ i ], raycaster, intersects, true ); + intersect( children[ i ], raycaster, intersects, true ); } @@ -51526,7 +51865,6 @@ var THREE = (async function (exports) { this.light = light; - this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; this.color = color; @@ -51578,6 +51916,24 @@ var THREE = (async function (exports) { this.light.updateWorldMatrix( true, false ); this.light.target.updateWorldMatrix( true, false ); + // update the local matrix based on the parent and light target transforms + if ( this.parent ) { + + this.parent.updateWorldMatrix( true ); + + this.matrix + .copy( this.parent.matrixWorld ) + .invert() + .multiply( this.light.matrixWorld ); + + } else { + + this.matrix.copy( this.light.matrixWorld ); + + } + + this.matrixWorld.copy( this.light.matrixWorld ); + const coneLength = this.light.distance ? this.light.distance : 1000; const coneWidth = coneLength * Math.tan( this.light.angle ); @@ -53018,6 +53374,26 @@ var THREE = (async function (exports) { } + class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162 + + constructor( width = 1, height = 1, count = 1, options = {} ) { + + console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' ); + + super( width, height, { ...options, count } ); + + this.isWebGLMultipleRenderTargets = true; + + } + + get texture() { + + return this.textures; + + } + + } + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { @@ -53040,23 +53416,20 @@ var THREE = (async function (exports) { } - if ( window.GPUShaderStage === undefined ) { + if ( self.GPUShaderStage === undefined ) { - window.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; + self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; } - let isAvailable = false; - - if ( navigator.gpu !== undefined ) { + // statics - const adapter = await( navigator.gpu.requestAdapter()); + let isAvailable = navigator.gpu !== undefined; - if ( adapter !== null ) { - isAvailable = true; + if ( typeof window !== 'undefined' && isAvailable ) { - } + isAvailable = await( navigator.gpu.requestAdapter()); } @@ -53064,6 +53437,12 @@ var THREE = (async function (exports) { static isAvailable() { + return Boolean( isAvailable ); + + } + + static getStaticAdapter() { + return isAvailable; } @@ -53228,6 +53607,168 @@ var THREE = (async function (exports) { } + const _plane = new Plane(); + const _viewNormalMatrix = new Matrix3(); + + let _clippingContextVersion = 0; + + class ClippingContext { + + constructor() { + + this.version = ++ _clippingContextVersion; + + this.globalClippingCount = 0; + + this.localClippingCount = 0; + this.localClippingEnabled = false; + this.localClipIntersection = false; + + this.planes = []; + + this.parentVersion = 0; + + } + + projectPlanes( source, offset ) { + + const l = source.length; + const planes = this.planes; + + for ( let i = 0; i < l; i ++ ) { + + _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, _viewNormalMatrix ); + + const v = planes[ offset + i ]; + const normal = _plane.normal; + + v.x = - normal.x; + v.y = - normal.y; + v.z = - normal.z; + v.w = _plane.constant; + + } + + } + + updateGlobal( renderer, camera ) { + + const rendererClippingPlanes = renderer.clippingPlanes; + this.viewMatrix = camera.matrixWorldInverse; + + _viewNormalMatrix.getNormalMatrix( this.viewMatrix ); + + let update = false; + + if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) { + + const l = rendererClippingPlanes.length; + + if ( l !== this.globalClippingCount ) { + + const planes = []; + + for ( let i = 0; i < l; i ++ ) { + + planes.push( new Vector4() ); + + } + + this.globalClippingCount = l; + this.planes = planes; + + update = true; + + } + + this.projectPlanes( rendererClippingPlanes, 0 ); + + } else if ( this.globalClippingCount !== 0 ) { + + this.globalClippingCount = 0; + this.planes = []; + update = true; + + } + + if ( renderer.localClippingEnabled !== this.localClippingEnabled ) { + + this.localClippingEnabled = renderer.localClippingEnabled; + update = true; + + } + + if ( update ) this.version = _clippingContextVersion ++; + + } + + update( parent, material ) { + + let update = false; + + if ( this !== parent && parent.version !== this.parentVersion ) { + + this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount; + this.localClippingEnabled = parent.localClippingEnabled; + this.planes = Array.from( parent.planes ); + this.parentVersion = parent.version; + this.viewMatrix = parent.viewMatrix; + + + update = true; + + } + + if ( this.localClippingEnabled ) { + + const localClippingPlanes = material.clippingPlanes; + + if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) { + + const l = localClippingPlanes.length; + const planes = this.planes; + const offset = this.globalClippingCount; + + if ( update || l !== this.localClippingCount ) { + + planes.length = offset + l; + + for ( let i = 0; i < l; i ++ ) { + + planes[ offset + i ] = new Vector4(); + + } + + this.localClippingCount = l; + update = true; + + } + + this.projectPlanes( localClippingPlanes, offset ); + + + } else if ( this.localClippingCount !== 0 ) { + + this.localClippingCount = 0; + update = true; + + } + + if ( this.localClipIntersection !== material.clipIntersection ) { + + this.localClipIntersection = material.clipIntersection; + update = true; + + } + + } + + if ( update ) this.version = _clippingContextVersion ++; + + } + + } + let id$4 = 0; class RenderObject { @@ -53254,6 +53795,10 @@ var THREE = (async function (exports) { this.pipeline = null; this.vertexBuffers = null; + this.updateClipping( renderContext.clippingContext ); + + this.clippingContextVersion = this.clippingContext.version; + this.initialNodesCacheKey = this.getNodesCacheKey(); this.initialCacheKey = this.getCacheKey(); @@ -53274,6 +53819,41 @@ var THREE = (async function (exports) { } + updateClipping( parent ) { + + const material = this.material; + + let clippingContext = this.clippingContext; + + if ( Array.isArray( material.clippingPlanes ) ) { + + if ( clippingContext === parent || ! clippingContext ) { + + clippingContext = new ClippingContext(); + this.clippingContext = clippingContext; + + } + + clippingContext.update( parent, material ); + + } else if ( this.clippingContext !== parent ) { + + this.clippingContext = parent; + + } + + } + + clippingNeedsUpdate () { + + if ( this.clippingContext.version === this.clippingContextVersion ) return false; + + this.clippingContextVersion = this.clippingContext.version; + + return true; + + } + getNodeBuilderState() { return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) ); @@ -53361,9 +53941,11 @@ var THREE = (async function (exports) { } + cacheKey += this.clippingContextVersion + ','; + if ( object.skeleton ) { - cacheKey += object.skeleton.uuid + ','; + cacheKey += object.skeleton.bones.length + ','; } @@ -53437,7 +54019,9 @@ var THREE = (async function (exports) { } else { - if ( renderObject.version !== material.version || renderObject.needsUpdate ) { + renderObject.updateClipping( renderContext.clippingContext ); + + if ( renderObject.version !== material.version || renderObject.needsUpdate || renderObject.clippingNeedsUpdate() ) { if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) { @@ -53860,7 +54444,8 @@ var THREE = (async function (exports) { }; this.compute = { - calls: 0 + calls: 0, + computeCalls: 0 }; this.memory = { @@ -53868,6 +54453,11 @@ var THREE = (async function (exports) { textures: 0 }; + this.timestamp = { + compute: 0, + render: 0 + }; + } update( object, count, instanceCount ) { @@ -53894,6 +54484,20 @@ var THREE = (async function (exports) { } + updateTimestamp( type, time ) { + + this.timestamp[ type ] += time; + + } + + resetCompute() { + + this.compute.computeCalls = 0; + + this.timestamp.compute = 0; + + } + reset() { this.render.drawCalls = 0; @@ -53901,6 +54505,8 @@ var THREE = (async function (exports) { this.render.points = 0; this.render.lines = 0; + this.timestamp.render = 0; + } dispose() { @@ -53912,6 +54518,8 @@ var THREE = (async function (exports) { this.render.calls = 0; this.compute.calls = 0; + this.timestamp.compute = 0; + this.timestamp.render = 0; this.memory.geometries = 0; this.memory.textures = 0; @@ -53958,16 +54566,18 @@ var THREE = (async function (exports) { } - let _id = 0; + let _id$3 = 0; class ProgrammableStage { - constructor( code, type ) { + constructor( code, type, transforms = null, attributes = null ) { - this.id = _id ++; + this.id = _id$3 ++; this.code = code; this.stage = type; + this.transforms = transforms; + this.attributes = attributes; this.usedTimes = 0; @@ -54014,18 +54624,18 @@ var THREE = (async function (exports) { // get shader - const nodeBuilder = this.nodes.getForCompute( computeNode ); + const nodeBuilderState = this.nodes.getForCompute( computeNode ); // programmable stage - let stageCompute = this.programs.compute.get( nodeBuilder.computeShader ); + let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader ); if ( stageCompute === undefined ) { if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram ); - stageCompute = new ProgrammableStage( nodeBuilder.computeShader, 'compute' ); - this.programs.compute.set( nodeBuilder.computeShader, stageCompute ); + stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes ); + this.programs.compute.set( nodeBuilderState.computeShader, stageCompute ); backend.createProgram( stageCompute ); @@ -54061,7 +54671,7 @@ var THREE = (async function (exports) { } - getForRender( renderObject ) { + getForRender( renderObject, promises = null ) { const { backend } = this; @@ -54121,7 +54731,7 @@ var THREE = (async function (exports) { if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline ); - pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey ); + pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ); } else { @@ -54222,7 +54832,7 @@ var THREE = (async function (exports) { } - _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey ) { + _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) { // check for existing pipeline @@ -54238,7 +54848,7 @@ var THREE = (async function (exports) { renderObject.pipeline = pipeline; - this.backend.createRenderPipeline( renderObject ); + this.backend.createRenderPipeline( renderObject, promises ); } @@ -54338,7 +54948,7 @@ var THREE = (async function (exports) { const nodeBuilderState = this.nodes.getForCompute( computeNode ); - const bindings = nodeBuilderState.bindings.compute; + const bindings = nodeBuilderState.bindings; data.bindings = bindings; @@ -54479,6 +55089,7 @@ var THREE = (async function (exports) { VECTOR2: 'vec2', VECTOR3: 'vec3', VECTOR4: 'vec4', + MATRIX2: 'mat2', MATRIX3: 'mat3', MATRIX4: 'mat4' }; @@ -54744,7 +55355,7 @@ var THREE = (async function (exports) { } - updateReference() { + setReference( /*state*/ ) { return this; @@ -54852,12 +55463,20 @@ var THREE = (async function (exports) { } - analyze( builder ) { + increaseUsage( builder ) { const nodeData = builder.getDataFromNode( this ); - nodeData.dependenciesCount = nodeData.dependenciesCount === undefined ? 1 : nodeData.dependenciesCount + 1; + nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; + + return nodeData.usageCount; + + } - if ( nodeData.dependenciesCount === 1 ) { + analyze( builder ) { + + const usageCount = this.increaseUsage( builder ); + + if ( usageCount === 1 ) { // node flow children @@ -54921,6 +55540,8 @@ var THREE = (async function (exports) { if ( buildStage === 'setup' ) { + this.setReference( builder ); + const properties = builder.getNodeProperties( this ); if ( properties.initialized !== true || builder.context.tempRead === false ) { @@ -55176,114 +55797,60 @@ var THREE = (async function (exports) { } - class InputNode extends Node { - - constructor( value, nodeType = null ) { - - super( nodeType ); - - this.isInputNode = true; - - this.value = value; - this.precision = null; - - } - - getNodeType( /*builder*/ ) { - - if ( this.nodeType === null ) { - - return getValueType( this.value ); - - } - - return this.nodeType; - - } - - getInputType( builder ) { - - return this.getNodeType( builder ); - - } + class TempNode extends Node { - setPrecision( precision ) { + constructor( type ) { - this.precision = precision; + super( type ); - return this; + this.isTempNode = true; } - serialize( data ) { - - super.serialize( data ); - - data.value = this.value; - - if ( this.value && this.value.toArray ) data.value = this.value.toArray(); - - data.valueType = getValueType( this.value ); - data.nodeType = this.nodeType; - - if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + hasDependencies( builder ) { - data.precision = this.precision; + return builder.getDataFromNode( this ).usageCount > 1; } - deserialize( data ) { - - super.deserialize( data ); - - this.nodeType = data.nodeType; - this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; - - this.precision = data.precision || null; - - if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + build( builder, output ) { - } + const buildStage = builder.getBuildStage(); - generate( /*builder, output*/ ) { + if ( buildStage === 'generate' ) { - } + const type = builder.getVectorType( this.getNodeType( builder, output ) ); + const nodeData = builder.getDataFromNode( this ); - } + if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { - addNodeClass( 'InputNode', InputNode ); + return builder.format( nodeData.propertyName, type, output ); - class UniformGroupNode extends Node { + } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - constructor( name, shared = false ) { + const snippet = super.build( builder, type ); - super( 'string' ); + const nodeVar = builder.getVarFromNode( this, null, type ); + const propertyName = builder.getPropertyName( nodeVar ); - this.name = name; - this.version = 0; + builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - this.shared = shared; + nodeData.snippet = snippet; + nodeData.propertyName = propertyName; - this.isUniformGroup = true; + return builder.format( nodeData.propertyName, type, output ); - } + } - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + return super.build( builder, output ); } } - const uniformGroup = ( name ) => new UniformGroupNode( name ); - const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); - - const frameGroup = sharedUniformGroup( 'frame' ); - const renderGroup = sharedUniformGroup( 'render' ); - const objectGroup = uniformGroup( 'object' ); - - addNodeClass( 'UniformGroupNode', UniformGroupNode ); + addNodeClass( 'TempNode', TempNode ); class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute @@ -55379,61 +55946,6 @@ var THREE = (async function (exports) { addNodeClass( 'ConvertNode', ConvertNode ); - class TempNode extends Node { - - constructor( type ) { - - super( type ); - - this.isTempNode = true; - - } - - hasDependencies( builder ) { - - return builder.getDataFromNode( this ).dependenciesCount > 1; - - } - - build( builder, output ) { - - const buildStage = builder.getBuildStage(); - - if ( buildStage === 'generate' ) { - - const type = builder.getVectorType( this.getNodeType( builder, output ) ); - const nodeData = builder.getDataFromNode( this ); - - if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { - - return builder.format( nodeData.propertyName, type, output ); - - } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - - const snippet = super.build( builder, type ); - - const nodeVar = builder.getVarFromNode( this, null, type ); - const propertyName = builder.getPropertyName( nodeVar ); - - builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - - nodeData.snippet = snippet; - nodeData.propertyName = propertyName; - - return builder.format( nodeData.propertyName, type, output ); - - } - - } - - return super.build( builder, output ); - - } - - } - - addNodeClass( 'TempNode', TempNode ); - class JoinNode extends TempNode { constructor( nodes = [], nodeType = null ) { @@ -55461,7 +55973,7 @@ var THREE = (async function (exports) { const type = this.getNodeType( builder ); const nodes = this.nodes; - const primitiveType = builder.getPrimitiveType( type ); + const primitiveType = builder.getComponentType( type ); const snippetValues = []; @@ -55469,7 +55981,7 @@ var THREE = (async function (exports) { let inputSnippet = input.build( builder ); - const inputPrimitiveType = builder.getPrimitiveType( input.getNodeType( builder ) ); + const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) ); if ( inputPrimitiveType !== primitiveType ) { @@ -55520,15 +56032,15 @@ var THREE = (async function (exports) { } - getPrimitiveType( builder ) { + getComponentType( builder ) { - return builder.getPrimitiveType( this.node.getNodeType( builder ) ); + return builder.getComponentType( this.node.getNodeType( builder ) ); } getNodeType( builder ) { - return builder.getTypeFromLength( this.components.length, this.getPrimitiveType( builder ) ); + return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) ); } @@ -55549,7 +56061,7 @@ var THREE = (async function (exports) { // needed expand the input node - type = builder.getTypeFromLength( this.getVectorLength(), this.getPrimitiveType( builder ) ); + type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) ); } @@ -55656,6 +56168,83 @@ var THREE = (async function (exports) { addNodeClass( 'SetNode', SetNode ); + class InputNode extends Node { + + constructor( value, nodeType = null ) { + + super( nodeType ); + + this.isInputNode = true; + + this.value = value; + this.precision = null; + + } + + getNodeType( /*builder*/ ) { + + if ( this.nodeType === null ) { + + return getValueType( this.value ); + + } + + return this.nodeType; + + } + + getInputType( builder ) { + + return this.getNodeType( builder ); + + } + + setPrecision( precision ) { + + this.precision = precision; + + return this; + + } + + serialize( data ) { + + super.serialize( data ); + + data.value = this.value; + + if ( this.value && this.value.toArray ) data.value = this.value.toArray(); + + data.valueType = getValueType( this.value ); + data.nodeType = this.nodeType; + + if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + + data.precision = this.precision; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.nodeType = data.nodeType; + this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; + + this.precision = data.precision || null; + + if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + + } + + generate( /*builder, output*/ ) { + + } + + } + + addNodeClass( 'InputNode', InputNode ); + class ConstNode extends InputNode { constructor( value, nodeType = null ) { @@ -56241,6 +56830,11 @@ var THREE = (async function (exports) { const uvec4 = new ConvertType( 'uvec4' ); const bvec4 = new ConvertType( 'bvec4' ); + const mat2 = new ConvertType( 'mat2' ); + const imat2 = new ConvertType( 'imat2' ); + const umat2 = new ConvertType( 'umat2' ); + const bmat2 = new ConvertType( 'bmat2' ); + const mat3 = new ConvertType( 'mat3' ); const imat3 = new ConvertType( 'imat3' ); const umat3 = new ConvertType( 'umat3' ); @@ -56271,6 +56865,10 @@ var THREE = (async function (exports) { addNodeElement( 'ivec4', ivec4 ); addNodeElement( 'uvec4', uvec4 ); addNodeElement( 'bvec4', bvec4 ); + addNodeElement( 'mat2', mat2 ); + addNodeElement( 'imat2', imat2 ); + addNodeElement( 'umat2', umat2 ); + addNodeElement( 'bmat2', bmat2 ); addNodeElement( 'mat3', mat3 ); addNodeElement( 'imat3', imat3 ); addNodeElement( 'umat3', umat3 ); @@ -56291,159 +56889,118 @@ var THREE = (async function (exports) { addNodeElement( 'element', element ); addNodeElement( 'convert', convert ); - class UniformNode extends InputNode { - - constructor( value, nodeType = null ) { - - super( value, nodeType ); - - this.isUniformNode = true; - - this.groupNode = objectGroup; - - } + class AssignNode extends TempNode { - setGroup( group ) { + constructor( targetNode, sourceNode ) { - this.groupNode = group; + super(); - return this; + this.targetNode = targetNode; + this.sourceNode = sourceNode; } - getGroup() { + hasDependencies() { - return this.groupNode; + return false; } - getUniformHash( builder ) { + getNodeType( builder, output ) { - return this.getHash( builder ); + return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; } - generate( builder, output ) { + needsSplitAssign( builder ) { - const type = this.getNodeType( builder ); + const { targetNode } = this; - const hash = this.getUniformHash( builder ); + if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) { - let sharedNode = builder.getNodeFromHash( hash ); + const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) ); + const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components; - if ( sharedNode === undefined ) { - - builder.setHashNode( this, hash ); - - sharedNode = this; + return assignDiferentVector; } - const sharedNodeType = sharedNode.getInputType( builder ); - - const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); - const propertyName = builder.getPropertyName( nodeUniform ); - - if ( builder.context.label !== undefined ) delete builder.context.label; - - return builder.format( propertyName, type, output ); - - } - - } - - const uniform = ( arg1, arg2 ) => { - - const nodeType = getConstNodeType( arg2 || arg1 ); - - // @TODO: get ConstNode from .traverse() in the future - const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; - - return nodeObject( new UniformNode( value, nodeType ) ); - - }; - - addNodeClass( 'UniformNode', UniformNode ); - - class ArrayUniformNode extends UniformNode { - - constructor( nodes = [] ) { - - super(); - - this.isArrayUniformNode = true; - - this.nodes = nodes; + return false; } - getNodeType( builder ) { + generate( builder, output ) { - return this.nodes[ 0 ].getNodeType( builder ); + const { targetNode, sourceNode } = this; - } + const needsSplitAssign = this.needsSplitAssign( builder ); - } + const targetType = targetNode.getNodeType( builder ); - addNodeClass( 'ArrayUniformNode', ArrayUniformNode ); + const target = targetNode.context( { assign: true } ).build( builder ); + const source = sourceNode.build( builder, targetType ); - class AssignNode extends TempNode { + const sourceType = sourceNode.getNodeType( builder ); - constructor( targetNode, sourceNode ) { + const nodeData = builder.getDataFromNode( this ); - super(); + // - this.targetNode = targetNode; - this.sourceNode = sourceNode; + let snippet; - } + if ( nodeData.initialized === true ) { - hasDependencies() { + if ( output !== 'void' ) { - return false; + snippet = target; - } + } - getNodeType( builder, output ) { + } else if ( needsSplitAssign ) { - return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; + const sourceVar = builder.getVarFromNode( this, null, targetType ); + const sourceProperty = builder.getPropertyName( sourceVar ); - } + builder.addLineFlowCode( `${ sourceProperty } = ${ source }` ); - generate( builder, output ) { + const targetRoot = targetNode.node.context( { assign: true } ).build( builder ); - const targetNode = this.targetNode; - const sourceNode = this.sourceNode; + for ( let i = 0; i < targetNode.components.length; i ++ ) { - const targetType = targetNode.getNodeType( builder ); + const component = targetNode.components[ i ]; - const target = targetNode.build( builder ); - const source = sourceNode.build( builder, targetType ); + builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` ); - const snippet = `${ target } = ${ source }`; + } - if ( output === 'void' ) { + if ( output !== 'void' ) { - builder.addLineFlowCode( snippet ); + snippet = target; - return; + } } else { - const sourceType = sourceNode.getNodeType( builder ); + snippet = `${ target } = ${ source }`; - if ( sourceType === 'void' ) { + if ( output === 'void' || sourceType === 'void' ) { builder.addLineFlowCode( snippet ); - return target; + if ( output !== 'void' ) { - } + snippet = target; + + } - return builder.format( snippet, targetType, output ); + } } + nodeData.initialized = true; + + return builder.format( snippet, targetType, output ); + } } @@ -57199,6 +57756,12 @@ var THREE = (async function (exports) { } + isGlobal() { + + return true; + + } + setIncludes( includes ) { this.includes = includes; @@ -57383,6 +57946,112 @@ var THREE = (async function (exports) { addNodeClass( 'FunctionNode', FunctionNode ); + class UniformGroupNode extends Node { + + constructor( name, shared = false ) { + + super( 'string' ); + + this.name = name; + this.version = 0; + + this.shared = shared; + + this.isUniformGroup = true; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + } + + const uniformGroup = ( name ) => new UniformGroupNode( name ); + const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); + + const frameGroup = sharedUniformGroup( 'frame' ); + const renderGroup = sharedUniformGroup( 'render' ); + const objectGroup = uniformGroup( 'object' ); + + addNodeClass( 'UniformGroupNode', UniformGroupNode ); + + class UniformNode extends InputNode { + + constructor( value, nodeType = null ) { + + super( value, nodeType ); + + this.isUniformNode = true; + + this.groupNode = objectGroup; + + } + + setGroup( group ) { + + this.groupNode = group; + + return this; + + } + + getGroup() { + + return this.groupNode; + + } + + getUniformHash( builder ) { + + return this.getHash( builder ); + + } + + generate( builder, output ) { + + const type = this.getNodeType( builder ); + + const hash = this.getUniformHash( builder ); + + let sharedNode = builder.getNodeFromHash( hash ); + + if ( sharedNode === undefined ) { + + builder.setHashNode( this, hash ); + + sharedNode = this; + + } + + const sharedNodeType = sharedNode.getInputType( builder ); + + const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); + const propertyName = builder.getPropertyName( nodeUniform ); + + if ( builder.context.label !== undefined ) delete builder.context.label; + + return builder.format( propertyName, type, output ); + + } + + } + + const uniform = ( arg1, arg2 ) => { + + const nodeType = getConstNodeType( arg2 || arg1 ); + + // @TODO: get ConstNode from .traverse() in the future + const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; + + return nodeObject( new UniformNode( value, nodeType ) ); + + }; + + addNodeClass( 'UniformNode', UniformNode ); + class UVNode extends AttributeNode { constructor( index = 0 ) { @@ -57490,7 +58159,7 @@ var THREE = (async function (exports) { const bNode = this.bNode; const typeA = aNode.getNodeType( builder ); - const typeB = bNode.getNodeType( builder ); + const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( typeA === 'void' || typeB === 'void' ) { @@ -57500,11 +58169,11 @@ var THREE = (async function (exports) { return typeA; - } else if ( op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { + } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { return builder.getIntegerType( typeA ); - } else if ( op === '==' || op === '&&' || op === '||' || op === '^^' ) { + } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) { return 'bool'; @@ -57561,7 +58230,7 @@ var THREE = (async function (exports) { if ( type !== 'void' ) { typeA = aNode.getNodeType( builder ); - typeB = bNode.getNodeType( builder ); + typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) { @@ -57607,7 +58276,7 @@ var THREE = (async function (exports) { } const a = aNode.build( builder, typeA ); - const b = bNode.build( builder, typeB ); + const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null; const outputLength = builder.getTypeLength( output ); const fnOpSnippet = builder.getFunctionOperator( op ); @@ -57630,6 +58299,10 @@ var THREE = (async function (exports) { return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output ); + } else if ( op === '!' || op === '~' ) { + + return builder.format( `(${op}${a})`, typeA, output ); + } else if ( fnOpSnippet ) { return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output ); @@ -57687,8 +58360,10 @@ var THREE = (async function (exports) { const greaterThanEqual = nodeProxy( OperatorNode, '>=' ); const and = nodeProxy( OperatorNode, '&&' ); const or = nodeProxy( OperatorNode, '||' ); + const not = nodeProxy( OperatorNode, '!' ); const xor = nodeProxy( OperatorNode, '^^' ); const bitAnd = nodeProxy( OperatorNode, '&' ); + const bitNot = nodeProxy( OperatorNode, '~' ); const bitOr = nodeProxy( OperatorNode, '|' ); const bitXor = nodeProxy( OperatorNode, '^' ); const shiftLeft = nodeProxy( OperatorNode, '<<' ); @@ -57707,8 +58382,10 @@ var THREE = (async function (exports) { addNodeElement( 'greaterThanEqual', greaterThanEqual ); addNodeElement( 'and', and ); addNodeElement( 'or', or ); + addNodeElement( 'not', not ); addNodeElement( 'xor', xor ); addNodeElement( 'bitAnd', bitAnd ); + addNodeElement( 'bitNot', bitNot ); addNodeElement( 'bitOr', bitOr ); addNodeElement( 'bitXor', bitXor ); addNodeElement( 'shiftLeft', shiftLeft ); @@ -57770,6 +58447,14 @@ var THREE = (async function (exports) { return 'vec3'; + } else if ( method === MathNode.ALL ) { + + return 'bool'; + + } else if ( method === MathNode.EQUALS ) { + + return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' ); + } else if ( method === MathNode.MOD ) { return this.aNode.getNodeType( builder ); @@ -57908,6 +58593,10 @@ var THREE = (async function (exports) { // 1 input + MathNode.ALL = 'all'; + MathNode.ANY = 'any'; + MathNode.EQUALS = 'equals'; + MathNode.RADIANS = 'radians'; MathNode.DEGREES = 'degrees'; MathNode.EXP = 'exp'; @@ -57964,6 +58653,12 @@ var THREE = (async function (exports) { const EPSILON = float( 1e-6 ); const INFINITY = float( 1e6 ); + const PI = float( Math.PI ); + const PI2 = float( Math.PI * 2 ); + + const all = nodeProxy( MathNode, MathNode.ALL ); + const any = nodeProxy( MathNode, MathNode.ANY ); + const equals = nodeProxy( MathNode, MathNode.EQUALS ); const radians = nodeProxy( MathNode, MathNode.RADIANS ); const degrees = nodeProxy( MathNode, MathNode.DEGREES ); @@ -58013,6 +58708,7 @@ var THREE = (async function (exports) { const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ); const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) ); + const lengthSq = ( a ) => dot( a, a ); const mix = nodeProxy( MathNode, MathNode.MIX ); const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) ); const saturate = ( value ) => clamp( value ); @@ -58023,6 +58719,10 @@ var THREE = (async function (exports) { const mixElement = ( t, e1, e2 ) => mix( e1, e2, t ); const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x ); + addNodeElement( 'all', all ); + addNodeElement( 'any', any ); + addNodeElement( 'equals', equals ); + addNodeElement( 'radians', radians ); addNodeElement( 'degrees', degrees ); addNodeElement( 'exp', exp ); @@ -58044,6 +58744,7 @@ var THREE = (async function (exports) { addNodeElement( 'abs', abs ); addNodeElement( 'sign', sign ); addNodeElement( 'length', length ); + addNodeElement( 'lengthSq', lengthSq ); addNodeElement( 'negate', negate ); addNodeElement( 'oneMinus', oneMinus ); addNodeElement( 'dFdx', dFdx ); @@ -58297,7 +58998,7 @@ var THREE = (async function (exports) { } - updateReference( /*frame*/ ) { + setReference( /*state*/ ) { return this.value; @@ -58606,440 +59307,428 @@ var THREE = (async function (exports) { addNodeClass( 'TextureNode', TextureNode ); - class ReferenceNode extends Node { - - constructor( property, uniformType, object = null ) { + class BufferNode extends UniformNode { - super(); + constructor( value, bufferType, bufferCount = 0 ) { - this.property = property; - this.index = null; + super( value, bufferType ); - this.uniformType = uniformType; + this.isBufferNode = true; - this.object = object; - this.reference = null; + this.bufferType = bufferType; + this.bufferCount = bufferCount; - this.node = null; + } - this.updateType = NodeUpdateType.OBJECT; + getInputType( /*builder*/ ) { - this.setNodeType( uniformType ); + return 'buffer'; } - updateReference( frame ) { + } - this.reference = this.object !== null ? this.object : frame.object; + const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - return this.reference; + addNodeClass( 'BufferNode', BufferNode ); - } + class UniformsElementNode extends ArrayElementNode { - setIndex( index ) { + constructor( arrayBuffer, indexNode ) { - this.index = index; + super( arrayBuffer, indexNode ); - return this; + this.isArrayBufferElementNode = true; } - getIndex() { + getNodeType( builder ) { - return this.index; + return this.node.getElementType( builder ); } - setNodeType( uniformType ) { + generate( builder ) { - let node = null; + const snippet = super.generate( builder ); + const type = this.getNodeType(); - if ( uniformType === 'texture' ) { + return builder.format( snippet, 'vec4', type ); - node = texture( null ); + } - } else { + } - node = uniform( uniformType ); + class UniformsNode extends BufferNode { - } + constructor( value, elementType = null ) { - this.node = node; + super( null, 'vec4' ); - } + this.array = value; + this.elementType = elementType; - getNodeType( builder ) { + this._elementType = null; + this._elementLength = 0; - return this.node.getNodeType( builder ); + this.updateType = NodeUpdateType.RENDER; - } + this.isArrayBufferNode = true; - update( /*frame*/ ) { + } - let value = this.reference[ this.property ]; + getElementType() { - if ( this.index !== null ) { + return this.elementType || this._elementType; - value = value[ this.index ]; + } - } + getElementLength() { - this.node.value = value; + return this._elementLength; } - setup( /*builder*/ ) { + update( /*frame*/ ) { - return this.node; + const { array, value } = this; - } + const elementLength = this.getElementLength(); + const elementType = this.getElementType(); - } + if ( elementLength === 1 ) { - const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); - const referenceIndex = ( name, index, type, object ) => nodeObject( new ReferenceNode( name, type, object ).setIndex( index ) ); + for ( let i = 0; i < array.length; i ++ ) { - addNodeClass( 'ReferenceNode', ReferenceNode ); + const index = i * 4; - class MaterialReferenceNode extends ReferenceNode { + value[ index ] = array[ i ]; - constructor( property, inputType, material = null ) { + } - super( property, inputType, material ); + } else if ( elementType === 'color' ) { - this.material = material; + for ( let i = 0; i < array.length; i ++ ) { - //this.updateType = NodeUpdateType.RENDER; + const index = i * 4; + const vector = array[ i ]; - } + value[ index ] = vector.r; + value[ index + 1 ] = vector.g; + value[ index + 2 ] = vector.b || 0; + //value[ index + 3 ] = vector.a || 0; - /*setNodeType( node ) { + } - super.setNodeType( node ); + } else { - this.node.groupNode = renderGroup; + for ( let i = 0; i < array.length; i ++ ) { - }*/ + const index = i * 4; + const vector = array[ i ]; - updateReference( frame ) { + value[ index ] = vector.x; + value[ index + 1 ] = vector.y; + value[ index + 2 ] = vector.z || 0; + value[ index + 3 ] = vector.w || 0; - this.reference = this.material !== null ? this.material : frame.material; + } - return this.reference; + } } setup( builder ) { - const material = this.material !== null ? this.material : builder.material; + const length = this.array.length; - this.node.value = material[ this.property ]; + this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType; + this._elementLength = builder.getTypeLength( this._elementType ); + + this.value = new Float32Array( length * 4 ); + this.bufferCount = length; return super.setup( builder ); } - } + element( indexNode ) { - const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); + return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) ); - addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); - - class Object3DNode extends Node { + } - constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { + } - super(); + const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) ); - this.scope = scope; - this.object3d = object3d; + addNodeClass( 'UniformsNode', UniformsNode ); - this.updateType = NodeUpdateType.OBJECT; + class ReferenceElementNode extends ArrayElementNode { - this._uniformNode = new UniformNode( null ); + constructor( referenceNode, indexNode ) { - } + super( referenceNode, indexNode ); - getNodeType() { + this.referenceNode = referenceNode; - const scope = this.scope; + this.isReferenceElementNode = true; - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - return 'mat4'; + getNodeType() { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + return this.referenceNode.uniformType; - return 'mat3'; + } - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + generate( builder ) { - return 'vec3'; + const snippet = super.generate( builder ); + const arrayType = this.referenceNode.getNodeType(); + const elementType = this.getNodeType(); - } + return builder.format( snippet, arrayType, elementType ); } - update( frame ) { + } - const object = this.object3d; - const uniformNode = this._uniformNode; - const scope = this.scope; + class ReferenceNode extends Node { - if ( scope === Object3DNode.VIEW_MATRIX ) { + constructor( property, uniformType, object = null, count = null ) { - uniformNode.value = object.modelViewMatrix; + super(); - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + this.property = property; + this.uniformType = uniformType; + this.object = object; + this.count = count; - uniformNode.value = object.normalMatrix; + this.properties = property.split( '.' ); + this.reference = null; + this.node = null; - } else if ( scope === Object3DNode.WORLD_MATRIX ) { + this.updateType = NodeUpdateType.OBJECT; - uniformNode.value = object.matrixWorld; + } - } else if ( scope === Object3DNode.POSITION ) { + element( indexNode ) { - uniformNode.value = uniformNode.value || new Vector3(); + return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) ); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } - } else if ( scope === Object3DNode.SCALE ) { + setNodeType( uniformType ) { - uniformNode.value = uniformNode.value || new Vector3(); + let node = null; - uniformNode.value.setFromMatrixScale( object.matrixWorld ); + if ( this.count !== null ) { - } else if ( scope === Object3DNode.DIRECTION ) { + node = buffer( null, uniformType, this.count ); - uniformNode.value = uniformNode.value || new Vector3(); + } else if ( Array.isArray( this.getValueFromReference() ) ) { - object.getWorldDirection( uniformNode.value ); + node = uniforms( null, uniformType ); - } else if ( scope === Object3DNode.VIEW_POSITION ) { + } else if ( uniformType === 'texture' ) { - const camera = frame.camera; + node = texture( null ); - uniformNode.value = uniformNode.value || new Vector3(); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } else { - uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); + node = uniform( null, uniformType ); } + this.node = node; + } - generate( builder ) { + getNodeType( builder ) { - const scope = this.scope; + return this.node.getNodeType( builder ); - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - this._uniformNode.nodeType = 'mat4'; + getValueFromReference( object = this.reference ) { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + const { properties } = this; - this._uniformNode.nodeType = 'mat3'; + let value = object[ properties[ 0 ] ]; - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + for ( let i = 1; i < properties.length; i ++ ) { - this._uniformNode.nodeType = 'vec3'; + value = value[ properties[ i ] ]; } - return this._uniformNode.build( builder ); + return value; } - serialize( data ) { + setReference( state ) { - super.serialize( data ); + this.reference = this.object !== null ? this.object : state.object; - data.scope = this.scope; + return this.reference; } - deserialize( data ) { + setup() { - super.deserialize( data ); + this.updateValue(); - this.scope = data.scope; + return this.node; } - } + update( /*frame*/ ) { - Object3DNode.VIEW_MATRIX = 'viewMatrix'; - Object3DNode.NORMAL_MATRIX = 'normalMatrix'; - Object3DNode.WORLD_MATRIX = 'worldMatrix'; - Object3DNode.POSITION = 'position'; - Object3DNode.SCALE = 'scale'; - Object3DNode.VIEW_POSITION = 'viewPosition'; - Object3DNode.DIRECTION = 'direction'; + this.updateValue(); - const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION ); - const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX ); - const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX ); - const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ); - const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION ); - const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE ); - const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ); + } - addNodeClass( 'Object3DNode', Object3DNode ); + updateValue() { - //const cameraGroup = sharedUniformGroup( 'camera' ); + if ( this.node === null ) this.setNodeType( this.uniformType ); - class CameraNode extends Object3DNode { + const value = this.getValueFromReference(); - constructor( scope = CameraNode.POSITION ) { + if ( Array.isArray( value ) ) { - super( scope ); + this.node.array = value; - this.updateType = NodeUpdateType.RENDER; + } else { - //this._uniformNode.groupNode = cameraGroup; + this.node.value = value; + + } } - getNodeType( builder ) { + } - const scope = this.scope; + const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); + const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) ); - if ( scope === CameraNode.PROJECTION_MATRIX ) { + addNodeClass( 'ReferenceNode', ReferenceNode ); - return 'mat4'; + class MaterialReferenceNode extends ReferenceNode { - } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + constructor( property, inputType, material = null ) { - return 'float'; + super( property, inputType, material ); - } + this.material = material; - return super.getNodeType( builder ); + //this.updateType = NodeUpdateType.RENDER; } - update( frame ) { + /*setNodeType( node ) { - const camera = frame.camera; - const uniformNode = this._uniformNode; - const scope = this.scope; + super.setNodeType( node ); - //cameraGroup.needsUpdate = true; + this.node.groupNode = renderGroup; - if ( scope === CameraNode.VIEW_MATRIX ) { + }*/ - uniformNode.value = camera.matrixWorldInverse; + setReference( state ) { - } else if ( scope === CameraNode.PROJECTION_MATRIX ) { + this.reference = this.material !== null ? this.material : state.material; - uniformNode.value = camera.projectionMatrix; + return this.reference; - } else if ( scope === CameraNode.NEAR ) { + } - uniformNode.value = camera.near; + } - } else if ( scope === CameraNode.FAR ) { + const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); - uniformNode.value = camera.far; + addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); - } else if ( scope === CameraNode.LOG_DEPTH ) { + class Object3DNode extends Node { - uniformNode.value = 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ); + constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { - } else { + super(); - this.object3d = camera; + this.scope = scope; + this.object3d = object3d; - super.update( frame ); + this.updateType = NodeUpdateType.OBJECT; - } + this._uniformNode = new UniformNode( null ); } - generate( builder ) { + getNodeType() { const scope = this.scope; - if ( scope === CameraNode.PROJECTION_MATRIX ) { - - this._uniformNode.nodeType = 'mat4'; - - } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { - this._uniformNode.nodeType = 'float'; + return 'mat4'; - } + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - return super.generate( builder ); + return 'mat3'; - } + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { - } + return 'vec3'; - CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; - CameraNode.NEAR = 'near'; - CameraNode.FAR = 'far'; - CameraNode.LOG_DEPTH = 'logDepth'; + } - const cameraProjectionMatrix = label( nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ), 'projectionMatrix' ); - const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); - const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); - const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); - const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX ); - const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX ); - const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX ); - const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION ); + } - addNodeClass( 'CameraNode', CameraNode ); + update( frame ) { - class ModelNode extends Object3DNode { + const object = this.object3d; + const uniformNode = this._uniformNode; + const scope = this.scope; - constructor( scope = ModelNode.VIEW_MATRIX ) { + if ( scope === Object3DNode.VIEW_MATRIX ) { - super( scope ); + uniformNode.value = object.modelViewMatrix; - } + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - update( frame ) { + uniformNode.value = object.normalMatrix; - this.object3d = frame.object; + } else if ( scope === Object3DNode.WORLD_MATRIX ) { - super.update( frame ); + uniformNode.value = object.matrixWorld; - } + } else if ( scope === Object3DNode.POSITION ) { - } + uniformNode.value = uniformNode.value || new Vector3(); - const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION ); - const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' ); - const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX ); - const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX ); - const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION ); - const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE ); - const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION ); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); - addNodeClass( 'ModelNode', ModelNode ); + } else if ( scope === Object3DNode.SCALE ) { - class NormalNode extends Node { + uniformNode.value = uniformNode.value || new Vector3(); - constructor( scope = NormalNode.LOCAL ) { + uniformNode.value.setFromMatrixScale( object.matrixWorld ); - super( 'vec3' ); + } else if ( scope === Object3DNode.DIRECTION ) { - this.scope = scope; + uniformNode.value = uniformNode.value || new Vector3(); - } + object.getWorldDirection( uniformNode.value ); - isGlobal() { + } else if ( scope === Object3DNode.VIEW_POSITION ) { - return true; + const camera = frame.camera; - } + uniformNode.value = uniformNode.value || new Vector3(); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); - getHash( /*builder*/ ) { + uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); - return `normal-${this.scope}`; + } } @@ -59047,30 +59736,250 @@ var THREE = (async function (exports) { const scope = this.scope; - let outputNode = null; - - if ( scope === NormalNode.GEOMETRY ) { - - outputNode = attribute( 'normal', 'vec3' ); - - } else if ( scope === NormalNode.LOCAL ) { + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { - outputNode = varying( normalGeometry ); + this._uniformNode.nodeType = 'mat4'; - } else if ( scope === NormalNode.VIEW ) { + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - const vertexNode = modelNormalMatrix.mul( normalLocal ); - outputNode = normalize( varying( vertexNode ) ); + this._uniformNode.nodeType = 'mat3'; - } else if ( scope === NormalNode.WORLD ) { + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { - // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView ) - const vertexNode = normalView.transformDirection( cameraViewMatrix ); - outputNode = normalize( varying( vertexNode ) ); + this._uniformNode.nodeType = 'vec3'; } - return outputNode.build( builder, this.getNodeType( builder ) ); + return this._uniformNode.build( builder ); + + } + + serialize( data ) { + + super.serialize( data ); + + data.scope = this.scope; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.scope = data.scope; + + } + + } + + Object3DNode.VIEW_MATRIX = 'viewMatrix'; + Object3DNode.NORMAL_MATRIX = 'normalMatrix'; + Object3DNode.WORLD_MATRIX = 'worldMatrix'; + Object3DNode.POSITION = 'position'; + Object3DNode.SCALE = 'scale'; + Object3DNode.VIEW_POSITION = 'viewPosition'; + Object3DNode.DIRECTION = 'direction'; + + const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION ); + const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX ); + const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX ); + const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ); + const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION ); + const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE ); + const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ); + + addNodeClass( 'Object3DNode', Object3DNode ); + + //const cameraGroup = sharedUniformGroup( 'camera' ); + + class CameraNode extends Object3DNode { + + constructor( scope = CameraNode.POSITION ) { + + super( scope ); + + this.updateType = NodeUpdateType.RENDER; + + //this._uniformNode.groupNode = cameraGroup; + + } + + getNodeType( builder ) { + + const scope = this.scope; + + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + return 'mat4'; + + } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + + return 'float'; + + } + + return super.getNodeType( builder ); + + } + + update( frame ) { + + const camera = frame.camera; + const uniformNode = this._uniformNode; + const scope = this.scope; + + //cameraGroup.needsUpdate = true; + + if ( scope === CameraNode.VIEW_MATRIX ) { + + uniformNode.value = camera.matrixWorldInverse; + + } else if ( scope === CameraNode.PROJECTION_MATRIX ) { + + uniformNode.value = camera.projectionMatrix; + + } else if ( scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + uniformNode.value = camera.projectionMatrixInverse; + + } else if ( scope === CameraNode.NEAR ) { + + uniformNode.value = camera.near; + + } else if ( scope === CameraNode.FAR ) { + + uniformNode.value = camera.far; + + } else if ( scope === CameraNode.LOG_DEPTH ) { + + uniformNode.value = 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ); + + } else { + + this.object3d = camera; + + super.update( frame ); + + } + + } + + generate( builder ) { + + const scope = this.scope; + + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + this._uniformNode.nodeType = 'mat4'; + + } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + + this._uniformNode.nodeType = 'float'; + + } + + return super.generate( builder ); + + } + + } + + CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; + CameraNode.PROJECTION_MATRIX_INVERSE = 'projectionMatrixInverse'; + CameraNode.NEAR = 'near'; + CameraNode.FAR = 'far'; + CameraNode.LOG_DEPTH = 'logDepth'; + + const cameraProjectionMatrix = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ); + const cameraProjectionMatrixInverse = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX_INVERSE ); + const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); + const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); + const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); + const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX ); + const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX ); + const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX ); + const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION ); + + addNodeClass( 'CameraNode', CameraNode ); + + class ModelNode extends Object3DNode { + + constructor( scope = ModelNode.VIEW_MATRIX ) { + + super( scope ); + + } + + update( frame ) { + + this.object3d = frame.object; + + super.update( frame ); + + } + + } + + const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION ); + const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' ); + const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX ); + const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX ); + const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION ); + const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE ); + const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION ); + + addNodeClass( 'ModelNode', ModelNode ); + + class NormalNode extends Node { + + constructor( scope = NormalNode.LOCAL ) { + + super( 'vec3' ); + + this.scope = scope; + + } + + isGlobal() { + + return true; + + } + + getHash( /*builder*/ ) { + + return `normal-${this.scope}`; + + } + + generate( builder ) { + + const scope = this.scope; + + let outputNode = null; + + if ( scope === NormalNode.GEOMETRY ) { + + outputNode = attribute( 'normal', 'vec3' ); + + } else if ( scope === NormalNode.LOCAL ) { + + outputNode = varying( normalGeometry ); + + } else if ( scope === NormalNode.VIEW ) { + + const vertexNode = modelNormalMatrix.mul( normalLocal ); + outputNode = normalize( varying( vertexNode ) ); + + } else if ( scope === NormalNode.WORLD ) { + + // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView ) + const vertexNode = normalView.transformDirection( cameraViewMatrix ); + outputNode = normalize( varying( vertexNode ) ); + + } + + return outputNode.build( builder, this.getNodeType( builder ) ); } @@ -59330,11 +60239,11 @@ var THREE = (async function (exports) { } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) { - const iridescenceThicknessMaximum = reference( 1, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange ); if ( material.iridescenceThicknessMap ) { - const iridescenceThicknessMinimum = reference( 0, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange ); node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum ); @@ -59603,12 +60512,14 @@ var THREE = (async function (exports) { const nodeType = this.getNodeType( builder ); - const nodeUniform = builder.getBufferAttributeFromNode( this, nodeType ); - const propertyName = builder.getPropertyName( nodeUniform ); + const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType ); + const propertyName = builder.getPropertyName( nodeAttribute ); let output = null; - if ( builder.shaderStage === 'vertex' ) { + if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) { + + this.name = propertyName; output = propertyName; @@ -59721,31 +60632,6 @@ var THREE = (async function (exports) { addNodeClass( 'InstanceNode', InstanceNode ); - class BufferNode extends UniformNode { - - constructor( value, bufferType, bufferCount = 0 ) { - - super( value, bufferType ); - - this.isBufferNode = true; - - this.bufferType = bufferType; - this.bufferCount = bufferCount; - - } - - getInputType( /*builder*/ ) { - - return 'buffer'; - - } - - } - - const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - - addNodeClass( 'BufferNode', BufferNode ); - class TangentNode extends Node { constructor( scope = TangentNode.LOCAL ) { @@ -59787,13 +60673,19 @@ var THREE = (async function (exports) { outputNode = attribute( 'tangent', 'vec4' ); + if ( builder.geometry.hasAttribute( 'tangent' ) === false ) { + + builder.geometry.computeTangents(); + + } + } else if ( scope === TangentNode.LOCAL ) { outputNode = varying( tangentGeometry.xyz ); } else if ( scope === TangentNode.VIEW ) { - const vertexNode = modelViewMatrix.mul( tangentLocal ).xyz; + const vertexNode = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz; outputNode = normalize( varying( vertexNode ) ); } else if ( scope === TangentNode.WORLD ) { @@ -59841,11 +60733,12 @@ var THREE = (async function (exports) { class SkinningNode extends Node { - constructor( skinnedMesh ) { + constructor( skinnedMesh, useReference = false ) { super( 'void' ); this.skinnedMesh = skinnedMesh; + this.useReference = useReference; this.updateType = NodeUpdateType.OBJECT; @@ -59854,9 +60747,25 @@ var THREE = (async function (exports) { this.skinIndexNode = attribute( 'skinIndex', 'uvec4' ); this.skinWeightNode = attribute( 'skinWeight', 'vec4' ); - this.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); - this.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); - this.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode; + + if ( useReference ) { + + bindMatrixNode = reference( 'bindMatrix', 'mat4' ); + bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' ); + boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length ); + + } else { + + bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); + bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); + boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + + } + + this.bindMatrixNode = bindMatrixNode; + this.bindMatrixInverseNode = bindMatrixInverseNode; + this.boneMatricesNode = boneMatricesNode; } @@ -59918,18 +60827,214 @@ var THREE = (async function (exports) { } - update() { + update( frame ) { + + const object = this.useReference ? frame.object : this.skinnedMesh; - this.skinnedMesh.skeleton.update(); + object.skeleton.update(); } } - const skinning = nodeProxy( SkinningNode ); + const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) ); + const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) ); addNodeClass( 'SkinningNode', SkinningNode ); + class LoopNode extends Node { + + constructor( params = [] ) { + + super(); + + this.params = params; + + } + + getVarName( index ) { + + return String.fromCharCode( 'i'.charCodeAt() + index ); + + } + + getProperties( builder ) { + + const properties = builder.getNodeProperties( this ); + + if ( properties.stackNode !== undefined ) return properties; + + // + + const inputs = {}; + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + const param = this.params[ i ]; + + const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); + const type = ( param.isNode !== true && param.type ) || 'int'; + + inputs[ name ] = expression( name, type ); + + } + + properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); + properties.stackNode = builder.removeStack(); + + return properties; + + } + + getNodeType( builder ) { + + const { returnsNode } = this.getProperties( builder ); + + return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; + + } + + setup( builder ) { + + // setup properties + + this.getProperties( builder ); + + } + + generate( builder ) { + + const properties = this.getProperties( builder ); + + const contextData = { tempWrite: false }; + + const params = this.params; + const stackNode = properties.stackNode; + + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { + + const param = params[ i ]; + + let start = null, end = null, name = null, type = null, condition = null, update = null; + + if ( param.isNode ) { + + type = 'int'; + name = this.getVarName( i ); + start = '0'; + end = param.build( builder, type ); + condition = '<'; + + } else { + + type = param.type || 'int'; + name = param.name || this.getVarName( i ); + start = param.start; + end = param.end; + condition = param.condition; + update = param.update; + + if ( typeof start === 'number' ) start = start.toString(); + else if ( start && start.isNode ) start = start.build( builder, type ); + + if ( typeof end === 'number' ) end = end.toString(); + else if ( end && end.isNode ) end = end.build( builder, type ); + + if ( start !== undefined && end === undefined ) { + + start = start + ' - 1'; + end = '0'; + condition = '>='; + + } else if ( end !== undefined && start === undefined ) { + + start = '0'; + condition = '<'; + + } + + if ( condition === undefined ) { + + if ( Number( start ) > Number( end ) ) { + + condition = '>='; + + } else { + + condition = '<'; + + } + + } + + } + + const internalParam = { start, end, condition }; + + // + + const startSnippet = internalParam.start; + const endSnippet = internalParam.end; + + let declarationSnippet = ''; + let conditionalSnippet = ''; + let updateSnippet = ''; + + if ( ! update ) { + + if ( type === 'int' || type === 'uint' ) { + + if ( condition.includes( '<' ) ) update = '++'; + else update = '--'; + + } else { + + if ( condition.includes( '<' ) ) update = '+= 1.'; + else update = '-= 1.'; + + } + + } + + declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; + + conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; + updateSnippet += name + ' ' + update; + + const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; + + builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); + + } + + const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); + + const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; + + builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); + + } + + builder.addFlowTab(); + + return returnsSnippet; + + } + + } + + const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); + const Continue = () => expression( 'continue' ).append(); + const Break = () => expression( 'break' ).append(); + + addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); + + addNodeClass( 'LoopNode', LoopNode ); + const morphTextures = new WeakMap(); const morphVec4 = new Vector4(); @@ -60105,10 +61210,9 @@ var THREE = (async function (exports) { const width = int( size.width ); - for ( let i = 0; i < morphTargetsCount; i ++ ) { + loop( morphTargetsCount, ( { i } ) => { - const influence = referenceIndex( 'morphTargetInfluences', i, 'float' ); - const depth = int( i ); + const influence = reference( 'morphTargetInfluences', 'float' ).element( i ); if ( hasMorphPosition === true ) { @@ -60117,7 +61221,7 @@ var THREE = (async function (exports) { influence, stride, width, - depth, + depth: i, offset: int( 0 ) } ) ); @@ -60130,13 +61234,13 @@ var THREE = (async function (exports) { influence, stride, width, - depth, + depth: i, offset: int( 1 ) } ) ); } - } + } ); } @@ -60158,7 +61262,7 @@ var THREE = (async function (exports) { } - const morph = nodeProxy( MorphNode ); + const morphReference = nodeProxy( MorphNode ); addNodeClass( 'MorphNode', MorphNode ); @@ -60260,7 +61364,7 @@ var THREE = (async function (exports) { addNodeClass( 'LightingNode', LightingNode ); - let depthMaterial = null; + let overrideMaterial = null; class AnalyticLightNode extends LightingNode { @@ -60302,7 +61406,13 @@ var THREE = (async function (exports) { if ( shadowNode === null ) { - if ( depthMaterial === null ) depthMaterial = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ); + if ( overrideMaterial === null ) { + + overrideMaterial = builder.createNodeMaterial(); + overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); + overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode + + } const shadow = this.light.shadow; const rtt = builder.getRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); @@ -60390,8 +61500,10 @@ var THREE = (async function (exports) { */ // + const shadowColor = texture( rtt.texture, shadowCoord ); + this.rtt = rtt; - this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode ) ); + this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) ) ); this.shadowNode = shadowNode; @@ -60417,7 +61529,7 @@ var THREE = (async function (exports) { const currentOverrideMaterial = scene.overrideMaterial; - scene.overrideMaterial = depthMaterial; + scene.overrideMaterial = overrideMaterial; rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height ); @@ -60643,7 +61755,7 @@ var THREE = (async function (exports) { } const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) ); - const lightNodes = nodeProxy( LightsNode ); + const lightsNode = nodeProxy( LightsNode ); function addLightNode( lightClass, lightNodeClass ) { @@ -61021,8 +62133,6 @@ var THREE = (async function (exports) { const scope = this.scope; - if ( scope === ViewportNode.COORDINATE ) return; - let output = null; if ( scope === ViewportNode.RESOLUTION ) { @@ -61095,7 +62205,7 @@ var THREE = (async function (exports) { addNodeClass( 'ViewportNode', ViewportNode ); - const _size$1 = new Vector2(); + const _size$2 = new Vector2(); class ViewportTextureNode extends TextureNode { @@ -61121,16 +62231,16 @@ var THREE = (async function (exports) { updateBefore( frame ) { const renderer = frame.renderer; - renderer.getDrawingBufferSize( _size$1 ); + renderer.getDrawingBufferSize( _size$2 ); // const framebufferTexture = this.value; - if ( framebufferTexture.image.width !== _size$1.width || framebufferTexture.image.height !== _size$1.height ) { + if ( framebufferTexture.image.width !== _size$2.width || framebufferTexture.image.height !== _size$2.height ) { - framebufferTexture.image.width = _size$1.width; - framebufferTexture.image.height = _size$1.height; + framebufferTexture.image.width = _size$2.width; + framebufferTexture.image.height = _size$2.height; framebufferTexture.needsUpdate = true; } @@ -61171,9 +62281,6 @@ var THREE = (async function (exports) { if ( sharedDepthbuffer === null ) { sharedDepthbuffer = new DepthTexture(); - sharedDepthbuffer.minFilter = NearestMipmapNearestFilter; - sharedDepthbuffer.type = UnsignedIntType; - sharedDepthbuffer.format = DepthFormat; } @@ -61279,6 +62386,162 @@ var THREE = (async function (exports) { addNodeClass( 'ViewportDepthNode', ViewportDepthNode ); + class ClippingNode extends Node { + + constructor( scope = ClippingNode.DEFAULT ) { + + super(); + + this.scope = scope; + + } + + setup( builder ) { + + super.setup( builder ); + + const clippingContext = builder.clippingContext; + const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext; + + const numClippingPlanes = globalClippingCount + localClippingCount; + const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes; + + if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) { + + return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); + + } else { + + return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); + + } + + } + + setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + const distanceToPlane = property( 'float', 'distanceToPlane' ); + const distanceGradient = property( 'float', 'distanceToGradient' ); + + const clipOpacity = property( 'float', 'clipOpacity' ); + + clipOpacity.assign( 1 ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) ); + + clipOpacity.equal( 0.0 ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const unionClipOpacity = property( 'float', 'unionclipOpacity' ); + + unionClipOpacity.assign( 1 ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() ); + + } ); + + clipOpacity.mulAssign( unionClipOpacity.oneMinus() ); + + } + + diffuseColor.a.mulAssign( clipOpacity ); + + diffuseColor.a.equal( 0.0 ).discard(); + + } )(); + + } + + setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + positionView.dot( plane.xyz ).greaterThan( plane.w ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const clipped = property( 'bool', 'clipped' ); + + clipped.assign( true ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) ); + + } ); + + clipped.discard(); + } + + } )(); + + } + + } + + ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage'; + ClippingNode.DEFAULT = 'default'; + + const clipping = () => nodeObject( new ClippingNode() ); + + const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) ); + + class FrontFacingNode extends Node { + + constructor() { + + super( 'bool' ); + + this.isFrontFacingNode = true; + + } + + generate( builder ) { + + return builder.getFrontFacing(); + + } + + } + + const frontFacing = nodeImmutable( FrontFacingNode ); + const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); + + addNodeClass( 'FrontFacingNode', FrontFacingNode ); + const NodeMaterials = new Map(); class NodeMaterial extends ShaderMaterial { @@ -61312,6 +62575,7 @@ var THREE = (async function (exports) { this.positionNode = null; this.depthNode = null; + this.shadowNode = null; this.outputNode = null; @@ -61348,6 +62612,8 @@ var THREE = (async function (exports) { let resultNode; + const clippingNode = this.setupClipping( builder ); + if ( this.fragmentNode === null ) { if ( this.depthWrite === true ) this.setupDepth( builder ); @@ -61359,6 +62625,8 @@ var THREE = (async function (exports) { const outgoingLightNode = this.setupLighting( builder ); + if ( clippingNode !== null ) builder.stack.add( clippingNode ); + resultNode = this.setupOutput( builder, vec4( outgoingLightNode, diffuseColor.a ) ); // OUTPUT NODE @@ -61381,6 +62649,31 @@ var THREE = (async function (exports) { } + setupClipping( builder ) { + + const { globalClippingCount, localClippingCount } = builder.clippingContext; + + let result = null; + + if ( globalClippingCount || localClippingCount ) { + + if ( this.alphaToCoverage ) { + + // to be added to flow when the color/alpha value has been determined + result = clippingAlpha(); + + } else { + + builder.stack.add( clipping() ); + + } + + } + + return result; + + } + setupDepth( builder ) { const { renderer } = builder; @@ -61416,13 +62709,13 @@ var THREE = (async function (exports) { if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) { - morph( object ).append(); + morphReference( object ).append(); } if ( object.isSkinnedMesh === true ) { - skinning( object ).append(); + skinningReference( object ).append(); } @@ -61494,13 +62787,13 @@ var THREE = (async function (exports) { const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize(); - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } else { const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal; - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } @@ -61548,15 +62841,15 @@ var THREE = (async function (exports) { } - let lightsNode = this.lightsNode || builder.lightsNode; + let lightsN = this.lightsNode || builder.lightsNode; if ( materialLightsNode.length > 0 ) { - lightsNode = lightNodes( [ ...lightsNode.lightNodes, ...materialLightsNode ] ); + lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] ); } - return lightsNode; + return lightsN; } @@ -61755,6 +63048,7 @@ var THREE = (async function (exports) { this.positionNode = source.positionNode; this.depthNode = source.depthNode; + this.shadowNode = source.shadowNode; this.outputNode = source.outputNode; @@ -62114,23 +63408,45 @@ var THREE = (async function (exports) { } - generate( builder ) { + generate( builder, output ) { const type = this.getNodeType( builder ); const context$1 = { tempWrite: false }; + const nodeData = builder.getDataFromNode( this ); + + if ( nodeData.nodeProperty !== undefined ) { + + return nodeData.nodeProperty; + + } + const { ifNode, elseNode } = this; - const needsProperty = ifNode.getNodeType( builder ) !== 'void' || ( elseNode && elseNode.getNodeType( builder ) !== 'void' ); - const nodeProperty = needsProperty ? property( type ).build( builder ) : ''; + const needsOutput = output !== 'void'; + const nodeProperty = needsOutput ? property( type ).build( builder ) : ''; + + nodeData.nodeProperty = nodeProperty; const nodeSnippet = context( this.condNode/*, context*/ ).build( builder, 'bool' ); builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab(); - let ifSnippet = context( this.ifNode, context$1 ).build( builder, type ); + let ifSnippet = context( ifNode, context$1 ).build( builder, type ); + + if ( ifSnippet ) { + + if ( needsOutput ) { - ifSnippet = needsProperty ? nodeProperty + ' = ' + ifSnippet + ';' : ifSnippet; + ifSnippet = nodeProperty + ' = ' + ifSnippet + ';'; + + } else { + + ifSnippet = 'return ' + ifSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' ); @@ -62139,7 +63455,20 @@ var THREE = (async function (exports) { builder.addFlowCode( ' else {\n\n' ).addFlowTab(); let elseSnippet = context( elseNode, context$1 ).build( builder, type ); - elseSnippet = nodeProperty ? nodeProperty + ' = ' + elseSnippet + ';' : elseSnippet; + + if ( elseSnippet ) { + + if ( needsOutput ) { + + elseSnippet = nodeProperty + ' = ' + elseSnippet + ';'; + + } else { + + elseSnippet = 'return ' + elseSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' ); @@ -62149,7 +63478,7 @@ var THREE = (async function (exports) { } - return nodeProperty; + return builder.format( nodeProperty, type, output ); } @@ -62352,6 +63681,8 @@ var THREE = (async function (exports) { this.fogNode = null; this.toneMappingNode = null; + this.clippingContext = null; + this.vertexShader = null; this.fragmentShader = null; this.computeShader = null; @@ -62730,7 +64061,7 @@ var THREE = (async function (exports) { isReference( type ) { - return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture'; + return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture'; } @@ -62740,12 +64071,6 @@ var THREE = (async function (exports) { } - /** @deprecated, r152 */ - getTextureEncodingFromMap( map ) { - return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - getTextureColorSpaceFromMap( map ) { let colorSpace; @@ -62789,7 +64114,7 @@ var THREE = (async function (exports) { getVectorType( type ) { if ( type === 'color' ) return 'vec3'; - if ( type === 'texture' ) return 'vec4'; + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) return 'vec4'; return type; @@ -62841,6 +64166,7 @@ var THREE = (async function (exports) { if ( vecNum !== null ) return Number( vecNum[ 1 ] ); if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; + if ( /mat2/.test( type ) === true ) return 4; if ( /mat3/.test( type ) === true ) return 9; if ( /mat4/.test( type ) === true ) return 16; @@ -63429,24 +64755,12 @@ var THREE = (async function (exports) { } - createNodeMaterial( type ) { + createNodeMaterial( type = 'NodeMaterial' ) { return createNodeMaterialFromType( type ); } - getPrimitiveType( type ) { - - let primitiveType; - - if ( type[ 0 ] === 'i' ) primitiveType = 'int'; - else if ( type[ 0 ] === 'u' ) primitiveType = 'uint'; - else primitiveType = 'float'; - - return primitiveType; - - } - format( snippet, fromType, toType ) { fromType = this.getVectorType( fromType ); @@ -63506,7 +64820,7 @@ var THREE = (async function (exports) { // convert a number value to vector type, e.g: // vec3( 1u ) -> vec3( float( 1u ) ) - snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`; + snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; } @@ -63567,7 +64881,7 @@ var THREE = (async function (exports) { updateBeforeNode( node ) { const updateType = node.getUpdateBeforeType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -63575,9 +64889,11 @@ var THREE = (async function (exports) { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.updateBefore( this ) !== false ) { - node.updateBefore( this ); + frameMap.set( node, this.frameId ); + + } } @@ -63587,9 +64903,11 @@ var THREE = (async function (exports) { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.updateBefore( this ) !== false ) { - node.updateBefore( this ); + renderMap.set( node, this.renderId ); + + } } @@ -63604,7 +64922,7 @@ var THREE = (async function (exports) { updateNode( node ) { const updateType = node.getUpdateType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -63612,9 +64930,11 @@ var THREE = (async function (exports) { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.update( this ) !== false ) { + + frameMap.set( node, this.frameId ); - node.update( this ); + } } @@ -63624,9 +64944,11 @@ var THREE = (async function (exports) { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.update( this ) !== false ) { + + renderMap.set( node, this.renderId ); - node.update( this ); + } } @@ -63778,6 +65100,85 @@ var THREE = (async function (exports) { addNodeClass( 'HashNode', HashNode ); + // remapping functions https://iquilezles.org/articles/functions/ + const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); + const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); + const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); + const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); + + + addNodeElement( 'parabola', parabola ); + addNodeElement( 'gain', gain ); + addNodeElement( 'pcurve', pcurve ); + addNodeElement( 'sinc', sinc ); + + // https://github.com/cabbibo/glsl-tri-noise-3d + + const tri = tslFn( ( [ x ] ) => { + + return x.fract().sub( .5 ).abs(); + + } ); + + const tri3 = tslFn( ( [ p ] ) => { + + return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); + + } ); + + const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => { + + const p = vec3( p_immutable ).toVar(); + const z = float( 1.4 ).toVar(); + const rz = float( 0.0 ).toVar(); + const bp = vec3( p ).toVar(); + + loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { + + const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); + p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); + bp.mulAssign( 1.8 ); + z.mulAssign( 1.5 ); + p.mulAssign( 1.2 ); + + const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); + rz.addAssign( t.div( z ) ); + bp.addAssign( 0.14 ); + + } ); + + return rz; + + } ); + + // layouts + + tri.setLayout( { + name: 'tri', + type: 'float', + inputs: [ + { name: 'x', type: 'float' } + ] + } ); + + tri3.setLayout( { + name: 'tri3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] + } ); + + triNoise3D.setLayout( { + name: 'triNoise3D', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'spd', type: 'float' }, + { name: 'time', type: 'float' } + ] + } ); + let discardExpression; class DiscardNode extends CondNode { @@ -63890,197 +65291,6 @@ var THREE = (async function (exports) { addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode ); - class LoopNode extends Node { - - constructor( params = [] ) { - - super(); - - this.params = params; - - } - - getVarName( index ) { - - return String.fromCharCode( 'i'.charCodeAt() + index ); - - } - - getProperties( builder ) { - - const properties = builder.getNodeProperties( this ); - - if ( properties.stackNode !== undefined ) return properties; - - // - - const inputs = {}; - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - const param = this.params[ i ]; - - const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); - const type = ( param.isNode !== true && param.type ) || 'int'; - - inputs[ name ] = expression( name, type ); - - } - - properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); - properties.stackNode = builder.removeStack(); - - return properties; - - } - - getNodeType( builder ) { - - const { returnsNode } = this.getProperties( builder ); - - return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; - - } - - setup( builder ) { - - // setup properties - - this.getProperties( builder ); - - } - - generate( builder ) { - - const properties = this.getProperties( builder ); - - const contextData = { tempWrite: false }; - - const params = this.params; - const stackNode = properties.stackNode; - - for ( let i = 0, l = params.length - 1; i < l; i ++ ) { - - const param = params[ i ]; - - let start = null, end = null, name = null, type = null, condition = null, update = null; - - if ( param.isNode ) { - - type = 'int'; - name = this.getVarName( i ); - start = '0'; - end = param.build( builder, type ); - condition = '<'; - - } else { - - type = param.type || 'int'; - name = param.name || this.getVarName( i ); - start = param.start; - end = param.end; - condition = param.condition; - update = param.update; - - if ( typeof start === 'number' ) start = start.toString(); - else if ( start && start.isNode ) start = start.build( builder, type ); - - if ( typeof end === 'number' ) end = end.toString(); - else if ( end && end.isNode ) end = end.build( builder, type ); - - if ( start !== undefined && end === undefined ) { - - start = start + ' - 1'; - end = '0'; - condition = '>='; - - } else if ( end !== undefined && start === undefined ) { - - start = '0'; - condition = '<'; - - } - - if ( condition === undefined ) { - - if ( Number( start ) > Number( end ) ) { - - condition = '>='; - - } else { - - condition = '<'; - - } - - } - - } - - const internalParam = { start, end, condition }; - - // - - const startSnippet = internalParam.start; - const endSnippet = internalParam.end; - - let declarationSnippet = ''; - let conditionalSnippet = ''; - let updateSnippet = ''; - - if ( ! update ) { - - if ( type === 'int' ) { - - if ( condition.includes( '<' ) ) update = '++'; - else update = '--'; - - } else { - - if ( condition.includes( '<' ) ) update = '+= 1'; - else update = '-= 1'; - - } - - } - - declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; - - conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; - updateSnippet += name + ' ' + update; - - const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; - - builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); - - } - - const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); - - const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; - - builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); - - } - - builder.addFlowTab(); - - return returnsSnippet; - - } - - } - - const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); - - addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); - - addNodeClass( 'LoopNode', LoopNode ); - class MatcapUVNode extends TempNode { constructor() { @@ -64372,17 +65582,9 @@ var THREE = (async function (exports) { const { uvNode, rotationNode, centerNode } = this; - const cosAngle = rotationNode.cos(); - const sinAngle = rotationNode.sin(); - const vector = uvNode.sub( centerNode ); - const rotatedVector = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( vector )? - vec2( cosAngle, sinAngle ).dot( vector ), - vec2( sinAngle.negate(), cosAngle ).dot( vector ) - ); - - return rotatedVector.add( centerNode ); + return vector.rotate( rotationNode ).add( centerNode ); } @@ -64394,6 +65596,62 @@ var THREE = (async function (exports) { addNodeClass( 'RotateUVNode', RotateUVNode ); + class RotateNode extends TempNode { + + constructor( positionNode, rotationNode ) { + + super(); + + this.positionNode = positionNode; + this.rotationNode = rotationNode; + + } + + getNodeType( builder ) { + + return this.positionNode.getNodeType( builder ); + + } + + setup( builder ) { + + const { rotationNode, positionNode } = this; + + const nodeType = this.getNodeType( builder ); + + if ( nodeType === 'vec2' ) { + + const cosAngle = rotationNode.cos(); + const sinAngle = rotationNode.sin(); + + const rotationMatrix = mat2( + cosAngle, sinAngle, + sinAngle.negate(), cosAngle + ); + + return rotationMatrix.mul( positionNode ); + + } else { + + const rotation = rotationNode; + const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + + return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz; + + } + + } + + } + + const rotate = nodeProxy( RotateNode ); + + addNodeElement( 'rotate', rotate ); + + addNodeClass( 'RotateNode', RotateNode ); + class SpriteSheetUVNode extends Node { constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { @@ -64430,6 +65688,92 @@ var THREE = (async function (exports) { addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode ); + class StorageArrayElementNode extends ArrayElementNode { + + constructor( storageBufferNode, indexNode ) { + + super( storageBufferNode, indexNode ); + + this.isStorageArrayElementNode = true; + + } + + set storageBufferNode( value ) { + + this.node = value; + + } + + get storageBufferNode() { + + return this.node; + + } + + setup( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + if ( ! this.node.instanceIndex && this.node.bufferObject === true ) { + + builder.setupPBO( this.node ); + + } + + } + + return super.setup( builder ); + + } + + generate( builder, output ) { + + let snippet; + + const isAssignContext = builder.context.assign; + + // + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + const { node } = this; + + if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) { + + snippet = builder.generatePBO( this ); + + } else { + + snippet = node.build( builder ); + + } + + } else { + + snippet = super.generate( builder ); + + } + + if ( isAssignContext !== true ) { + + const type = this.getNodeType( builder ); + + snippet = builder.format( snippet, type, output ); + + } + + return snippet; + + } + + } + + const storageElement = nodeProxy( StorageArrayElementNode ); + + addNodeElement( 'storageElement', storageElement ); + + addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode ); + class TriplanarTexturesNode extends Node { constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { @@ -64484,6 +65828,225 @@ var THREE = (async function (exports) { addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode ); + const _reflectorPlane = new Plane(); + const _normal = new Vector3(); + const _reflectorWorldPosition = new Vector3(); + const _cameraWorldPosition = new Vector3(); + const _rotationMatrix = new Matrix4(); + const _lookAtPosition = new Vector3( 0, 0, - 1 ); + const clipPlane = new Vector4(); + + const _view = new Vector3(); + const _target = new Vector3(); + const _q = new Vector4(); + + const _size$1 = new Vector2(); + + const _defaultRT = new RenderTarget(); + const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y ); + + let _inReflector = false; + + class ReflectorNode extends TextureNode { + + constructor( parameters = {} ) { + + super( _defaultRT.texture, _defaultUV ); + + const { + target = new Object3D(), + resolution = 1, + generateMipmaps = false, + bounces = true + } = parameters; + + // + + this.target = target; + this.resolution = resolution; + this.generateMipmaps = generateMipmaps; + this.bounces = bounces; + + this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + + this.virtualCameras = new WeakMap(); + this.renderTargets = new WeakMap(); + + + } + + _updateResolution( renderTarget, renderer ) { + + const resolution = this.resolution; + + renderer.getDrawingBufferSize( _size$1 ); + + renderTarget.setSize( Math.round( _size$1.width * resolution ), Math.round( _size$1.height * resolution ) ); + + } + + setup( builder ) { + + this._updateResolution( _defaultRT, builder.renderer ); + + return super.setup( builder ); + + } + + getTextureNode() { + + return this.textureNode; + + } + + getVirtualCamera( camera ) { + + let virtualCamera = this.virtualCameras.get( camera ); + + if ( virtualCamera === undefined ) { + + virtualCamera = camera.clone(); + + this.virtualCameras.set( camera, virtualCamera ); + + } + + return virtualCamera; + + } + + getRenderTarget( camera ) { + + let renderTarget = this.renderTargets.get( camera ); + + if ( renderTarget === undefined ) { + + renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); + + if ( this.generateMipmaps === true ) { + + renderTarget.texture.minFilter = LinearMipMapLinearFilter; + renderTarget.texture.generateMipmaps = true; + + } + + this.renderTargets.set( camera, renderTarget ); + + } + + return renderTarget; + + } + + updateBefore( frame ) { + + if ( this.bounces === false && _inReflector ) return false; + + _inReflector = true; + + const { scene, camera, renderer, material } = frame; + const { target } = this; + + const virtualCamera = this.getVirtualCamera( camera ); + const renderTarget = this.getRenderTarget( virtualCamera ); + + renderer.getDrawingBufferSize( _size$1 ); + + this._updateResolution( renderTarget, renderer ); + + // + + _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); + _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); + + _rotationMatrix.extractRotation( target.matrixWorld ); + + _normal.set( 0, 0, 1 ); + _normal.applyMatrix4( _rotationMatrix ); + + _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); + + // Avoid rendering when reflector is facing away + + if ( _view.dot( _normal ) > 0 ) return; + + _view.reflect( _normal ).negate(); + _view.add( _reflectorWorldPosition ); + + _rotationMatrix.extractRotation( camera.matrixWorld ); + + _lookAtPosition.set( 0, 0, - 1 ); + _lookAtPosition.applyMatrix4( _rotationMatrix ); + _lookAtPosition.add( _cameraWorldPosition ); + + _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); + _target.reflect( _normal ).negate(); + _target.add( _reflectorWorldPosition ); + + // + + virtualCamera.coordinateSystem = camera.coordinateSystem; + virtualCamera.position.copy( _view ); + virtualCamera.up.set( 0, 1, 0 ); + virtualCamera.up.applyMatrix4( _rotationMatrix ); + virtualCamera.up.reflect( _normal ); + virtualCamera.lookAt( _target ); + + virtualCamera.near = camera.near; + virtualCamera.far = camera.far; + + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); + + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); + _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); + + clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); + + const projectionMatrix = virtualCamera.projectionMatrix; + + _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; + _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; + _q.z = - 1.0; + _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; + + // Calculate the scaled plane vector + clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); + + const clipBias = 0; + + // Replacing the third row of the projection matrix + projectionMatrix.elements[ 2 ] = clipPlane.x; + projectionMatrix.elements[ 6 ] = clipPlane.y; + projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias; + projectionMatrix.elements[ 14 ] = clipPlane.w; + + // + + this.value = renderTarget.texture; + + material.visible = false; + + const currentRenderTarget = renderer.getRenderTarget(); + + renderer.setRenderTarget( renderTarget ); + + renderer.render( scene, virtualCamera ); + + renderer.setRenderTarget( currentRenderTarget ); + + material.visible = true; + + _inReflector = false; + + } + + } + + const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); + class BitangentNode extends Node { constructor( scope = BitangentNode.LOCAL ) { @@ -64564,6 +66127,11 @@ var THREE = (async function (exports) { addNodeClass( 'BitangentNode', BitangentNode ); + const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); + + const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/; + const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) ); + class VertexColorNode extends AttributeNode { constructor( index = 0 ) { @@ -64787,6 +66355,11 @@ var THREE = (async function (exports) { this.isStorageBufferNode = true; + this.bufferObject = false; + + this._attribute = null; + this._varying = null; + } getInputType( /*builder*/ ) { @@ -64795,9 +66368,46 @@ var THREE = (async function (exports) { } + element( indexNode ) { + + return storageElement( this, indexNode ); + + } + + setBufferObject( value ) { + + this.bufferObject = value; + + return this; + + } + + generate( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) ) return super.generate( builder ); + + const nodeType = this.getNodeType( builder ); + + if ( this._attribute === null ) { + + this._attribute = bufferAttribute( this.value ); + this._varying = varying( this._attribute ); + + } + + + const output = this._varying.build( builder, nodeType ); + + builder.registerTransform( output, this._attribute ); + + return output; + + } + } const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); + const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); addNodeClass( 'StorageBufferNode', StorageBufferNode ); @@ -64813,15 +66423,68 @@ var THREE = (async function (exports) { } - getNodeType( /*builder*/ ) { + getInputType( /*builder*/ ) { + + return 'storageTexture'; + + } - return 'void'; + setup( builder ) { + + super.setup( builder ); + + const properties = builder.getNodeProperties( this ); + properties.storeNode = this.storeNode; + + } + + generate( builder, output ) { + + let snippet; + + if ( this.storeNode !== null ) { + + snippet = this.generateStore( builder ); + + } else { + + snippet = super.generate( builder, output ); + + } + + return snippet; + + } + + generateStore( builder ) { + + const properties = builder.getNodeProperties( this ); + + const { uvNode, storeNode } = properties; + + const textureProperty = super.generate( builder, 'property' ); + const uvSnippet = uvNode.build( builder, 'uvec2' ); + const storeSnippet = storeNode.build( builder, 'vec4' ); + + const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); + + builder.addLineFlowCode( snippet ); } } - const textureStore = nodeProxy( TextureStoreNode ); + const textureStoreBase = nodeProxy( TextureStoreNode ); + + const textureStore = ( value, uvNode, storeNode ) => { + + const node = textureStoreBase( value, uvNode, storeNode ); + + if ( storeNode !== null ) node.append(); + + return node; + + }; addNodeClass( 'TextureStoreNode', TextureStoreNode ); @@ -64855,6 +66518,13 @@ var THREE = (async function (exports) { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'burnColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const DodgeNode = tslFn( ( { base, blend } ) => { @@ -64863,6 +66533,13 @@ var THREE = (async function (exports) { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'dodgeColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const ScreenNode = tslFn( ( { base, blend } ) => { @@ -64871,14 +66548,29 @@ var THREE = (async function (exports) { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'screenColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const OverlayNode = tslFn( ( { base, blend } ) => { const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() ); + //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) ); return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'overlayColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); class BlendModeNode extends TempNode { @@ -64942,29 +66634,6 @@ var THREE = (async function (exports) { addNodeClass( 'BlendModeNode', BlendModeNode ); - class FrontFacingNode extends Node { - - constructor() { - - super( 'bool' ); - - this.isFrontFacingNode = true; - - } - - generate( builder ) { - - return builder.getFrontFacing(); - - } - - } - - const frontFacing = nodeImmutable( FrontFacingNode ); - const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); - - addNodeClass( 'FrontFacingNode', FrontFacingNode ); - // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf @@ -65134,9 +66803,12 @@ var THREE = (async function (exports) { const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 ); const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma ); + const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); + addNodeElement( 'saturation', saturation ); addNodeElement( 'vibrance', vibrance ); addNodeElement( 'hue', hue ); + addNodeElement( 'threshold', threshold ); addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode ); @@ -65227,8 +66899,6 @@ var THREE = (async function (exports) { const normalMap = nodeProxy( NormalMapNode ); - const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); - addNodeElement( 'normalMap', normalMap ); addNodeClass( 'NormalMapNode', NormalMapNode ); @@ -65331,11 +67001,52 @@ var THREE = (async function (exports) { } ); + + + const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); + const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); + + const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => { + + const x = vec3( x_immutable ).toVar(); + const x2 = vec3( x.mul( x ) ).toVar(); + const x4 = vec3( x2.mul( x2 ) ).toVar(); + + return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); + + } ); + + const AGXToneMappingNode = tslFn( ( { color, exposure } ) => { + + const colortone = vec3( color ).toVar(); + const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); + const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); + const AgxMinEv = float( - 12.47393 ); + const AgxMaxEv = float( 4.026069 ); + colortone.mulAssign( exposure ); + colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); + colortone.assign( AgXInsetMatrix.mul( colortone ) ); + colortone.assign( max$1( colortone, 1e-10 ) ); + colortone.assign( log2( colortone ) ); + colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + colortone.assign( agxDefaultContrastApprox( colortone ) ); + colortone.assign( AgXOutsetMatrix.mul( colortone ) ); + colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); + colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + + return colortone; + + } ); + + const toneMappingLib = { [ LinearToneMapping ]: LinearToneMappingNode, [ ReinhardToneMapping ]: ReinhardToneMappingNode, [ CineonToneMapping ]: OptimizedCineonToneMappingNode, - [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode + [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode, + [ AgXToneMapping ]: AGXToneMappingNode }; class ToneMappingNode extends TempNode { @@ -65392,19 +67103,19 @@ var THREE = (async function (exports) { addNodeClass( 'ToneMappingNode', ToneMappingNode ); - let sharedFramebuffer = null; + let _sharedFramebuffer = null; class ViewportSharedTextureNode extends ViewportTextureNode { constructor( uvNode = viewportTopLeft, levelNode = null ) { - if ( sharedFramebuffer === null ) { + if ( _sharedFramebuffer === null ) { - sharedFramebuffer = new FramebufferTexture(); + _sharedFramebuffer = new FramebufferTexture(); } - super( uvNode, levelNode, sharedFramebuffer ); + super( uvNode, levelNode, _sharedFramebuffer ); } @@ -65416,6 +67127,179 @@ var THREE = (async function (exports) { addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode ); + class PassTextureNode extends TextureNode { + + constructor( passNode, texture ) { + + super( texture ); + + this.passNode = passNode; + + this.setUpdateMatrix( false ); + + } + + setup( builder ) { + + this.passNode.build( builder ); + + return super.setup( builder ); + + } + + clone() { + + return new this.constructor( this.passNode, this.value ); + + } + + } + + class PassNode extends TempNode { + + constructor( scope, scene, camera ) { + + super( 'vec4' ); + + this.scope = scope; + this.scene = scene; + this.camera = camera; + + this._pixelRatio = 1; + this._width = 1; + this._height = 1; + + const depthTexture = new DepthTexture(); + depthTexture.isRenderTargetTexture = true; + //depthTexture.type = FloatType; + depthTexture.name = 'PostProcessingDepth'; + + const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); + renderTarget.texture.name = 'PostProcessing'; + renderTarget.depthTexture = depthTexture; + + this.renderTarget = renderTarget; + + this.updateBeforeType = NodeUpdateType.FRAME; + + this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); + this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); + + this._depthNode = null; + this._cameraNear = uniform( 0 ); + this._cameraFar = uniform( 0 ); + + this.isPassNode = true; + + } + + isGlobal() { + + return true; + + } + + getTextureNode() { + + return this._textureNode; + + } + + getTextureDepthNode() { + + return this._depthTextureNode; + + } + + getDepthNode() { + + if ( this._depthNode === null ) { + + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; + + this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + + } + + return this._depthNode; + + } + + setup() { + + return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + + } + + updateBefore( frame ) { + + const { renderer } = frame; + const { scene, camera } = this; + + this._pixelRatio = renderer.getPixelRatio(); + + const size = renderer.getSize( new Vector2() ); + + this.setSize( size.width, size.height ); + + const currentToneMapping = renderer.toneMapping; + const currentToneMappingNode = renderer.toneMappingNode; + const currentRenderTarget = renderer.getRenderTarget(); + + this._cameraNear.value = camera.near; + this._cameraFar.value = camera.far; + + renderer.toneMapping = NoToneMapping; + renderer.toneMappingNode = null; + renderer.setRenderTarget( this.renderTarget ); + + renderer.render( scene, camera ); + + renderer.toneMapping = currentToneMapping; + renderer.toneMappingNode = currentToneMappingNode; + renderer.setRenderTarget( currentRenderTarget ); + + } + + setSize( width, height ) { + + this._width = width; + this._height = height; + + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; + + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + + } + + setPixelRatio( pixelRatio ) { + + this._pixelRatio = pixelRatio; + + this.setSize( this._width, this._height ); + + } + + dispose() { + + this.renderTarget.dispose(); + + } + + + } + + PassNode.COLOR = 'color'; + PassNode.DEPTH = 'depth'; + + const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); + const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); + const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + + addNodeClass( 'PassNode', PassNode ); + // Helper for passes that need to fill the viewport with a single quad. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); @@ -65453,9 +67337,9 @@ var THREE = (async function (exports) { } - render( renderer ) { + async renderAsync( renderer ) { - renderer.render( this._mesh, _camera ); + await renderer.renderAsync( this._mesh, _camera ); } @@ -65471,6 +67355,12 @@ var THREE = (async function (exports) { } + get render() { + + return this.renderAsync; + + } + } // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that @@ -65483,7 +67373,7 @@ var THREE = (async function (exports) { constructor( textureNode, sigma = 2 ) { - super( textureNode ); + super( 'vec4' ); this.textureNode = textureNode; this.sigma = sigma; @@ -65498,6 +67388,8 @@ var THREE = (async function (exports) { this._verticalRT = new RenderTarget(); this._verticalRT.texture.name = 'GaussianBlurNode.vertical'; + this._textureNode = texturePass( this, this._verticalRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; this.resolution = new Vector2( 1, 1 ); @@ -65530,6 +67422,11 @@ var THREE = (async function (exports) { this.setSize( map.image.width, map.image.height ); + const textureType = map.type; + + this._horizontalRT.texture.type = textureType; + this._verticalRT.texture.type = textureType; + // horizontal renderer.setRenderTarget( this._horizontalRT ); @@ -65554,6 +67451,12 @@ var THREE = (async function (exports) { } + getTextureNode() { + + return this._textureNode; + + } + setup( builder ) { const textureNode = this.textureNode; @@ -65602,7 +67505,7 @@ var THREE = (async function (exports) { // - const material = this._material || ( this._material = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const material = this._material || ( this._material = builder.createNodeMaterial() ); material.fragmentNode = blur(); // @@ -65612,7 +67515,7 @@ var THREE = (async function (exports) { // - return texture( this._verticalRT.texture ); + return this._textureNode; } @@ -65654,10 +67557,18 @@ var THREE = (async function (exports) { this._oldRT = new RenderTarget(); this._oldRT.texture.name = 'AfterImageNode.old'; + this._textureNode = texturePass( this, this._compRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; } + getTextureNode() { + + return this._textureNode; + + } + setSize( width, height ) { this._compRT.setSize( width, height ); @@ -65670,6 +67581,12 @@ var THREE = (async function (exports) { const { renderer } = frame; const textureNode = this.textureNode; + const map = textureNode.value; + + const textureType = map.type; + + this._compRT.texture.type = textureType; + this._oldRT.texture.type = textureType; const currentRenderTarget = renderer.getRenderTarget(); const currentTexture = textureNode.value; @@ -65686,7 +67603,6 @@ var THREE = (async function (exports) { this._compRT = temp; // set size before swapping fails - const map = currentTexture; this.setSize( map.image.width, map.image.height ); renderer.setRenderTarget( currentRenderTarget ); @@ -65734,7 +67650,7 @@ var THREE = (async function (exports) { // - const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() ); materialComposed.fragmentNode = afterImg(); quadMeshComp.material = materialComposed; @@ -65746,7 +67662,7 @@ var THREE = (async function (exports) { // - return texture( this._compRT.texture ); + return this._textureNode; } @@ -65756,177 +67672,138 @@ var THREE = (async function (exports) { addNodeElement( 'afterImage', afterImage ); - class PassTextureNode extends TextureNode { + const quadMesh = new QuadMesh(); - constructor( passNode, texture ) { + class AnamorphicNode extends TempNode { - super( texture ); + constructor( textureNode, tresholdNode, scaleNode, samples ) { - this.passNode = passNode; + super( 'vec4' ); - this.setUpdateMatrix( false ); + this.textureNode = textureNode; + this.tresholdNode = tresholdNode; + this.scaleNode = scaleNode; + this.colorNode = vec3( 0.1, 0.0, 1.0 ); + this.samples = samples; + this.resolution = new Vector2( 1, 1 ); - } + this._renderTarget = new RenderTarget(); + this._renderTarget.texture.name = 'anamorphic'; - setup( builder ) { + this._invSize = uniform( new Vector2() ); - this.passNode.build( builder ); + this._textureNode = texturePass( this, this._renderTarget.texture ); - return super.setup( builder ); + this.updateBeforeType = NodeUpdateType.RENDER; } - clone() { + getTextureNode() { - return new this.constructor( this.passNode, this.value ); + return this._textureNode; } - } - - class PassNode extends TempNode { - - constructor( scope, scene, camera ) { - - super( 'vec4' ); - - this.scope = scope; - this.scene = scene; - this.camera = camera; - - this._pixelRatio = 1; - this._width = 1; - this._height = 1; - - const depthTexture = new DepthTexture(); - depthTexture.isRenderTargetTexture = true; - depthTexture.type = FloatType; - depthTexture.name = 'PostProcessingDepth'; - - const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); - renderTarget.texture.name = 'PostProcessing'; - renderTarget.depthTexture = depthTexture; - - this.renderTarget = renderTarget; - - this.updateBeforeType = NodeUpdateType.FRAME; - - this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); - this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); - - this._depthNode = null; - this._cameraNear = uniform( 0 ); - this._cameraFar = uniform( 0 ); - - this.isPassNode = true; + setSize( width, height ) { - } + this._invSize.value.set( 1 / width, 1 / height ); - isGlobal() { + width = Math.max( Math.round( width * this.resolution.x ), 1 ); + height = Math.max( Math.round( height * this.resolution.y ), 1 ); - return true; + this._renderTarget.setSize( width, height ); } - getTextureNode() { + updateBefore( frame ) { - return this._textureNode; + const { renderer } = frame; - } + const textureNode = this.textureNode; + const map = textureNode.value; - getTextureDepthNode() { + this._renderTarget.texture.type = map.type; - return this._depthTextureNode; + const currentRenderTarget = renderer.getRenderTarget(); + const currentTexture = textureNode.value; - } + quadMesh.material = this._material; - getDepthNode() { + this.setSize( map.image.width, map.image.height ); - if ( this._depthNode === null ) { + // render - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; + renderer.setRenderTarget( this._renderTarget ); - this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + quadMesh.render( renderer ); - } + // restore - return this._depthNode; + renderer.setRenderTarget( currentRenderTarget ); + textureNode.value = currentTexture; } - setup() { - - return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + setup( builder ) { - } + const textureNode = this.textureNode; - updateBefore( frame ) { + if ( textureNode.isTextureNode !== true ) { - const { renderer } = frame; - const { scene, camera } = this; + return vec4(); - this._pixelRatio = renderer.getPixelRatio(); + } - const size = renderer.getSize( new Vector2() ); + // - this.setSize( size.width, size.height ); + const uvNode = textureNode.uvNode || uv(); - const currentToneMapping = renderer.toneMapping; - const currentToneMappingNode = renderer.toneMappingNode; - const currentRenderTarget = renderer.getRenderTarget(); + const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } ); - this._cameraNear.value = camera.near; - this._cameraFar.value = camera.far; + const anamorph = tslFn( () => { - renderer.toneMapping = NoToneMapping; - renderer.toneMappingNode = null; - renderer.setRenderTarget( this.renderTarget ); + const samples = this.samples; + const halfSamples = Math.floor( samples / 2 ); - renderer.render( scene, camera ); + const total = vec3( 0 ).toVar(); - renderer.toneMapping = currentToneMapping; - renderer.toneMappingNode = currentToneMappingNode; - renderer.setRenderTarget( currentRenderTarget ); + loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => { - } + const softness = float( i ).abs().div( halfSamples ).oneMinus(); - setSize( width, height ) { + const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y ); + const color = sampleTexture( uv ); + const pass = threshold( color, this.tresholdNode ).mul( softness ); - this._width = width; - this._height = height; + total.addAssign( pass ); - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; + } ); - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + return total.mul( this.colorNode ); - } + } ); - setPixelRatio( pixelRatio ) { + // - this._pixelRatio = pixelRatio; + const material = this._material || ( this._material = builder.createNodeMaterial() ); + material.fragmentNode = anamorph(); - this.setSize( this._width, this._height ); + // - } + const properties = builder.getNodeProperties( this ); + properties.textureNode = textureNode; - dispose() { + // - this.renderTarget.dispose(); + return this._textureNode; } - } - PassNode.COLOR = 'color'; - PassNode.DEPTH = 'depth'; + const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ), nodeObject( threshold ), nodeObject( scale ), samples ) ); - const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); - const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); - - addNodeClass( 'PassNode', PassNode ); + addNodeElement( 'anamorphic', anamorphic ); class FunctionCallNode extends TempNode { @@ -66678,7 +68555,7 @@ var THREE = (async function (exports) { mixAssign( outputNode ) { - return this.mix( outputNode, this.colorNode ); + return mix( outputNode, this.colorNode, this ); } @@ -69208,13 +71085,7 @@ var THREE = (async function (exports) { const rotation = float( rotationNode || materialRotation ); - const cosAngle = rotation.cos(); - const sinAngle = rotation.sin(); - - const rotatedPosition = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( alignedPosition )? - vec2( cosAngle, sinAngle.negate() ).dot( alignedPosition ), - vec2( sinAngle, cosAngle ).dot( alignedPosition ) - ); + const rotatedPosition = alignedPosition.rotate( rotation ); mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw ); @@ -71419,6 +73290,8 @@ var THREE = (async function (exports) { this.width = 0; this.height = 0; + this.isRenderContext = true; + } } @@ -71443,19 +73316,8 @@ var THREE = (async function (exports) { } else { - let format, count; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - format = renderTarget.texture[ 0 ].format; - count = renderTarget.texture.length; - - } else { - - format = renderTarget.texture.format; - count = 1; - - } + const format = renderTarget.texture.format; + const count = renderTarget.count; attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; @@ -71497,10 +73359,11 @@ var THREE = (async function (exports) { class Textures extends DataMap { - constructor( backend, info ) { + constructor( renderer, backend, info ) { super(); + this.renderer = renderer; this.backend = backend; this.info = info; @@ -71513,19 +73376,8 @@ var THREE = (async function (exports) { const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); - let texture, textures; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - textures = renderTarget.texture; - texture = renderTarget.texture[ 0 ]; - - } else { - - textures = [ renderTarget.texture ]; - texture = renderTarget.texture; - - } + const texture = renderTarget.texture; + const textures = renderTarget.textures; const size = this.getSize( texture ); @@ -71538,8 +73390,8 @@ var THREE = (async function (exports) { if ( depthTexture === undefined ) { depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; + depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; + depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; depthTexture.image.width = mipWidth; depthTexture.image.height = mipHeight; @@ -71563,6 +73415,7 @@ var THREE = (async function (exports) { renderTargetData.depthTexture = depthTexture; renderTargetData.depth = renderTarget.depthBuffer; renderTargetData.stencil = renderTarget.stencilBuffer; + renderTargetData.renderTarget = renderTarget; if ( renderTargetData.sampleCount !== sampleCount ) { @@ -71644,6 +73497,25 @@ var THREE = (async function (exports) { // + if ( texture.isFramebufferTexture ) { + + const renderer = this.renderer; + const renderTarget = renderer.getRenderTarget(); + + if ( renderTarget ) { + + texture.type = renderTarget.texture.type; + + } else { + + texture.type = UnsignedByteType; + + } + + } + + // + const { width, height, depth } = this.getSize( texture ); options.width = width; @@ -71697,7 +73569,7 @@ var THREE = (async function (exports) { } - backend.updateTexture( texture, options ); + if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); @@ -71898,7 +73770,7 @@ var THREE = (async function (exports) { const backgroundMeshNode = context( vec4( backgroundNode ), { // @TODO: Add Texture2D support using node context getUV: () => normalWorld, - getTextureLevel: () => backgroundBlurriness + getTextureLevel: ( textureNode ) => backgroundBlurriness.mul( maxMipLevel( textureNode ) ) } ).mul( backgroundIntensity ); let viewProj = modelViewProjection(); @@ -71974,11 +73846,12 @@ var THREE = (async function (exports) { class NodeBuilderState { - constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes ) { + constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, transforms = [] ) { this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; this.computeShader = computeShader; + this.transforms = transforms; this.nodeAttributes = nodeAttributes; this.bindings = bindings; @@ -72124,6 +73997,7 @@ var THREE = (async function (exports) { nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene ); nodeBuilder.fogNode = this.getFogNode( renderObject.scene ); nodeBuilder.toneMappingNode = this.getToneMappingNode(); + nodeBuilder.clippingContext = renderObject.clippingContext; nodeBuilder.build(); nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); @@ -72174,7 +74048,7 @@ var THREE = (async function (exports) { nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); - computeData.nodeBuilderState = nodeBuilder; + computeData.nodeBuilderState = nodeBuilderState; } @@ -72191,7 +74065,8 @@ var THREE = (async function (exports) { nodeBuilder.getAttributesArray(), nodeBuilder.getBindings(), nodeBuilder.updateNodes, - nodeBuilder.updateBeforeNodes + nodeBuilder.updateBeforeNodes, + nodeBuilder.transforms ); } @@ -72534,6 +74409,8 @@ var THREE = (async function (exports) { this.depth = true; this.stencil = true; + this.clippingPlanes = []; + this.info = new Info(); // internals @@ -72577,9 +74454,13 @@ var THREE = (async function (exports) { this._renderObjectFunction = null; this._currentRenderObjectFunction = null; + this._handleObjectFunction = this._renderObjectDirect; + this._initialized = false; this._initPromise = null; + this._compilationPromises = null; + // backwards compatibility this.shadowMap = { @@ -72627,7 +74508,7 @@ var THREE = (async function (exports) { this._attributes = new Attributes( backend ); this._background = new Background( this, this._nodes ); this._geometries = new Geometries( this._attributes, this.info ); - this._textures = new Textures( backend, this.info ); + this._textures = new Textures( this, backend, this.info ); this._pipelines = new Pipelines( backend, this._nodes ); this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); @@ -72652,14 +74533,154 @@ var THREE = (async function (exports) { } - async compile( /*scene, camera*/ ) { + async compileAsync( scene, camera, targetScene = null ) { + + if ( this._initialized === false ) await this.init(); + + // preserve render tree + + const nodeFrame = this._nodes.nodeFrame; + + const previousRenderId = nodeFrame.renderId; + const previousRenderContext = this._currentRenderContext; + const previousRenderObjectFunction = this._currentRenderObjectFunction; + const previousCompilationPromises = this._compilationPromises; + + // + + const sceneRef = ( scene.isScene === true ) ? scene : _scene; + + if ( targetScene === null ) targetScene = scene; + + const renderTarget = this._renderTarget; + const renderContext = this._renderContexts.get( targetScene, camera, renderTarget ); + const activeMipmapLevel = this._activeMipmapLevel; + + const compilationPromises = []; + + this._currentRenderContext = renderContext; + this._currentRenderObjectFunction = this.renderObject; + + this._handleObjectFunction = this._createObjectPipeline; + + this._compilationPromises = compilationPromises; + + nodeFrame.renderId ++; + + // + + nodeFrame.update(); + + // + + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; + + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); + + // + + sceneRef.onBeforeRender( this, scene, camera, renderTarget ); + + // + + const renderList = this._renderLists.get( scene, camera ); + renderList.begin(); + + this._projectObject( scene, camera, 0, renderList ); + + // include lights from target scene + if ( targetScene !== scene ) { + + targetScene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + renderList.pushLight( object ); + + } + + } ); + + } + + renderList.finish(); + + // + + if ( renderTarget !== null ) { + + this._textures.updateRenderTarget( renderTarget, activeMipmapLevel ); + + const renderTargetData = this._textures.get( renderTarget ); + + renderContext.textures = renderTargetData.textures; + renderContext.depthTexture = renderTargetData.depthTexture; + + } else { + + renderContext.textures = null; + renderContext.depthTexture = null; + + } + + // + + this._nodes.updateScene( sceneRef ); + + // + + this._background.update( sceneRef, renderList, renderContext ); + + // process render lists + + const opaqueObjects = renderList.opaque; + const transparentObjects = renderList.transparent; + const lightsNode = renderList.lightsNode; + + if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode ); + if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode ); + + // restore render tree + + nodeFrame.renderId = previousRenderId; + + this._currentRenderContext = previousRenderContext; + this._currentRenderObjectFunction = previousRenderObjectFunction; + this._compilationPromises = previousCompilationPromises; + + this._handleObjectFunction = this._renderObjectDirect; + + // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete + + await Promise.all( compilationPromises ); } - async render( scene, camera ) { + async renderAsync( scene, camera ) { if ( this._initialized === false ) await this.init(); + const renderContext = this._renderContext( scene, camera ); + + await this.backend.resolveTimestampAsync( renderContext, 'render' ); + + } + + render( scene, camera ) { + + if ( this._initialized === false ) { + return; + + } + + this._renderContext( scene, camera ); + + } + + _renderContext( scene, camera ) { + // preserve render tree const nodeFrame = this._nodes.nodeFrame; @@ -72740,8 +74761,8 @@ var THREE = (async function (exports) { renderContext.scissorValue.width >>= activeMipmapLevel; renderContext.scissorValue.height >>= activeMipmapLevel; - renderContext.depth = this.depth; - renderContext.stencil = this.stencil; + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); // @@ -72778,6 +74799,8 @@ var THREE = (async function (exports) { renderContext.width = renderTargetData.width; renderContext.height = renderTargetData.height; renderContext.renderTarget = renderTarget; + renderContext.depth = renderTarget.depthBuffer; + renderContext.stencil = renderTarget.stencilBuffer; } else { @@ -72785,6 +74808,8 @@ var THREE = (async function (exports) { renderContext.depthTexture = null; renderContext.width = this.domElement.width; renderContext.height = this.domElement.height; + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; } @@ -72830,6 +74855,10 @@ var THREE = (async function (exports) { sceneRef.onAfterRender( this, scene, camera, renderTarget ); + // + + return renderContext; + } getMaxAnisotropy() { @@ -72990,6 +75019,8 @@ var THREE = (async function (exports) { this._scissorTest = boolean; + this.backend.setScissorTest( boolean ); + } getViewport( target ) { @@ -73093,19 +75124,45 @@ var THREE = (async function (exports) { clearColor() { - this.clear( true, false, false ); + return this.clear( true, false, false ); } clearDepth() { - this.clear( false, true, false ); + return this.clear( false, true, false ); } clearStencil() { - this.clear( false, false, true ); + return this.clear( false, false, true ); + + } + + async clearAsync( color = true, depth = true, stencil = true ) { + + if ( this._initialized === false ) await this.init(); + + this.clear( color, depth, stencil ); + + } + + clearColorAsync() { + + return this.clearAsync( true, false, false ); + + } + + clearDepthAsync() { + + return this.clearAsync( false, true, false ); + + } + + clearStencilAsync() { + + return this.clearAsync( false, false, true ); } @@ -73169,7 +75226,7 @@ var THREE = (async function (exports) { } - async compute( computeNodes ) { + async computeAsync( computeNodes ) { if ( this._initialized === false ) await this.init(); @@ -73181,10 +75238,12 @@ var THREE = (async function (exports) { this.info.calls ++; this.info.compute.calls ++; + this.info.compute.computeCalls ++; nodeFrame.renderId = this.info.calls; // + if ( this.info.autoReset === true ) this.info.resetCompute(); const backend = this.backend; const pipelines = this._pipelines; @@ -73236,12 +75295,20 @@ var THREE = (async function (exports) { backend.finishCompute( computeNodes ); + await this.backend.resolveTimestampAsync( computeNodes, 'compute' ); + // nodeFrame.renderId = previousRenderId; } + hasFeatureAsync( name ) { + + return this.backend.hasFeatureAsync( name ); + + } + hasFeature( name ) { return this.backend.hasFeature( name ); @@ -73415,6 +75482,7 @@ var THREE = (async function (exports) { renderObject( object, scene, camera, geometry, material, group, lightsNode ) { let overridePositionNode; + let overrideFragmentNode; // @@ -73436,6 +75504,45 @@ var THREE = (async function (exports) { } + if ( overrideMaterial.isShadowNodeMaterial ) { + + overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide; + + if ( material.shadowNode && material.shadowNode.isNode ) { + + overrideFragmentNode = overrideMaterial.fragmentNode; + overrideMaterial.fragmentNode = material.shadowNode; + + } + + if ( this.localClippingEnabled ) { + + if ( material.clipShadows ) { + + if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) { + + overrideMaterial.clippingPlanes = material.clippingPlanes; + overrideMaterial.needsUpdate = true; + + } + + if ( overrideMaterial.clipIntersection !== material.clipIntersection ) { + + overrideMaterial.clipIntersection = material.clipIntersection; + + } + + } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) { + + overrideMaterial.clippingPlanes = null; + overrideMaterial.needsUpdate = true; + + } + + } + + } + material = overrideMaterial; } @@ -73445,16 +75552,16 @@ var THREE = (async function (exports) { if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { material.side = BackSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id material.side = FrontSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode ); // use default pass id material.side = DoubleSide; } else { - this._renderObjectDirect( object, material, scene, camera, lightsNode ); + this._handleObjectFunction( object, material, scene, camera, lightsNode ); } @@ -73466,6 +75573,12 @@ var THREE = (async function (exports) { } + if ( overrideFragmentNode !== undefined ) { + + scene.overrideMaterial.fragmentNode = overrideFragmentNode; + + } + // object.onAfterRender( this, scene, camera, geometry, material, group ); @@ -73498,6 +75611,36 @@ var THREE = (async function (exports) { } + _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) { + + const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId ); + + // + + this._nodes.updateBefore( renderObject ); + + // + + this._nodes.updateForRender( renderObject ); + this._geometries.updateForRender( renderObject ); + this._bindings.updateForRender( renderObject ); + + this._pipelines.getForRender( renderObject, this._compilationPromises ); + + } + + get compute() { + + return this.computeAsync; + + } + + get compile() { + + return this.compileAsync; + + } + } class Binding { @@ -73532,24 +75675,6 @@ var THREE = (async function (exports) { } - function getVectorLength( count, vectorLength = 4 ) { - - const strideLength = getStrideLength( vectorLength ); - - const floatLength = strideLength * count; - - return getFloatLength( floatLength ); - - } - - function getStrideLength( vectorLength ) { - - const strideLength = 4; - - return vectorLength + ( ( strideLength - ( vectorLength % strideLength ) ) % strideLength ); - - } - class Buffer extends Binding { constructor( name, buffer = null ) { @@ -73596,6 +75721,26 @@ var THREE = (async function (exports) { } + let _id$2 = 0; + + class NodeUniformBuffer extends UniformBuffer { + + constructor( nodeUniform ) { + + super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + + } + class UniformsGroup extends UniformBuffer { constructor( name ) { @@ -73658,6 +75803,8 @@ var THREE = (async function (exports) { const uniform = this.uniforms[ i ]; + const { boundary, itemSize } = uniform; + // offset within a single chunk in bytes const chunkOffset = offset % GPU_CHUNK_BYTES; @@ -73665,23 +75812,23 @@ var THREE = (async function (exports) { // conformance tests - if ( chunkOffset !== 0 && ( remainingSizeInChunk - uniform.boundary ) < 0 ) { + if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) { // check for chunk overflow offset += ( GPU_CHUNK_BYTES - chunkOffset ); - } else if ( chunkOffset % uniform.boundary !== 0 ) { + } else if ( chunkOffset % boundary !== 0 ) { // check for correct alignment - offset += ( chunkOffset % uniform.boundary ); + offset += ( chunkOffset % boundary ); } uniform.offset = ( offset / this.bytesPerElement ); - offset += ( uniform.itemSize * this.bytesPerElement ); + offset += ( itemSize * this.bytesPerElement ); } @@ -74022,7 +76169,8 @@ var THREE = (async function (exports) { const glslMethods = { [ MathNode.ATAN2 ]: 'atan', - textureDimensions: 'textureSize' + textureDimensions: 'textureSize', + equals: 'equal' }; const precisionLib = { @@ -74032,7 +76180,8 @@ var THREE = (async function (exports) { }; const supports$1 = { - instance: true + instance: true, + swizzleAssign: true }; const defaultPrecisions = ` @@ -74049,6 +76198,7 @@ precision lowp sampler2DShadow; super( object, renderer, new GLSLNodeParser(), scene ); this.uniformGroups = {}; + this.transforms = []; } @@ -74096,6 +76246,130 @@ ${ flowData.code } } + setupPBO( storageBufferNode ) { + + const attribute = storageBufferNode.value; + + if ( attribute.pbo === undefined ) { + + const originalArray = attribute.array; + const numElements = attribute.count * attribute.itemSize; + + const { itemSize } = attribute; + let format = RedFormat; + + if ( itemSize === 2 ) { + + format = RGFormat; + + } else if ( itemSize === 3 ) { + + format = 6407; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization + + } else if ( itemSize === 4 ) { + + format = RGBAFormat; + + } + + const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) ); + let height = Math.ceil( ( numElements / itemSize ) / width ); + if ( width * height * itemSize < numElements ) height ++; // Ensure enough space + + const newSize = width * height * itemSize; + + const newArray = new Float32Array( newSize ); + + newArray.set( originalArray, 0 ); + + attribute.array = newArray; + + const pboTexture = new DataTexture( attribute.array, width, height, format, FloatType ); + pboTexture.needsUpdate = true; + pboTexture.isPBOTexture = true; + + const pbo = new UniformNode( pboTexture ); + pbo.setPrecision( 'high' ); + + attribute.pboNode = pbo; + attribute.pbo = pbo.value; + + this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + + } + + } + + generatePBO( storageArrayElementNode ) { + + const { node, indexNode } = storageArrayElementNode; + const attribute = node.value; + + if ( this.renderer.backend.has( attribute ) ) { + + const attributeData = this.renderer.backend.get( attribute ); + attributeData.pbo = attribute.pbo; + + } + + + const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + const textureName = this.getPropertyName( nodeUniform ); + + indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y + const indexSnippet = indexNode.build( this, 'uint' ); + + const elementNodeData = this.getDataFromNode( storageArrayElementNode ); + + let propertyName = elementNodeData.propertyName; + + if ( propertyName === undefined ) { + + // property element + + const nodeVar = this.getVarFromNode( storageArrayElementNode ); + + propertyName = this.getPropertyName( nodeVar ); + + // property size + + const bufferNodeData = this.getDataFromNode( node ); + + let propertySizeName = bufferNodeData.propertySizeName; + + if ( propertySizeName === undefined ) { + + propertySizeName = propertyName + 'Size'; + + this.getVarFromNode( node, propertySizeName, 'uint' ); + + this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` ); + + bufferNodeData.propertySizeName = propertySizeName; + + } + + // + + const { itemSize } = attribute; + + const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize ); + const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`; + + const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' ); + + // + + this.addLineFlowCode( `${ propertyName } = ${ snippet + channel }` ); + + elementNodeData.propertyName = propertyName; + + } + + return propertyName; + + } + generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) { if ( depthSnippet ) { @@ -74288,7 +76562,7 @@ ${ flowData.code } let snippet = ''; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { const attributes = this.getAttributesArray(); @@ -74355,10 +76629,11 @@ ${ flowData.code } const varyings = this.varyings; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { for ( const varying of varyings ) { + if ( shaderStage === 'compute' ) varying.needsInterpolation = true; const type = varying.type; const flat = type === 'int' || type === 'uint' ? 'flat ' : ''; @@ -74423,13 +76698,38 @@ ${ flowData.code } } - isFlipY() { return true; } + registerTransform( varyingName, attributeNode ) { + + this.transforms.push( { varyingName, attributeNode } ); + + } + + getTransforms( /* shaderStage */ ) { + + const transforms = this.transforms; + + let snippet = ''; + + for ( let i = 0; i < transforms.length; i ++ ) { + + const transform = transforms[ i ]; + + const attributeName = this.getPropertyName( transform.attributeNode ); + + snippet += `${ transform.varyingName } = ${ attributeName };\n\t`; + + } + + return snippet; + + } + _getGLSLUniformStruct( name, vars ) { return ` @@ -74465,6 +76765,9 @@ void main() { // vars ${shaderData.vars} + // transforms + ${shaderData.transforms} + // flow ${shaderData.flow} @@ -74567,6 +76870,7 @@ void main() { stageData.vars = this.getVars( shaderStage ); stageData.structs = this.getStructs( shaderStage ); stageData.codes = this.getCodes( shaderStage ); + stageData.transforms = this.getTransforms( shaderStage ); stageData.flow = flow; } @@ -74576,6 +76880,10 @@ void main() { this.vertexShader = this._getGLSLVertexCode( shadersData.vertex ); this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment ); + } else { + + this.computeShader = this._getGLSLVertexCode( shadersData.compute ); + } } @@ -74603,11 +76911,11 @@ void main() { } else if ( type === 'buffer' ) { - node.name = `NodeBuffer_${node.id}`; - - const buffer = new UniformBuffer( node.name, node.value ); + node.name = `NodeBuffer_${ node.id }`; + uniformNode.name = `buffer${ node.id }`; - uniformNode.name = `buffer${node.id}`; + const buffer = new NodeUniformBuffer( node ); + buffer.name = node.name; this.bindings[ shaderStage ].push( buffer ); @@ -74738,6 +77046,10 @@ void main() { // utils + resolveTimestampAsync( renderContext, type ) { } + + hasFeatureAsync( name ) { } // return Boolean + hasFeature( name ) { } // return Boolean getInstanceCount( renderObject ) { @@ -74764,6 +77076,8 @@ void main() { } + setScissorTest( boolean ) { } + getClearColor() { const renderer = this.renderer; @@ -74820,6 +77134,12 @@ void main() { } + has( object ) { + + return this.data.has( object ); + + } + delete( object ) { this.data.delete( object ); @@ -74828,6 +77148,52 @@ void main() { } + let _id$1 = 0; + + class DualAttributeData { + + constructor( attributeData, dualBuffer ) { + + this.buffers = [ attributeData.bufferGPU, dualBuffer ]; + this.type = attributeData.type; + this.bufferType = attributeData.bufferType; + this.pbo = attributeData.pbo; + this.byteLength = attributeData.byteLength; + this.bytesPerElement = attributeData.BYTES_PER_ELEMENT; + this.version = attributeData.version; + this.isInteger = attributeData.isInteger; + this.activeBufferIndex = 0; + this.baseId = attributeData.id; + + } + + + get id() { + + return `${ this.baseId }|${ this.activeBufferIndex }`; + + } + + get bufferGPU() { + + return this.buffers[ this.activeBufferIndex ]; + + } + + get transformBuffer() { + + return this.buffers[ this.activeBufferIndex ^ 1 ]; + + } + + switchBuffers() { + + this.activeBufferIndex ^= 1; + + } + + } + class WebGLAttributeUtils { constructor( backend ) { @@ -74851,11 +77217,7 @@ void main() { if ( bufferGPU === undefined ) { - bufferGPU = gl.createBuffer(); - - gl.bindBuffer( bufferType, bufferGPU ); - gl.bufferData( bufferType, array, usage ); - gl.bindBuffer( bufferType, null ); + bufferGPU = this._createBuffer( gl, bufferType, array, usage ); bufferData.bufferGPU = bufferGPU; bufferData.bufferType = bufferType; @@ -74913,13 +77275,27 @@ void main() { } - backend.set( attribute, { + let attributeData = { bufferGPU, + bufferType, type, + byteLength: array.byteLength, bytesPerElement: array.BYTES_PER_ELEMENT, version: attribute.version, - isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType - } ); + pbo: attribute.pbo, + isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType, + id: _id$1 ++ + }; + + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) { + + // create buffer for tranform feedback use + const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage ); + attributeData = new DualAttributeData( attributeData, bufferGPUDual ); + + } + + backend.set( attribute, attributeData ); } @@ -75013,6 +77389,18 @@ void main() { } + _createBuffer( gl, bufferType, array, usage ) { + + const bufferGPU = gl.createBuffer(); + + gl.bindBuffer( bufferType, bufferGPU ); + gl.bufferData( bufferType, array, usage ); + gl.bindBuffer( bufferType, null ); + + return bufferGPU; + + } + } let initialized$1 = false, equationToGL, factorToGL; @@ -75770,6 +78158,7 @@ void main() { } if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === gl.RGB ) return gl.RGB; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization if ( p === RGBAFormat ) return gl.RGBA; if ( p === LuminanceFormat ) return gl.LUMINANCE; if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA; @@ -76149,6 +78538,17 @@ void main() { } + if ( glFormat === gl.RGB ) { + + if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F; + if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F; + if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8; + if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565; + if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1; + if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4; + + } + if ( glFormat === gl.RGBA ) { if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F; @@ -76186,7 +78586,9 @@ void main() { setTextureParameters( textureType, texture ) { - const { gl, extensions } = this; + const { gl, extensions, backend } = this; + + const { currentAnisotropy } = backend.get( texture ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); @@ -76201,7 +78603,7 @@ void main() { // follow WebGPU backend mapping for texture filtering - const minFilter = texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; + const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] ); @@ -76214,13 +78616,17 @@ void main() { if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - //extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 - if ( texture.anisotropy > 1 /*|| properties.get( texture ).__currentAnisotropy*/ ) ; + if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) ); + backend.get( texture ).currentAnisotropy = texture.anisotropy; + + } } @@ -76298,6 +78704,41 @@ void main() { } + copyBufferToTexture( buffer, texture ) { + + const { gl, backend } = this; + + const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture ); + + const { width, height } = texture.source.data; + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer ); + + backend.state.bindTexture( glTextureType, textureGPU ); + + gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false ); + gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false ); + gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 ); + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null ); + + backend.state.unbindTexture(); + // debug + // const framebuffer = gl.createFramebuffer(); + // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer ); + // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 ); + + // const readout = new Float32Array( width * height * 4 ); + + // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ); + // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ); + + // gl.readPixels( 0, 0, width, height, altFormat, altType, readout ); + // gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + // console.log( readout ); + + } + updateTexture( texture, options ) { const { gl } = this; @@ -76487,21 +78928,25 @@ void main() { const width = texture.image.width; const height = texture.image.height; - state.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); - if ( texture.isDepthTexture ) { - const fb = gl.createFramebuffer(); + let mask = gl.DEPTH_BUFFER_BIT; + + if ( renderContext.stencil ) { - gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); + mask |= gl.STENCIL_BUFFER_BIT; + + } + + const fb = gl.createFramebuffer(); + state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, textureGPU, 0 ); - gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST ); + gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST ); gl.deleteFramebuffer( fb ); - } else { state.bindTexture( gl.TEXTURE_2D, textureGPU ); @@ -76621,10 +79066,11 @@ void main() { if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array; - if ( glType === gl.UNSIGNED_INT ) return Uint32Array; - if ( glType === gl.UNSIGNED_FLOAT ) return Float32Array; + if ( glType === gl.FLOAT ) return Float32Array; + + throw new Error( `Unsupported WebGL type: ${glType}` ); } @@ -76753,7 +79199,12 @@ void main() { this.state = new WebGLState( this ); this.utils = new WebGLUtils( this ); + this.vaoCache = {}; + this.transformFeedbackCache = {}; + this.discard = false; + this.extensions.get( 'EXT_color_buffer_float' ); + this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' ); this._currentContext = null; } @@ -76790,7 +79241,7 @@ void main() { this._setFramebuffer( renderContext ); - this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext ); + this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false ); // if ( renderContext.viewport ) { @@ -76803,6 +79254,14 @@ void main() { } + if ( renderContext.scissor ) { + + const { x, y, width, height } = renderContext.scissorValue; + + gl.scissor( x, y, width, height ); + + } + const occlusionQueryCount = renderContext.occlusionQueryCount; if ( occlusionQueryCount > 0 ) { @@ -76995,7 +79454,23 @@ void main() { } - clear( color, depth, stencil, descriptor = null ) { + setScissorTest( boolean ) { + + const gl = this.gl; + + if ( boolean ) { + + gl.enable( gl.SCISSOR_TEST ); + + } else { + + gl.disable( gl.SCISSOR_TEST ); + + } + + } + + clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) { const { gl } = this; @@ -77018,7 +79493,7 @@ void main() { if ( clear !== 0 ) { - const clearColor = descriptor.clearColorValue; + const clearColor = descriptor.clearColorValue || this.getClearColor(); if ( depth ) this.state.setDepthMask( true ); @@ -77029,6 +79504,8 @@ void main() { } else { + if ( setFrameBuffer ) this._setFramebuffer( descriptor ); + if ( color ) { for ( let i = 0; i < descriptor.textures.length; i ++ ) { @@ -77061,20 +79538,95 @@ void main() { beginCompute( /*computeGroup*/ ) { + const gl = this.gl; + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + } - compute( /*computeGroup, computeNode, bindings, pipeline*/ ) { + compute( computeGroup, computeNode, bindings, pipeline ) { + + const gl = this.gl; + + if ( ! this.discard ) { + + // required here to handle async behaviour of render.compute() + gl.enable( gl.RASTERIZER_DISCARD ); + this.discard = true; + + } + + const { programGPU, transformBuffers, attributes } = this.get( pipeline ); + + const vaoKey = this._getVaoKey( null, attributes ); + + const vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + this._createVao( null, attributes ); + + } else { + + gl.bindVertexArray( vaoGPU ); + + } + + gl.useProgram( programGPU ); + + this._bindUniforms( bindings ); + + const transformFeedbackGPU = this._getTransformFeedback( transformBuffers ); + + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); + gl.beginTransformFeedback( gl.POINTS ); + + if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) { + + gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count ); + + } else { + + gl.drawArrays( gl.POINTS, 0, computeNode.count ); + + } + + gl.endTransformFeedback(); + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); + + // switch active buffers + + for ( let i = 0; i < transformBuffers.length; i ++ ) { + + const dualAttributeData = transformBuffers[ i ]; + + if ( dualAttributeData.pbo ) { + + this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo ); + + } + + dualAttributeData.switchBuffers(); + + + } } finishCompute( /*computeGroup*/ ) { + const gl = this.gl; + + this.discard = false; + + gl.disable( gl.RASTERIZER_DISCARD ); + } draw( renderObject, info ) { const { pipeline, material, context } = renderObject; - const { programGPU, vaoGPU } = this.get( pipeline ); + const { programGPU } = this.get( pipeline ); const { gl, state } = this; @@ -77082,28 +79634,34 @@ void main() { // - const bindings = renderObject.getBindings(); + this._bindUniforms( renderObject.getBindings() ); - for ( const binding of bindings ) { + state.setMaterial( material ); - const bindingData = this.get( binding ); - const index = bindingData.index; + gl.useProgram( programGPU ); - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + // - gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); + let vaoGPU = renderObject.staticVao; - } else if ( binding.isSampledTexture ) { + if ( vaoGPU === undefined ) { - state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); + const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() ); + + vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + let staticVao; + + ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) ); + + if ( staticVao ) renderObject.staticVao = vaoGPU; } } - state.setMaterial( material ); - - gl.useProgram( programGPU ); gl.bindVertexArray( vaoGPU ); // @@ -77185,7 +79743,6 @@ void main() { } - info.update( object, indexCount, 1 ); } else { @@ -77209,8 +79766,6 @@ void main() { } - - // gl.bindVertexArray( null ); @@ -77291,7 +79846,7 @@ void main() { const gl = this.gl; const { stage, code } = program; - const shader = stage === 'vertex' ? gl.createShader( gl.VERTEX_SHADER ) : gl.createShader( gl.FRAGMENT_SHADER ); + const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER ); gl.shaderSource( shader, code ); gl.compileShader( shader ); @@ -77306,7 +79861,7 @@ void main() { } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const gl = this.gl; const pipeline = renderObject.pipeline; @@ -77324,39 +79879,487 @@ void main() { gl.attachShader( programGPU, vertexShader ); gl.linkProgram( programGPU ); + this.set( pipeline, { + programGPU, + fragmentShader, + vertexShader + } ); + + if ( promises !== null && this.parallel ) { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + const parallel = this.parallel; + const checkStatus = () => { + + if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) { + + this._completeCompile( renderObject, pipeline ); + resolve(); + + } else { + + requestAnimationFrame( checkStatus ); + + } + + }; + + checkStatus(); + + } ); + + promises.push( p ); + + return; + + } + + this._completeCompile( renderObject, pipeline ); + + } + + _completeCompile( renderObject, pipeline ) { + + const gl = this.gl; + const pipelineData = this.get( pipeline ); + const { programGPU, fragmentShader, vertexShader } = pipelineData; + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; gl.useProgram( programGPU ); // Bindings - const bindings = renderObject.getBindings(); + this._setupBindings( renderObject.getBindings(), programGPU ); - for ( const binding of bindings ) { + // - const bindingData = this.get( binding ); - const index = bindingData.index; + this.set( pipeline, { + programGPU + } ); + + } + + createComputePipeline( computePipeline, bindings ) { + + const gl = this.gl; + + // Program + + const fragmentProgram = { + stage: 'fragment', + code: '#version 300 es\nprecision highp float;\nvoid main() {}' + }; + + this.createProgram( fragmentProgram ); + + const { computeProgram } = computePipeline; + + const programGPU = gl.createProgram(); + + const fragmentShader = this.get( fragmentProgram ).shaderGPU; + const vertexShader = this.get( computeProgram ).shaderGPU; + + const transforms = computeProgram.transforms; + + const transformVaryingNames = []; + const transformAttributeNodes = []; + + for ( let i = 0; i < transforms.length; i ++ ) { + + const transform = transforms[ i ]; + + transformVaryingNames.push( transform.varyingName ); + transformAttributeNodes.push( transform.attributeNode ); + + } + + gl.attachShader( programGPU, fragmentShader ); + gl.attachShader( programGPU, vertexShader ); + + gl.transformFeedbackVaryings( + programGPU, + transformVaryingNames, + gl.SEPARATE_ATTRIBS, + ); + + gl.linkProgram( programGPU ); + + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; + + gl.useProgram( programGPU ); + + // Bindings + + this.createBindings( bindings ); + + this._setupBindings( bindings, programGPU ); + + const attributeNodes = computeProgram.attributes; + const attributes = []; + const transformBuffers = []; + + for ( let i = 0; i < attributeNodes.length; i ++ ) { + + const attribute = attributeNodes[ i ].node.attribute; + + attributes.push( attribute ); + + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + } + + for ( let i = 0; i < transformAttributeNodes.length; i ++ ) { + + const attribute = transformAttributeNodes[ i ].attribute; + + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + const attributeData = this.get( attribute ); + + transformBuffers.push( attributeData ); + + } + + // + + this.set( computePipeline, { + programGPU, + transformBuffers, + attributes + } ); + + } + + createBindings( bindings ) { + + this.updateBindings( bindings ); + + } + + updateBindings( bindings ) { + + const { gl } = this; + + let groupIndex = 0; + let textureIndex = 0; + + for ( const binding of bindings ) { if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - const location = gl.getUniformBlockIndex( programGPU, binding.name ); - gl.uniformBlockBinding( programGPU, location, index ); + const bufferGPU = gl.createBuffer(); + const data = binding.buffer; + + gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); + gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU ); + + this.set( binding, { + index: groupIndex ++, + bufferGPU + } ); } else if ( binding.isSampledTexture ) { - const location = gl.getUniformLocation( programGPU, binding.name ); - gl.uniform1i( location, index ); + const { textureGPU, glTextureType } = this.get( binding.texture ); + + this.set( binding, { + index: textureIndex ++, + textureGPU, + glTextureType + } ); } } - // VAO + } + + updateBinding( binding ) { + + const gl = this.gl; + + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + + const bindingData = this.get( binding ); + const bufferGPU = bindingData.bufferGPU; + const data = binding.buffer; + + gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); + gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + + } + + } + + // attributes + + createIndexAttribute( attribute ) { + + const gl = this.gl; + + this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + + } + + createAttribute( attribute ) { + + if ( this.has( attribute ) ) return; + + const gl = this.gl; + + this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + } + + createStorageAttribute( attribute ) { + + //console.warn( 'Abstract class.' ); + + } + + updateAttribute( attribute ) { + + this.attributeUtils.updateAttribute( attribute ); + + } + + destroyAttribute( attribute ) { + + this.attributeUtils.destroyAttribute( attribute ); + + } + + updateSize() { + + //console.warn( 'Abstract class.' ); + + } + + async hasFeatureAsync( name ) { + + return this.hasFeature( name ); + + } + + hasFeature( name ) { + + const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); + + const extensions = this.extensions; + + for ( let i = 0; i < keysMatching.length; i ++ ) { + + + if ( extensions.has( keysMatching[ i ] ) ) return true; + + } + + return false; + + } + + + getMaxAnisotropy() { + + return this.capabilities.getMaxAnisotropy(); + + } + + copyFramebufferToTexture( texture, renderContext ) { + + this.textureUtils.copyFramebufferToTexture( texture, renderContext ); + + } + + _setFramebuffer( renderContext ) { + + const { gl, state } = this; + + let currentFrameBuffer = null; + + if ( renderContext.textures !== null ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetContextData = this.get( renderTarget ); + const { samples, depthBuffer, stencilBuffer } = renderTarget; + const cubeFace = this.renderer._activeCubeFace; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + + let msaaFb = renderTargetContextData.msaaFrameBuffer; + let depthRenderbuffer = renderTargetContextData.depthRenderbuffer; + + let fb; + + if ( isCube ) { + + if ( renderTargetContextData.cubeFramebuffers === undefined ) { + + renderTargetContextData.cubeFramebuffers = []; + + } + + fb = renderTargetContextData.cubeFramebuffers[ cubeFace ]; + + } else { + + fb = renderTargetContextData.framebuffer; + + } + + if ( fb === undefined ) { + + fb = gl.createFramebuffer(); + + state.bindFramebuffer( gl.FRAMEBUFFER, fb ); + + const textures = renderContext.textures; + + if ( isCube ) { + + renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb; + const { textureGPU } = this.get( textures[ 0 ] ); + + gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 ); + + } else { + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + const textureData = this.get( texture ); + textureData.renderTarget = renderContext.renderTarget; + + const attachment = gl.COLOR_ATTACHMENT0 + i; + + gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 ); + + } + + renderTargetContextData.framebuffer = fb; + + state.drawBuffers( renderContext, fb ); + + } + + if ( renderContext.depthTexture !== null ) { + + const textureData = this.get( renderContext.depthTexture ); + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + + gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 ); + + } + + } + + if ( samples > 0 ) { + + if ( msaaFb === undefined ) { + + const invalidationArray = []; + + msaaFb = gl.createFramebuffer(); + + state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb ); + + const msaaRenderbuffers = []; + + const textures = renderContext.textures; + + for ( let i = 0; i < textures.length; i ++ ) { + + + msaaRenderbuffers[ i ] = gl.createRenderbuffer(); + + gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); + + invalidationArray.push( gl.COLOR_ATTACHMENT0 + i ); + + if ( depthBuffer ) { + + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + invalidationArray.push( depthStyle ); + + } + + const texture = renderContext.textures[ i ]; + const textureData = this.get( texture ); + + gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height ); + gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); + + + } + + renderTargetContextData.msaaFrameBuffer = msaaFb; + renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers; + + if ( depthRenderbuffer === undefined ) { + + depthRenderbuffer = gl.createRenderbuffer(); + this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext ); + + renderTargetContextData.depthRenderbuffer = depthRenderbuffer; + + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + invalidationArray.push( depthStyle ); + + } + + renderTargetContextData.invalidationArray = invalidationArray; + + } + + currentFrameBuffer = renderTargetContextData.msaaFrameBuffer; + + } else { + + currentFrameBuffer = fb; + + } + + } + + state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer ); + + } + + + _getVaoKey( index, attributes ) { + + let key = []; + + if ( index !== null ) { + + const indexData = this.get( index ); + + key += ':' + indexData.id; + + } + + for ( let i = 0; i < attributes.length; i ++ ) { + + const attributeData = this.get( attributes[ i ] ); + + key += ':' + attributeData.id; + + } + + return key; + + } + + _createVao( index, attributes ) { + + const { gl } = this; const vaoGPU = gl.createVertexArray(); + let key = ''; - const index = renderObject.getIndex(); - const attributes = renderObject.getAttributes(); + let staticVao = true; gl.bindVertexArray( vaoGPU ); @@ -77366,6 +80369,8 @@ void main() { gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU ); + key += ':' + indexData.id; + } for ( let i = 0; i < attributes.length; i ++ ) { @@ -77373,9 +80378,13 @@ void main() { const attribute = attributes[ i ]; const attributeData = this.get( attribute ); + key += ':' + attributeData.id; + gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU ); gl.enableVertexAttribArray( i ); + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false; + let stride, offset; if ( attribute.isInterleavedBufferAttribute === true ) { @@ -77412,304 +80421,101 @@ void main() { } - gl.bindVertexArray( null ); - - // - - this.set( pipeline, { - programGPU, - vaoGPU - } ); + gl.bindBuffer( gl.ARRAY_BUFFER, null ); - } + this.vaoCache[ key ] = vaoGPU; - createComputePipeline( /*computePipeline, bindings*/ ) { + return { vaoGPU, staticVao }; } - createBindings( bindings ) { - - this.updateBindings( bindings ); - - } - - updateBindings( bindings ) { - - const { gl } = this; - - let groupIndex = 0; - let textureIndex = 0; - - for ( const binding of bindings ) { + _getTransformFeedback( transformBuffers ) { - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + let key = ''; - const bufferGPU = gl.createBuffer(); - const data = binding.buffer; + for ( let i = 0; i < transformBuffers.length; i ++ ) { - gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); - gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); - gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU ); - - this.set( binding, { - index: groupIndex ++, - bufferGPU - } ); - - } else if ( binding.isSampledTexture ) { - - const { textureGPU, glTextureType } = this.get( binding.texture ); - - this.set( binding, { - index: textureIndex ++, - textureGPU, - glTextureType - } ); - - } + key += ':' + transformBuffers[ i ].id; } - } + let transformFeedbackGPU = this.transformFeedbackCache[ key ]; - updateBinding( binding ) { + if ( transformFeedbackGPU !== undefined ) { - const gl = this.gl; - - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - - const bindingData = this.get( binding ); - const bufferGPU = bindingData.bufferGPU; - const data = binding.buffer; - - gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); - gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + return transformFeedbackGPU; } - } - - // attributes - - createIndexAttribute( attribute ) { - const gl = this.gl; - this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - - } + transformFeedbackGPU = gl.createTransformFeedback(); - createAttribute( attribute ) { + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); - const gl = this.gl; + for ( let i = 0; i < transformBuffers.length; i ++ ) { - this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + const attributeData = transformBuffers[ i ]; - } + gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer ); - createStorageAttribute( /*attribute*/ ) { + } - } + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); - updateAttribute( attribute ) { + this.transformFeedbackCache[ key ] = transformFeedbackGPU; - this.attributeUtils.updateAttribute( attribute ); + return transformFeedbackGPU; } - destroyAttribute( attribute ) { - - this.attributeUtils.destroyAttribute( attribute ); - } - - updateSize() { + _setupBindings( bindings, programGPU ) { - //console.warn( 'Abstract class.' ); + const gl = this.gl; - } + for ( const binding of bindings ) { - hasFeature( name ) { + const bindingData = this.get( binding ); + const index = bindingData.index; - const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - const extensions = this.extensions; + const location = gl.getUniformBlockIndex( programGPU, binding.name ); + gl.uniformBlockBinding( programGPU, location, index ); - for ( let i = 0; i < keysMatching.length; i ++ ) { + } else if ( binding.isSampledTexture ) { + const location = gl.getUniformLocation( programGPU, binding.name ); + gl.uniform1i( location, index ); - if ( extensions.has( keysMatching[ i ] ) ) return true; + } } - return false; - } - - getMaxAnisotropy() { - - return this.capabilities.getMaxAnisotropy(); - - } - - copyFramebufferToTexture( texture, renderContext ) { - - this.textureUtils.copyFramebufferToTexture( texture, renderContext ); - - } - - _setFramebuffer( renderContext ) { + _bindUniforms( bindings ) { const { gl, state } = this; - let currentFrameBuffer = null; - - if ( renderContext.textures !== null ) { - - const renderTarget = renderContext.renderTarget; - const renderTargetContextData = this.get( renderTarget ); - const { samples, depthBuffer, stencilBuffer } = renderTarget; - const cubeFace = this.renderer._activeCubeFace; - const isCube = renderTarget.isWebGLCubeRenderTarget === true; - - let msaaFb = renderTargetContextData.msaaFrameBuffer; - let depthRenderbuffer = renderTargetContextData.depthRenderbuffer; - - let fb; - - if ( isCube ) { - - if ( renderTargetContextData.cubeFramebuffers === undefined ) { - - renderTargetContextData.cubeFramebuffers = []; - - } - - fb = renderTargetContextData.cubeFramebuffers[ cubeFace ]; - - } else { - - fb = renderTargetContextData.framebuffer; - - } - - if ( fb === undefined ) { - - fb = gl.createFramebuffer(); - - state.bindFramebuffer( gl.FRAMEBUFFER, fb ); - - const textures = renderContext.textures; - - if ( isCube ) { - - renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb; - const { textureGPU } = this.get( textures[ 0 ] ); - - gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 ); - - } else { - - for ( let i = 0; i < textures.length; i ++ ) { - - const texture = textures[ i ]; - const textureData = this.get( texture ); - textureData.renderTarget = renderContext.renderTarget; - - const attachment = gl.COLOR_ATTACHMENT0 + i; - - gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 ); - - } - - renderTargetContextData.framebuffer = fb; - - state.drawBuffers( renderContext, fb ); - - } - - if ( renderContext.depthTexture !== null ) { - - const textureData = this.get( renderContext.depthTexture ); - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - - gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 ); - - } - - } - - if ( samples > 0 ) { - - if ( msaaFb === undefined ) { - - const invalidationArray = []; - - msaaFb = gl.createFramebuffer(); - - state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb ); - - const msaaRenderbuffers = []; - - const textures = renderContext.textures; - - for ( let i = 0; i < textures.length; i ++ ) { - - - msaaRenderbuffers[ i ] = gl.createRenderbuffer(); - - gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); - - invalidationArray.push( gl.COLOR_ATTACHMENT0 + i ); - - if ( depthBuffer ) { - - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - invalidationArray.push( depthStyle ); - - } - - const texture = renderContext.textures[ i ]; - const textureData = this.get( texture ); - - gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height ); - gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); - - - } - - renderTargetContextData.msaaFrameBuffer = msaaFb; - renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers; - - if ( depthRenderbuffer === undefined ) { - - depthRenderbuffer = gl.createRenderbuffer(); - this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext ); - - renderTargetContextData.depthRenderbuffer = depthRenderbuffer; - - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - invalidationArray.push( depthStyle ); - - } + for ( const binding of bindings ) { - renderTargetContextData.invalidationArray = invalidationArray; + const bindingData = this.get( binding ); + const index = bindingData.index; - } + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - currentFrameBuffer = renderTargetContextData.msaaFrameBuffer; + gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); - } else { + } else if ( binding.isSampledTexture ) { - currentFrameBuffer = fb; + state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); } } - state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer ); - } } @@ -78041,6 +80847,26 @@ void main() { } + let _id = 0; + + class NodeStorageBuffer extends StorageBuffer { + + constructor( nodeUniform ) { + + super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + + } + class WebGPUTexturePassUtils { constructor( device ) { @@ -78631,13 +81457,13 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { if ( texture.isDataTexture || texture.isData3DTexture ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, false ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY ); } else if ( texture.isDataArrayTexture ) { for ( let i = 0; i < options.image.depth; i ++ ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, false, i ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i ); } @@ -78678,6 +81504,9 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { const format = textureData.textureDescriptorGPU.format; const bytesPerTexel = this._getBytesPerTexel( format ); + let bytesPerRow = width * bytesPerTexel; + bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes + const readBuffer = device.createBuffer( { size: width * height * bytesPerTexel, @@ -78694,7 +81523,7 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { }, { buffer: readBuffer, - bytesPerRow: width * bytesPerTexel + bytesPerRow: bytesPerRow }, { width: width, @@ -78983,15 +81812,57 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { _getBytesPerTexel( format ) { - if ( format === GPUTextureFormat.R8Unorm ) return 1; - if ( format === GPUTextureFormat.R16Float ) return 2; - if ( format === GPUTextureFormat.RG8Unorm ) return 2; - if ( format === GPUTextureFormat.RG16Float ) return 4; - if ( format === GPUTextureFormat.R32Float ) return 4; - if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4; - if ( format === GPUTextureFormat.RG32Float ) return 8; - if ( format === GPUTextureFormat.RGBA16Float ) return 8; - if ( format === GPUTextureFormat.RGBA32Float ) return 16; + // 8-bit formats + if ( format === GPUTextureFormat.R8Unorm || + format === GPUTextureFormat.R8Snorm || + format === GPUTextureFormat.R8Uint || + format === GPUTextureFormat.R8Sint ) return 1; + + // 16-bit formats + if ( format === GPUTextureFormat.R16Uint || + format === GPUTextureFormat.R16Sint || + format === GPUTextureFormat.R16Float || + format === GPUTextureFormat.RG8Unorm || + format === GPUTextureFormat.RG8Snorm || + format === GPUTextureFormat.RG8Uint || + format === GPUTextureFormat.RG8Sint ) return 2; + + // 32-bit formats + if ( format === GPUTextureFormat.R32Uint || + format === GPUTextureFormat.R32Sint || + format === GPUTextureFormat.R32Float || + format === GPUTextureFormat.RG16Uint || + format === GPUTextureFormat.RG16Sint || + format === GPUTextureFormat.RG16Float || + format === GPUTextureFormat.RGBA8Unorm || + format === GPUTextureFormat.RGBA8UnormSRGB || + format === GPUTextureFormat.RGBA8Snorm || + format === GPUTextureFormat.RGBA8Uint || + format === GPUTextureFormat.RGBA8Sint || + format === GPUTextureFormat.BGRA8Unorm || + format === GPUTextureFormat.BGRA8UnormSRGB || + // Packed 32-bit formats + format === GPUTextureFormat.RGB9E5UFloat || + format === GPUTextureFormat.RGB10A2Unorm || + format === GPUTextureFormat.RG11B10UFloat || + format === GPUTextureFormat.Depth32Float || + format === GPUTextureFormat.Depth24Plus || + format === GPUTextureFormat.Depth24PlusStencil8 || + format === GPUTextureFormat.Depth32FloatStencil8 ) return 4; + + // 64-bit formats + if ( format === GPUTextureFormat.RG32Uint || + format === GPUTextureFormat.RG32Sint || + format === GPUTextureFormat.RG32Float || + format === GPUTextureFormat.RGBA16Uint || + format === GPUTextureFormat.RGBA16Sint || + format === GPUTextureFormat.RGBA16Float ) return 8; + + // 128-bit formats + if ( format === GPUTextureFormat.RGBA32Uint || + format === GPUTextureFormat.RGBA32Sint || + format === GPUTextureFormat.RGBA32Float ) return 16; + } @@ -79017,6 +81888,9 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { if ( format === GPUTextureFormat.RG16Sint ) return Int16Array; if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array; if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array; + if ( format === GPUTextureFormat.R16Float ) return Float32Array; + if ( format === GPUTextureFormat.RG16Float ) return Float32Array; + if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array; if ( format === GPUTextureFormat.R32Uint ) return Uint32Array; @@ -79029,6 +81903,17 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array; if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array; + if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array; + if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array; + if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array; + if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array; + if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array; + + if ( format === GPUTextureFormat.Depth32Float ) return Float32Array; + if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array; + if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array; + if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array; + } _getDimension( texture ) { @@ -79059,7 +81944,7 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { let formatGPU; - if ( /*texture.isRenderTargetTexture === true ||*/ texture.isFramebufferTexture === true ) { + if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) { formatGPU = GPUTextureFormat.BGRA8Unorm; @@ -79368,7 +82253,7 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { } // GPUShaderStage is not defined in browsers not supporting WebGPU - const GPUShaderStage = window.GPUShaderStage; + const GPUShaderStage = self.GPUShaderStage; const gpuShaderStageLib = { 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1, @@ -79377,7 +82262,8 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { }; const supports = { - instance: true + instance: true, + storageBuffer: true }; const wgslFnOpLib = { @@ -79406,6 +82292,11 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { uvec4: 'vec4', bvec4: 'vec4', + mat2: 'mat2x2', + imat2: 'mat2x2', + umat2: 'mat2x2', + bmat2: 'mat2x2', + mat3: 'mat3x3', imat3: 'mat3x3', umat3: 'mat3x3', @@ -79424,6 +82315,10 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { mod_vec2: 'threejs_mod_vec2', mod_vec3: 'threejs_mod_vec3', mod_vec4: 'threejs_mod_vec4', + equals_bool: 'threejs_equals_bool', + equals_bvec2: 'threejs_equals_bvec2', + equals_bvec3: 'threejs_equals_bvec3', + equals_bvec4: 'threejs_equals_bvec4', lessThanEqual: 'threejs_lessThanEqual', greaterThan: 'threejs_greaterThan', inversesqrt: 'inverseSqrt', @@ -79456,6 +82351,10 @@ fn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 { mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ), mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ), mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ), + equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ), + equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }' ), + equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }' ), + equals_bvec4: new CodeNode( 'fn threejs_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: new CodeNode( ` fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 { @@ -79555,6 +82454,12 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 } + generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) { + + return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`; + + } + isUnfilterable( texture ) { return texture.isDataTexture === true && texture.type === FloatType; @@ -79626,7 +82531,7 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 const name = node.name; const type = node.type; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { return name; @@ -79679,11 +82584,11 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 const bindings = this.bindings[ shaderStage ]; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { let texture = null; - if ( type === 'texture' ) { + if ( type === 'texture' || type === 'storageTexture' ) { texture = new NodeSampledTexture( uniformNode.name, uniformNode.node ); @@ -79715,8 +82620,8 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 } else if ( type === 'buffer' || type === 'storageBuffer' ) { - const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer; - const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value ); + const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer; + const buffer = new bufferClass( node ); buffer.setVisibility( gpuShaderStageLib[ shaderStage ] ); bindings.push( buffer ); @@ -79743,31 +82648,9 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 } - if ( node.isArrayUniformNode === true ) { - - uniformGPU = []; - - for ( const uniformNode of node.nodes ) { - - const uniformNodeGPU = this.getNodeUniform( uniformNode, type ); - - // fit bounds to buffer - uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize ); - uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize ); - - uniformsGroup.addUniform( uniformNodeGPU ); - - uniformGPU.push( uniformNodeGPU ); - - } - - } else { - - uniformGPU = this.getNodeUniform( uniformNode, type ); - - uniformsGroup.addUniform( uniformGPU ); + uniformGPU = this.getNodeUniform( uniformNode, type ); - } + uniformsGroup.addUniform( uniformGPU ); } @@ -80066,7 +82949,7 @@ ${ flowData.code } for ( const uniform of uniforms ) { - if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' ) { + if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) { const texture = uniform.node.value; @@ -80138,17 +83021,7 @@ ${ flowData.code } snippets: [] } ); - if ( Array.isArray( uniform.value ) === true ) { - - const length = uniform.value.length; - - group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` ); - - } else { - - group.snippets.push( `\t${uniform.name} : ${ vectorType}` ); - - } + group.snippets.push( `\t${ uniform.name } : ${ vectorType }` ); } @@ -80563,7 +83436,21 @@ var<${access}> ${name} : ${structName};`; const device = backend.device; - const array = bufferAttribute.array; + let array = bufferAttribute.array; + + if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) { + + bufferAttribute.itemSize = 4; + array = new array.constructor( bufferAttribute.count * 4 ); + + for ( let i = 0; i < bufferAttribute.count; i ++ ) { + + array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 ); + + } + + } + const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441 buffer = device.createBuffer( { @@ -81033,7 +83920,7 @@ var<${access}> ${name} : ${structName};`; } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const { object, material, geometry, pipeline } = renderObject; const { vertexProgram, fragmentProgram } = pipeline; @@ -81127,7 +84014,7 @@ var<${access}> ${name} : ${structName};`; } - pipelineData.pipeline = device.createRenderPipeline( { + const pipelineDescriptor = { vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ), fragment: Object.assign( {}, fragmentModule, { targets } ), primitive: primitiveState, @@ -81147,7 +84034,28 @@ var<${access}> ${name} : ${structName};`; layout: device.createPipelineLayout( { bindGroupLayouts: [ bindingsData.layout ] } ) - } ); + }; + + if ( promises === null ) { + + pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor ); + + } else { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => { + + pipelineData.pipeline = pipeline; + resolve(); + + } ); + + } ); + + promises.push( p ); + + } } @@ -81558,16 +84466,6 @@ var<${access}> ${name} : ${structName};`; import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js'; //*/ - // statics - - let _staticAdapter = null; - - if ( navigator.gpu !== undefined ) { - - _staticAdapter = await( navigator.gpu.requestAdapter()); - - } - // class WebGPUBackend extends Backend { @@ -81595,10 +84493,13 @@ var<${access}> ${name} : ${structName};`; this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits; + this.trackTimestamp = ( parameters.trackTimestamp === true ); + this.adapter = null; this.device = null; this.context = null; this.colorBuffer = null; + this.defaultRenderPassdescriptor = null; this.utils = new WebGPUUtils( this ); this.attributeUtils = new WebGPUAttributeUtils( this ); @@ -81689,60 +84590,88 @@ var<${access}> ${name} : ${structName};`; } - beginRender( renderContext ) { + _getDefaultRenderPassDescriptor() { - const renderContextData = this.get( renderContext ); + let descriptor = this.defaultRenderPassdescriptor; - const device = this.device; - const occlusionQueryCount = renderContext.occlusionQueryCount; + const antialias = this.parameters.antialias; - let occlusionQuerySet; + if ( descriptor === null ) { - if ( occlusionQueryCount > 0 ) { + const renderer = this.renderer; - if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); - if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + descriptor = { + colorAttachments: [ { + view: null + } ], + depthStencilAttachment: { + view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() + } + }; - // Get a reference to the array of objects with queries. The renderContextData property - // can be changed by another render pass before the buffer.mapAsyc() completes. - renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; - renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; - renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + const colorAttachment = descriptor.colorAttachments[ 0 ]; - // + if ( antialias === true ) { - occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + colorAttachment.view = this.colorBuffer.createView(); - renderContextData.occlusionQuerySet = occlusionQuerySet; - renderContextData.occlusionQueryIndex = 0; - renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + } else { - renderContextData.lastOcclusionObject = null; + colorAttachment.resolveTarget = undefined; - } + } - const descriptor = { - colorAttachments: [ { - view: null - } ], - depthStencilAttachment: { - view: null - }, - occlusionQuerySet - }; + this.defaultRenderPassdescriptor = descriptor; + + } const colorAttachment = descriptor.colorAttachments[ 0 ]; - const depthStencilAttachment = descriptor.depthStencilAttachment; - const antialias = this.parameters.antialias; + if ( antialias === true ) { - if ( renderContext.textures !== null ) { + colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - const textures = renderContext.textures; + } else { - descriptor.colorAttachments = []; + colorAttachment.view = this.context.getCurrentTexture().createView(); - const colorAttachments = descriptor.colorAttachments; + } + + return descriptor; + + } + + _getRenderPassDescriptor( renderContext ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetData = this.get( renderTarget ); + + let descriptors = renderTargetData.descriptors; + + if ( descriptors === undefined ) { + + descriptors = []; + + renderTargetData.descriptors = descriptors; + + } + + if ( renderTargetData.width !== renderTarget.width || + renderTargetData.height !== renderTarget.height || + renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel || + renderTargetData.samples !== renderTarget.samples + ) { + + descriptors.length = 0; + + } + + let descriptor = descriptors[ renderContext.activeCubeFace ]; + + if ( descriptor === undefined ) { + + const textures = renderContext.textures; + const colorAttachments = []; for ( let i = 0; i < textures.length; i ++ ) { @@ -81780,32 +84709,78 @@ var<${access}> ${name} : ${structName};`; const depthTextureData = this.get( renderContext.depthTexture ); - depthStencilAttachment.view = depthTextureData.texture.createView(); + const depthStencilAttachment = { + view: depthTextureData.texture.createView(), + }; - if ( renderContext.stencil && renderContext.depthTexture.format === DepthFormat ) { + descriptor = { + colorAttachments, + depthStencilAttachment + }; - renderContext.stencil = false; + descriptors[ renderContext.activeCubeFace ] = descriptor; - } + renderTargetData.width = renderTarget.width; + renderTargetData.height = renderTarget.height; + renderTargetData.samples = renderTarget.samples; + renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel; - } else { + } - if ( antialias === true ) { + return descriptor; - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); + } - } else { + beginRender( renderContext ) { - colorAttachment.view = this.context.getCurrentTexture().createView(); - colorAttachment.resolveTarget = undefined; + const renderContextData = this.get( renderContext ); - } + const device = this.device; + const occlusionQueryCount = renderContext.occlusionQueryCount; - depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ).createView(); + let occlusionQuerySet; + + if ( occlusionQueryCount > 0 ) { + + if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); + if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + + // Get a reference to the array of objects with queries. The renderContextData property + // can be changed by another render pass before the buffer.mapAsyc() completes. + renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; + renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; + renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + + // + + occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + + renderContextData.occlusionQuerySet = occlusionQuerySet; + renderContextData.occlusionQueryIndex = 0; + renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + + renderContextData.lastOcclusionObject = null; } + let descriptor; + + if ( renderContext.textures === null ) { + + descriptor = this._getDefaultRenderPassDescriptor(); + + } else { + + descriptor = this._getRenderPassDescriptor( renderContext ); + + } + + this.initTimestampQuery( renderContext, descriptor ); + + descriptor.occlusionQuerySet = occlusionQuerySet; + + const depthStencilAttachment = descriptor.depthStencilAttachment; + if ( renderContext.textures !== null ) { const colorAttachments = descriptor.colorAttachments; @@ -81829,9 +84804,10 @@ var<${access}> ${name} : ${structName};`; } - } else { + const colorAttachment = descriptor.colorAttachments[ 0 ]; + if ( renderContext.clearColor ) { colorAttachment.clearValue = renderContext.clearColorValue; @@ -81968,8 +84944,11 @@ var<${access}> ${name} : ${structName};`; } + this.prepareTimestampBuffer( renderContext, renderContextData.encoder ); + this.device.queue.submit( [ renderContextData.encoder.finish() ] ); + // if ( renderContext.textures !== null ) { @@ -82020,7 +84999,7 @@ var<${access}> ${name} : ${structName};`; const buffer = currentOcclusionQueryBuffer.getMappedRange(); const results = new BigUint64Array( buffer ); - for ( let i = 0; i < currentOcclusionQueryObjects.length; i++ ) { + for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) { if ( results[ i ] !== 0n ) { @@ -82041,7 +85020,7 @@ var<${access}> ${name} : ${structName};`; updateViewport( renderContext ) { const { currentPass } = this.get( renderContext ); - let { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; + const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth ); @@ -82052,7 +85031,7 @@ var<${access}> ${name} : ${structName};`; const device = this.device; const renderer = this.renderer; - const colorAttachments = []; + let colorAttachments = []; let depthStencilAttachment; let clearValue; @@ -82073,39 +85052,23 @@ var<${access}> ${name} : ${structName};`; supportsDepth = renderer.depth; supportsStencil = renderer.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; + const descriptor = this._getDefaultRenderPassDescriptor(); if ( color ) { - const antialias = this.parameters.antialias; - - const colorAttachment = {}; + colorAttachments = descriptor.colorAttachments; - if ( antialias === true ) { - - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - - } else { - - colorAttachment.view = this.context.getCurrentTexture().createView(); - - } + const colorAttachment = colorAttachments[ 0 ]; colorAttachment.clearValue = clearValue; colorAttachment.loadOp = GPULoadOp.Clear; colorAttachment.storeOp = GPUStoreOp.Store; - colorAttachments.push( colorAttachment ); - } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { - depthStencilAttachment = { - view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() - }; + depthStencilAttachment = descriptor.depthStencilAttachment; } @@ -82114,9 +85077,6 @@ var<${access}> ${name} : ${structName};`; supportsDepth = renderTargetData.depth; supportsStencil = renderTargetData.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; - if ( color ) { for ( const texture of renderTargetData.textures ) { @@ -82150,7 +85110,7 @@ var<${access}> ${name} : ${structName};`; } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { const depthTextureData = this.get( renderTargetData.depthTexture ); @@ -82164,7 +85124,7 @@ var<${access}> ${name} : ${structName};`; // - if ( depthStencilAttachment !== undefined ) { + if ( supportsDepth ) { if ( depth ) { @@ -82179,7 +85139,11 @@ var<${access}> ${name} : ${structName};`; } - // + } + + // + + if ( supportsStencil ) { if ( stencil ) { @@ -82216,8 +85180,14 @@ var<${access}> ${name} : ${structName};`; const groupGPU = this.get( computeGroup ); - groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( {} ); - groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass(); + + const descriptor = {}; + + this.initTimestampQuery( computeGroup, descriptor ); + + groupGPU.cmdEncoderGPU = this.device.createCommandEncoder(); + + groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor ); } @@ -82244,6 +85214,9 @@ var<${access}> ${name} : ${structName};`; const groupData = this.get( computeGroup ); groupData.passEncoderGPU.end(); + + this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU ); + this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] ); } @@ -82320,7 +85293,7 @@ var<${access}> ${name} : ${structName};`; // occlusion queries - handle multiple consecutive draw calls for an object - if ( contextData.occlusionQuerySet !== undefined ) { + if ( contextData.occlusionQuerySet !== undefined ) { const lastObject = contextData.lastOcclusionObject; @@ -82404,7 +85377,8 @@ var<${access}> ${name} : ${structName};`; data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage || data.sampleCount !== sampleCount || data.colorSpace !== colorSpace || data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat || - data.primitiveTopology !== primitiveTopology + data.primitiveTopology !== primitiveTopology || + data.clippingContextVersion !== renderObject.clippingContextVersion ) { data.material = material; data.materialVersion = material.version; @@ -82422,6 +85396,7 @@ var<${access}> ${name} : ${structName};`; data.colorFormat = colorFormat; data.depthStencilFormat = depthStencilFormat; data.primitiveTopology = primitiveTopology; + data.clippingContextVersion = renderObject.clippingContextVersion; needsUpdate = true; @@ -82450,7 +85425,8 @@ var<${access}> ${name} : ${structName};`; material.side, utils.getSampleCount( renderContext ), utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ), - utils.getPrimitiveTopology( object, material ) + utils.getPrimitiveTopology( object, material ), + renderObject.clippingContextVersion ].join(); } @@ -82505,6 +85481,87 @@ var<${access}> ${name} : ${structName};`; } + + initTimestampQuery( renderContext, descriptor ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + if ( ! renderContextData.timeStampQuerySet ) { + + // Create a GPUQuerySet which holds 2 timestamp query results: one for the + // beginning and one for the end of compute pass execution. + const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } ); + + const timestampWrites = { + querySet: timeStampQuerySet, + beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins. + endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends. + }; + Object.assign( descriptor, { + timestampWrites, + } ); + renderContextData.timeStampQuerySet = timeStampQuerySet; + + } + + } + + // timestamp utils + + prepareTimestampBuffer( renderContext, encoder ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + const size = 2 * BigInt64Array.BYTES_PER_ELEMENT; + const resolveBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC, + } ); + + const resultBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + } ); + + encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 ); + encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size ); + + renderContextData.currentTimestampQueryBuffer = resultBuffer; + + } + + async resolveTimestampAsync( renderContext, type = 'render' ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + // handle timestamp query results + + const { currentTimestampQueryBuffer } = renderContextData; + + if ( currentTimestampQueryBuffer ) { + + renderContextData.currentTimestampQueryBuffer = null; + + await currentTimestampQueryBuffer.mapAsync( GPUMapMode.READ ); + + const times = new BigUint64Array( currentTimestampQueryBuffer.getMappedRange() ); + + const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000; + // console.log( `Compute ${type} duration: ${Number( times[ 1 ] - times[ 0 ] ) / 1000000}ms` ); + this.renderer.info.updateTimestamp( type, duration ); + + currentTimestampQueryBuffer.unmap(); + + } + + } + // node builder createNodeBuilder( object, renderer, scene = null ) { @@ -82534,9 +85591,9 @@ var<${access}> ${name} : ${structName};`; // pipelines - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { - this.pipelineUtils.createRenderPipeline( renderObject ); + this.pipelineUtils.createRenderPipeline( renderObject, promises ); } @@ -82603,7 +85660,8 @@ var<${access}> ${name} : ${structName};`; updateSize() { this.colorBuffer = this.textureUtils.getColorBuffer(); - + this.defaultRenderPassdescriptor = null; + } // utils public @@ -82614,9 +85672,9 @@ var<${access}> ${name} : ${structName};`; } - hasFeature( name ) { + async hasFeatureAsync( name ) { - const adapter = this.adapter || _staticAdapter; + const adapter = this.adapter || await WebGPU.getStaticAdapter(); // @@ -82624,6 +85682,18 @@ var<${access}> ${name} : ${structName};`; } + hasFeature( name ) { + + if ( ! this.adapter ) { + + return false; + + } + + return this.adapter.features.has( name ); + + } + copyFramebufferToTexture( texture, renderContext ) { const renderContextData = this.get( renderContext ); @@ -82632,18 +85702,40 @@ var<${access}> ${name} : ${structName};`; let sourceGPU = null; - if ( texture.isFramebufferTexture ) { + if ( renderContext.renderTarget ) { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.get( renderContext.depthTexture ).texture; + + } else { + + sourceGPU = this.get( renderContext.textures[ 0 ] ).texture; + + } + + } else { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); - sourceGPU = this.context.getCurrentTexture(); + } else { - } else if ( texture.isDepthTexture ) { + sourceGPU = this.context.getCurrentTexture(); - sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); + } } const destinationGPU = this.get( texture ).texture; + if ( sourceGPU.format !== destinationGPU.format ) { + + return; + + } + renderContextData.currentPass.end(); encoder.copyTextureToTexture( @@ -82693,7 +85785,11 @@ var<${access}> ${name} : ${structName};`; let BackendClass; - if ( WebGPU.isAvailable() ) { + if ( parameters.forceWebGL ) { + + BackendClass = WebGLBackend; + + } else if ( WebGPU.isAvailable() ) { BackendClass = WebGPUBackend; @@ -82759,6 +85855,7 @@ var<${access}> ${name} : ${structName};`; exports.AmbientLight = AmbientLight; exports.AmbientLightNode = AmbientLightNode; exports.AnalyticLightNode = AnalyticLightNode; + exports.AnamorphicNode = AnamorphicNode; exports.AnimationAction = AnimationAction; exports.AnimationClip = AnimationClip; exports.AnimationLoader = AnimationLoader; @@ -82768,7 +85865,6 @@ var<${access}> ${name} : ${structName};`; exports.ArcCurve = ArcCurve; exports.ArrayCamera = ArrayCamera; exports.ArrayElementNode = ArrayElementNode; - exports.ArrayUniformNode = ArrayUniformNode; exports.ArrowHelper = ArrowHelper; exports.AssignNode = AssignNode; exports.AttachedBindMode = AttachedBindMode; @@ -82794,6 +85890,7 @@ var<${access}> ${name} : ${structName};`; exports.Box3Helper = Box3Helper; exports.BoxGeometry = BoxGeometry; exports.BoxHelper = BoxHelper; + exports.Break = Break; exports.BufferAttribute = BufferAttribute; exports.BufferAttributeNode = BufferAttributeNode; exports.BufferGeometry = BufferGeometry; @@ -82832,6 +85929,7 @@ var<${access}> ${name} : ${structName};`; exports.ConstantAlphaFactor = ConstantAlphaFactor; exports.ConstantColorFactor = ConstantColorFactor; exports.ContextNode = ContextNode; + exports.Continue = Continue; exports.ConvertNode = ConvertNode; exports.CubeCamera = CubeCamera; exports.CubeReflectionMapping = CubeReflectionMapping; @@ -82898,7 +85996,6 @@ var<${access}> ${name} : ${structName};`; exports.FileLoader = FileLoader; exports.Float16BufferAttribute = Float16BufferAttribute; exports.Float32BufferAttribute = Float32BufferAttribute; - exports.Float64BufferAttribute = Float64BufferAttribute; exports.FloatType = FloatType; exports.Fog = Fog; exports.FogExp2 = FogExp2; @@ -82988,7 +86085,6 @@ var<${access}> ${name} : ${structName};`; exports.LineLoop = LineLoop; exports.LineSegments = LineSegments; exports.LinearDisplayP3ColorSpace = LinearDisplayP3ColorSpace; - exports.LinearEncoding = LinearEncoding; exports.LinearFilter = LinearFilter; exports.LinearInterpolant = LinearInterpolant; exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; @@ -83050,6 +86146,7 @@ var<${access}> ${name} : ${structName};`; exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter; exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter; + exports.NeutralToneMapping = NeutralToneMapping; exports.NeverCompare = NeverCompare; exports.NeverDepth = NeverDepth; exports.NeverStencilFunc = NeverStencilFunc; @@ -83102,6 +86199,8 @@ var<${access}> ${name} : ${structName};`; exports.P3Primaries = P3Primaries; exports.PCFShadowMap = PCFShadowMap; exports.PCFSoftShadowMap = PCFSoftShadowMap; + exports.PI = PI; + exports.PI2 = PI2; exports.PMREMGenerator = PMREMGenerator; exports.PackingNode = PackingNode; exports.ParameterNode = ParameterNode; @@ -83179,6 +86278,7 @@ var<${access}> ${name} : ${structName};`; exports.RedIntegerFormat = RedIntegerFormat; exports.ReferenceNode = ReferenceNode; exports.ReflectVectorNode = ReflectVectorNode; + exports.ReflectorNode = ReflectorNode; exports.ReinhardToneMapping = ReinhardToneMapping; exports.RemapNode = RemapNode; exports.RenderTarget = RenderTarget; @@ -83186,6 +86286,7 @@ var<${access}> ${name} : ${structName};`; exports.ReplaceStencilOp = ReplaceStencilOp; exports.ReverseSubtractEquation = ReverseSubtractEquation; exports.RingGeometry = RingGeometry; + exports.RotateNode = RotateNode; exports.RotateUVNode = RotateUVNode; exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format; exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format; @@ -83234,6 +86335,7 @@ var<${access}> ${name} : ${structName};`; exports.StaticDrawUsage = StaticDrawUsage; exports.StaticReadUsage = StaticReadUsage; exports.StereoCamera = StereoCamera; + exports.StorageArrayElementNode = StorageArrayElementNode; exports.StorageBufferNode = StorageBufferNode; exports.StreamCopyUsage = StreamCopyUsage; exports.StreamDrawUsage = StreamDrawUsage; @@ -83273,6 +86375,7 @@ var<${access}> ${name} : ${structName};`; exports.UniformNode = UniformNode; exports.UniformsGroup = UniformsGroup$1; exports.UniformsLib = UniformsLib; + exports.UniformsNode = UniformsNode; exports.UniformsUtils = UniformsUtils; exports.UnsignedByteType = UnsignedByteType; exports.UnsignedInt248Type = UnsignedInt248Type; @@ -83324,7 +86427,10 @@ var<${access}> ${name} : ${structName};`; exports.addNodeElement = addNodeElement; exports.addNodeMaterial = addNodeMaterial; exports.afterImage = afterImage; + exports.all = all; + exports.anamorphic = anamorphic; exports.and = and; + exports.any = any; exports.append = append; exports.arrayBuffer = arrayBuffer; exports.asin = asin; @@ -83335,6 +86441,7 @@ var<${access}> ${name} : ${structName};`; exports.backgroundBlurriness = backgroundBlurriness; exports.backgroundIntensity = backgroundIntensity; exports.bitAnd = bitAnd; + exports.bitNot = bitNot; exports.bitOr = bitOr; exports.bitXor = bitXor; exports.bitangentGeometry = bitangentGeometry; @@ -83342,6 +86449,7 @@ var<${access}> ${name} : ${structName};`; exports.bitangentView = bitangentView; exports.bitangentWorld = bitangentWorld; exports.bitcast = bitcast; + exports.bmat2 = bmat2; exports.bmat3 = bmat3; exports.bmat4 = bmat4; exports.bool = bool; @@ -83361,6 +86469,7 @@ var<${access}> ${name} : ${structName};`; exports.cameraNormalMatrix = cameraNormalMatrix; exports.cameraPosition = cameraPosition; exports.cameraProjectionMatrix = cameraProjectionMatrix; + exports.cameraProjectionMatrixInverse = cameraProjectionMatrixInverse; exports.cameraViewMatrix = cameraViewMatrix; exports.cameraWorldMatrix = cameraWorldMatrix; exports.cbrt = cbrt; @@ -83405,6 +86514,7 @@ var<${access}> ${name} : ${structName};`; exports.dynamicBufferAttribute = dynamicBufferAttribute; exports.element = element; exports.equal = equal; + exports.equals = equals; exports.equirectUV = equirectUV; exports.exp = exp; exports.exp2 = exp2; @@ -83419,6 +86529,7 @@ var<${access}> ${name} : ${structName};`; exports.frameId = frameId; exports.frontFacing = frontFacing; exports.fwidth = fwidth; + exports.gain = gain; exports.gapSize = gapSize; exports.gaussianBlur = gaussianBlur; exports.getConstNodeType = getConstNodeType; @@ -83433,6 +86544,7 @@ var<${access}> ${name} : ${structName};`; exports.greaterThanEqual = greaterThanEqual; exports.hash = hash; exports.hue = hue; + exports.imat2 = imat2; exports.imat3 = imat3; exports.imat4 = imat4; exports.instance = instance; @@ -83450,12 +86562,13 @@ var<${access}> ${name} : ${structName};`; exports.js = js; exports.label = label; exports.length = length; + exports.lengthSq = lengthSq; exports.lessThan = lessThan; exports.lessThanEqual = lessThanEqual; - exports.lightNodes = lightNodes; exports.lightTargetDirection = lightTargetDirection; exports.lightingContext = lightingContext; exports.lights = lights; + exports.lightsNode = lightsNode; exports.linearToColorSpace = linearToColorSpace; exports.linearTosRGB = linearTosRGB; exports.log = log; @@ -83463,6 +86576,7 @@ var<${access}> ${name} : ${structName};`; exports.loop = loop; exports.lumaCoeffs = lumaCoeffs; exports.luminance = luminance; + exports.mat2 = mat2; exports.mat3 = mat3; exports.mat4 = mat4; exports.matcapUV = matcapUV; @@ -83507,7 +86621,7 @@ var<${access}> ${name} : ${structName};`; exports.modelViewPosition = modelViewPosition; exports.modelViewProjection = modelViewProjection; exports.modelWorldMatrix = modelWorldMatrix; - exports.morph = morph; + exports.morphReference = morphReference; exports.mul = mul; exports.mx_aastep = mx_aastep; exports.mx_cell_noise_float = mx_cell_noise_float; @@ -83543,6 +86657,7 @@ var<${access}> ${name} : ${structName};`; exports.normalView = normalView; exports.normalWorld = normalWorld; exports.normalize = normalize; + exports.not = not; exports.objectDirection = objectDirection; exports.objectGroup = objectGroup; exports.objectNormalMatrix = objectNormalMatrix; @@ -83562,8 +86677,12 @@ var<${access}> ${name} : ${structName};`; exports.outputStruct = outputStruct; exports.overlay = overlay; exports.overloadingFn = overloadingFn; + exports.parabola = parabola; + exports.parallaxDirection = parallaxDirection; + exports.parallaxUV = parallaxUV; exports.parameter = parameter; exports.pass = pass; + exports.pcurve = pcurve; exports.perspectiveDepthToViewZ = perspectiveDepthToViewZ; exports.pointUV = pointUV; exports.pointWidth = pointWidth; @@ -83584,18 +86703,19 @@ var<${access}> ${name} : ${structName};`; exports.rangeFog = rangeFog; exports.reciprocal = reciprocal; exports.reference = reference; - exports.referenceIndex = referenceIndex; + exports.referenceBuffer = referenceBuffer; exports.reflect = reflect; exports.reflectVector = reflectVector; + exports.reflector = reflector; exports.refract = refract; exports.remainder = remainder; exports.remap = remap; exports.remapClamp = remapClamp; exports.renderGroup = renderGroup; + exports.rotate = rotate; exports.rotateUV = rotateUV; exports.roughness = roughness; exports.round = round; - exports.sRGBEncoding = sRGBEncoding; exports.sRGBToLinear = sRGBToLinear; exports.sampler = sampler; exports.saturate = saturate; @@ -83613,6 +86733,7 @@ var<${access}> ${name} : ${structName};`; exports.shininess = shininess; exports.sign = sign; exports.sin = sin; + exports.sinc = sinc; exports.skinning = skinning; exports.smoothstep = smoothstep; exports.specularColor = specularColor; @@ -83623,6 +86744,7 @@ var<${access}> ${name} : ${structName};`; exports.stack = stack; exports.step = step; exports.storage = storage; + exports.storageObject = storageObject; exports.string = string; exports.sub = sub; exports.tan = tan; @@ -83635,6 +86757,7 @@ var<${access}> ${name} : ${structName};`; exports.textureBicubic = textureBicubic; exports.textureLoad = textureLoad; exports.textureStore = textureStore; + exports.threshold = threshold; exports.timerDelta = timerDelta; exports.timerGlobal = timerGlobal; exports.timerLocal = timerLocal; @@ -83647,15 +86770,18 @@ var<${access}> ${name} : ${structName};`; exports.transformedNormalWorld = transformedNormalWorld; exports.transformedTangentView = transformedTangentView; exports.transformedTangentWorld = transformedTangentWorld; + exports.triNoise3D = triNoise3D; exports.triplanarTexture = triplanarTexture; exports.triplanarTextures = triplanarTextures; exports.trunc = trunc; exports.tslFn = tslFn; exports.uint = uint; + exports.umat2 = umat2; exports.umat3 = umat3; exports.umat4 = umat4; exports.uniform = uniform; exports.uniformGroup = uniformGroup; + exports.uniforms = uniforms; exports.userData = userData; exports.uv = uv; exports.uvec2 = uvec2; diff --git a/build/three-webgpu.min.js b/build/three-webgpu.min.js index 9d5e8d9..21122a6 100644 --- a/build/three-webgpu.min.js +++ b/build/three-webgpu.min.js @@ -11,7 +11,7 @@ var THREE = (async function (exports) { * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ - const REVISION = '161dev'; + const REVISION = '162'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; @@ -70,6 +70,7 @@ var THREE = (async function (exports) { const ACESFilmicToneMapping = 4; const CustomToneMapping = 5; const AgXToneMapping = 6; + const NeutralToneMapping = 7; const AttachedBindMode = 'attached'; const DetachedBindMode = 'detached'; @@ -161,10 +162,6 @@ var THREE = (async function (exports) { const TrianglesDrawMode = 0; const TriangleStripDrawMode = 1; const TriangleFanDrawMode = 2; - /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */ - const LinearEncoding = 3000; - /** @deprecated Use SRGBColorSpace in three.js r152+. */ - const sRGBEncoding = 3001; const BasicDepthPacking = 3200; const RGBADepthPacking = 3201; const TangentSpaceNormalMap = 0; @@ -1846,6 +1843,7 @@ var THREE = (async function (exports) { this.uuid = generateUUID(); this.data = data; + this.dataReady = true; this.version = 0; @@ -2003,17 +2001,7 @@ var THREE = (async function (exports) { this.flipY = true; this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - if ( typeof colorSpace === 'string' ) { - - this.colorSpace = colorSpace; - - } else { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - + this.colorSpace = colorSpace; this.userData = {}; @@ -2252,20 +2240,6 @@ var THREE = (async function (exports) { } - get encoding() { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - - set encoding( encoding ) { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - } Texture.DEFAULT_IMAGE = null; @@ -2939,14 +2913,6 @@ var THREE = (async function (exports) { const image = { width: width, height: height, depth: 1 }; - if ( options.encoding !== undefined ) { - - // @deprecated, r152 - warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' ); - options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - options = Object.assign( { generateMipmaps: false, internalFormat: null, @@ -2954,15 +2920,25 @@ var THREE = (async function (exports) { depthBuffer: true, stencilBuffer: false, depthTexture: null, - samples: 0 + samples: 0, + count: 1 }, options ); - this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); - this.texture.isRenderTargetTexture = true; + const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); + + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + + this.textures = []; - this.texture.flipY = false; - this.texture.generateMipmaps = options.generateMipmaps; - this.texture.internalFormat = options.internalFormat; + const count = options.count; + for ( let i = 0; i < count; i ++ ) { + + this.textures[ i ] = texture.clone(); + this.textures[ i ].isRenderTargetTexture = true; + + } this.depthBuffer = options.depthBuffer; this.stencilBuffer = options.stencilBuffer; @@ -2973,6 +2949,18 @@ var THREE = (async function (exports) { } + get texture() { + + return this.textures[ 0 ]; + + } + + set texture( value ) { + + this.textures[ 0 ] = value; + + } + setSize( width, height, depth = 1 ) { if ( this.width !== width || this.height !== height || this.depth !== depth ) { @@ -2981,9 +2969,13 @@ var THREE = (async function (exports) { this.height = height; this.depth = depth; - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = depth; + for ( let i = 0, il = this.textures.length; i < il; i ++ ) { + + this.textures[ i ].image.width = width; + this.textures[ i ].image.height = height; + this.textures[ i ].image.depth = depth; + + } this.dispose(); @@ -3011,8 +3003,14 @@ var THREE = (async function (exports) { this.viewport.copy( source.viewport ); - this.texture = source.texture.clone(); - this.texture.isRenderTargetTexture = true; + this.textures.length = 0; + + for ( let i = 0, il = source.textures.length; i < il; i ++ ) { + + this.textures[ i ] = source.textures[ i ].clone(); + this.textures[ i ].isRenderTargetTexture = true; + + } // ensure image object is not shared, see #20328 @@ -3140,85 +3138,6 @@ var THREE = (async function (exports) { } - class WebGLMultipleRenderTargets extends WebGLRenderTarget { - - constructor( width = 1, height = 1, count = 1, options = {} ) { - - super( width, height, options ); - - this.isWebGLMultipleRenderTargets = true; - - const texture = this.texture; - - this.texture = []; - - for ( let i = 0; i < count; i ++ ) { - - this.texture[ i ] = texture.clone(); - this.texture[ i ].isRenderTargetTexture = true; - - } - - } - - setSize( width, height, depth = 1 ) { - - if ( this.width !== width || this.height !== height || this.depth !== depth ) { - - this.width = width; - this.height = height; - this.depth = depth; - - for ( let i = 0, il = this.texture.length; i < il; i ++ ) { - - this.texture[ i ].image.width = width; - this.texture[ i ].image.height = height; - this.texture[ i ].image.depth = depth; - - } - - this.dispose(); - - } - - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); - - } - - copy( source ) { - - this.dispose(); - - this.width = source.width; - this.height = source.height; - this.depth = source.depth; - - this.scissor.copy( source.scissor ); - this.scissorTest = source.scissorTest; - - this.viewport.copy( source.viewport ); - - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - - if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - - this.texture.length = 0; - - for ( let i = 0, il = source.texture.length; i < il; i ++ ) { - - this.texture[ i ] = source.texture[ i ].clone(); - this.texture[ i ].isRenderTargetTexture = true; - - } - - return this; - - } - - } - class Quaternion { constructor( x = 0, y = 0, z = 0, w = 1 ) { @@ -3810,23 +3729,24 @@ var THREE = (async function (exports) { random() { - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. + // sets this quaternion to a uniform random unit quaternnion - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt( 1 - u1 ); - const sqrtu1 = Math.sqrt( u1 ); + // Ken Shoemake + // Uniform random rotations + // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992. - const u2 = 2 * Math.PI * Math.random(); + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); - const u3 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt( 1 - x0 ); + const r2 = Math.sqrt( x0 ); return this.set( - sqrt1u1 * Math.cos( u2 ), - sqrtu1 * Math.sin( u3 ), - sqrtu1 * Math.cos( u3 ), - sqrt1u1 * Math.sin( u2 ), + r1 * Math.sin( theta1 ), + r1 * Math.cos( theta1 ), + r2 * Math.sin( theta2 ), + r2 * Math.cos( theta2 ), ); } @@ -4594,15 +4514,15 @@ var THREE = (async function (exports) { randomDirection() { - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + // https://mathworld.wolfram.com/SpherePointPicking.html - const u = ( Math.random() - 0.5 ) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt( 1 - u ** 2 ); + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt( 1 - u * u ); - this.x = f * Math.cos( t ); - this.y = f * Math.sin( t ); - this.z = u; + this.x = c * Math.cos( theta ); + this.y = u; + this.z = c * Math.sin( theta ); return this; @@ -6628,25 +6548,25 @@ var THREE = (async function (exports) { position.z = te[ 14 ]; // scale the rotation part - _m1$2.copy( this ); + _m1$4.copy( this ); const invSX = 1 / sx; const invSY = 1 / sy; const invSZ = 1 / sz; - _m1$2.elements[ 0 ] *= invSX; - _m1$2.elements[ 1 ] *= invSX; - _m1$2.elements[ 2 ] *= invSX; + _m1$4.elements[ 0 ] *= invSX; + _m1$4.elements[ 1 ] *= invSX; + _m1$4.elements[ 2 ] *= invSX; - _m1$2.elements[ 4 ] *= invSY; - _m1$2.elements[ 5 ] *= invSY; - _m1$2.elements[ 6 ] *= invSY; + _m1$4.elements[ 4 ] *= invSY; + _m1$4.elements[ 5 ] *= invSY; + _m1$4.elements[ 6 ] *= invSY; - _m1$2.elements[ 8 ] *= invSZ; - _m1$2.elements[ 9 ] *= invSZ; - _m1$2.elements[ 10 ] *= invSZ; + _m1$4.elements[ 8 ] *= invSZ; + _m1$4.elements[ 9 ] *= invSZ; + _m1$4.elements[ 10 ] *= invSZ; - quaternion.setFromRotationMatrix( _m1$2 ); + quaternion.setFromRotationMatrix( _m1$4 ); scale.x = sx; scale.y = sy; @@ -6787,14 +6707,14 @@ var THREE = (async function (exports) { } const _v1$5 = /*@__PURE__*/ new Vector3(); - const _m1$2 = /*@__PURE__*/ new Matrix4(); + const _m1$4 = /*@__PURE__*/ new Matrix4(); const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); const _x = /*@__PURE__*/ new Vector3(); const _y = /*@__PURE__*/ new Vector3(); const _z = /*@__PURE__*/ new Vector3(); - const _matrix$1 = /*@__PURE__*/ new Matrix4(); + const _matrix$2 = /*@__PURE__*/ new Matrix4(); const _quaternion$3 = /*@__PURE__*/ new Quaternion(); class Euler { @@ -7029,9 +6949,9 @@ var THREE = (async function (exports) { setFromQuaternion( q, order, update ) { - _matrix$1.makeRotationFromQuaternion( q ); + _matrix$2.makeRotationFromQuaternion( q ); - return this.setFromRotationMatrix( _matrix$1, order, update ); + return this.setFromRotationMatrix( _matrix$2, order, update ); } @@ -7166,8 +7086,8 @@ var THREE = (async function (exports) { const _v1$4 = /*@__PURE__*/ new Vector3(); const _q1 = /*@__PURE__*/ new Quaternion(); - const _m1$1 = /*@__PURE__*/ new Matrix4(); - const _target = /*@__PURE__*/ new Vector3(); + const _m1$3 = /*@__PURE__*/ new Matrix4(); + const _target$1 = /*@__PURE__*/ new Vector3(); const _position$3 = /*@__PURE__*/ new Vector3(); const _scale$2 = /*@__PURE__*/ new Vector3(); @@ -7180,6 +7100,9 @@ var THREE = (async function (exports) { const _addedEvent = { type: 'added' }; const _removedEvent = { type: 'removed' }; + const _childaddedEvent = { type: 'childadded', child: null }; + const _childremovedEvent = { type: 'childremoved', child: null }; + class Object3D extends EventDispatcher { constructor() { @@ -7416,7 +7339,7 @@ var THREE = (async function (exports) { this.updateWorldMatrix( true, false ); - return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() ); } @@ -7426,11 +7349,11 @@ var THREE = (async function (exports) { if ( x.isVector3 ) { - _target.copy( x ); + _target$1.copy( x ); } else { - _target.set( x, y, z ); + _target$1.set( x, y, z ); } @@ -7442,20 +7365,20 @@ var THREE = (async function (exports) { if ( this.isCamera || this.isLight ) { - _m1$1.lookAt( _position$3, _target, this.up ); + _m1$3.lookAt( _position$3, _target$1, this.up ); } else { - _m1$1.lookAt( _target, _position$3, this.up ); + _m1$3.lookAt( _target$1, _position$3, this.up ); } - this.quaternion.setFromRotationMatrix( _m1$1 ); + this.quaternion.setFromRotationMatrix( _m1$3 ); if ( parent ) { - _m1$1.extractRotation( parent.matrixWorld ); - _q1.setFromRotationMatrix( _m1$1 ); + _m1$3.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$3 ); this.quaternion.premultiply( _q1.invert() ); } @@ -7496,6 +7419,10 @@ var THREE = (async function (exports) { object.dispatchEvent( _addedEvent ); + _childaddedEvent.child = object; + this.dispatchEvent( _childaddedEvent ); + _childaddedEvent.child = null; + } else { console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); @@ -7529,6 +7456,10 @@ var THREE = (async function (exports) { object.dispatchEvent( _removedEvent ); + _childremovedEvent.child = object; + this.dispatchEvent( _childremovedEvent ); + _childremovedEvent.child = null; + } return this; @@ -7563,17 +7494,17 @@ var THREE = (async function (exports) { this.updateWorldMatrix( true, false ); - _m1$1.copy( this.matrixWorld ).invert(); + _m1$3.copy( this.matrixWorld ).invert(); if ( object.parent !== null ) { object.parent.updateWorldMatrix( true, false ); - _m1$1.multiply( object.parent.matrixWorld ); + _m1$3.multiply( object.parent.matrixWorld ); } - object.applyMatrix4( _m1$1 ); + object.applyMatrix4( _m1$3 ); this.add( object ); @@ -8163,7 +8094,7 @@ var THREE = (async function (exports) { const _v0$1 = /*@__PURE__*/ new Vector3(); const _v1$3 = /*@__PURE__*/ new Vector3(); const _v2$2 = /*@__PURE__*/ new Vector3(); - const _v3$1 = /*@__PURE__*/ new Vector3(); + const _v3$2 = /*@__PURE__*/ new Vector3(); const _vab = /*@__PURE__*/ new Vector3(); const _vac = /*@__PURE__*/ new Vector3(); @@ -8235,19 +8166,19 @@ var THREE = (async function (exports) { static containsPoint( point, a, b, c ) { // if the triangle is degenerate then we can't contain a point - if ( this.getBarycoord( point, a, b, c, _v3$1 ) === null ) { + if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) { return false; } - return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); + return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 ); } static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) { - if ( this.getBarycoord( point, p1, p2, p3, _v3$1 ) === null ) { + if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) { target.x = 0; target.y = 0; @@ -8258,9 +8189,9 @@ var THREE = (async function (exports) { } target.setScalar( 0 ); - target.addScaledVector( v1, _v3$1.x ); - target.addScaledVector( v2, _v3$1.y ); - target.addScaledVector( v3, _v3$1.z ); + target.addScaledVector( v1, _v3$2.x ); + target.addScaledVector( v2, _v3$2.y ); + target.addScaledVector( v3, _v3$2.z ); return target; @@ -9273,7 +9204,7 @@ var THREE = (async function (exports) { if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); - if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; @@ -9383,6 +9314,7 @@ var THREE = (async function (exports) { } + if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray(); if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; @@ -9627,6 +9559,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -9661,6 +9594,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -9888,7 +9822,7 @@ var THREE = (async function (exports) { get updateRange() { - console.warn( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 + warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 return this._updateRange; } @@ -10465,19 +10399,9 @@ var THREE = (async function (exports) { } - class Float64BufferAttribute extends BufferAttribute { - - constructor( array, itemSize, normalized ) { - - super( new Float64Array( array ), itemSize, normalized ); - - } - - } - - let _id$2 = 0; + let _id$2$1 = 0; - const _m1 = /*@__PURE__*/ new Matrix4(); + const _m1$2 = /*@__PURE__*/ new Matrix4(); const _obj = /*@__PURE__*/ new Object3D(); const _offset = /*@__PURE__*/ new Vector3(); const _box$2 = /*@__PURE__*/ new Box3(); @@ -10492,7 +10416,7 @@ var THREE = (async function (exports) { this.isBufferGeometry = true; - Object.defineProperty( this, 'id', { value: _id$2 ++ } ); + Object.defineProperty( this, 'id', { value: _id$2$1 ++ } ); this.uuid = generateUUID(); @@ -10643,9 +10567,9 @@ var THREE = (async function (exports) { applyQuaternion( q ) { - _m1.makeRotationFromQuaternion( q ); + _m1$2.makeRotationFromQuaternion( q ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10655,9 +10579,9 @@ var THREE = (async function (exports) { // rotate geometry around world x-axis - _m1.makeRotationX( angle ); + _m1$2.makeRotationX( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10667,9 +10591,9 @@ var THREE = (async function (exports) { // rotate geometry around world y-axis - _m1.makeRotationY( angle ); + _m1$2.makeRotationY( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10679,9 +10603,9 @@ var THREE = (async function (exports) { // rotate geometry around world z-axis - _m1.makeRotationZ( angle ); + _m1$2.makeRotationZ( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10691,9 +10615,9 @@ var THREE = (async function (exports) { // translate geometry - _m1.makeTranslation( x, y, z ); + _m1$2.makeTranslation( x, y, z ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10703,9 +10627,9 @@ var THREE = (async function (exports) { // scale geometry - _m1.makeScale( x, y, z ); + _m1$2.makeScale( x, y, z ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10765,7 +10689,7 @@ var THREE = (async function (exports) { if ( position && position.isGLBufferAttribute ) { - console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this ); this.boundingBox.set( new Vector3( - Infinity, - Infinity, - Infinity ), @@ -10835,7 +10759,7 @@ var THREE = (async function (exports) { if ( position && position.isGLBufferAttribute ) { - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this ); this.boundingSphere.set( new Vector3(), Infinity ); @@ -10952,24 +10876,21 @@ var THREE = (async function (exports) { } - const indices = index.array; - const positions = attributes.position.array; - const normals = attributes.normal.array; - const uvs = attributes.uv.array; - - const nVertices = positions.length / 3; + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; if ( this.hasAttribute( 'tangent' ) === false ) { - this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) ); } - const tangents = this.getAttribute( 'tangent' ).array; + const tangentAttribute = this.getAttribute( 'tangent' ); const tan1 = [], tan2 = []; - for ( let i = 0; i < nVertices; i ++ ) { + for ( let i = 0; i < positionAttribute.count; i ++ ) { tan1[ i ] = new Vector3(); tan2[ i ] = new Vector3(); @@ -10989,13 +10910,13 @@ var THREE = (async function (exports) { function handleTriangle( a, b, c ) { - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + vA.fromBufferAttribute( positionAttribute, a ); + vB.fromBufferAttribute( positionAttribute, b ); + vC.fromBufferAttribute( positionAttribute, c ); - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + uvA.fromBufferAttribute( uvAttribute, a ); + uvB.fromBufferAttribute( uvAttribute, b ); + uvC.fromBufferAttribute( uvAttribute, c ); vB.sub( vA ); vC.sub( vA ); @@ -11028,7 +10949,7 @@ var THREE = (async function (exports) { groups = [ { start: 0, - count: indices.length + count: index.count } ]; } @@ -11043,9 +10964,9 @@ var THREE = (async function (exports) { for ( let j = start, jl = start + count; j < jl; j += 3 ) { handleTriangle( - indices[ j + 0 ], - indices[ j + 1 ], - indices[ j + 2 ] + index.getX( j + 0 ), + index.getX( j + 1 ), + index.getX( j + 2 ) ); } @@ -11057,7 +10978,7 @@ var THREE = (async function (exports) { function handleVertex( v ) { - n.fromArray( normals, v * 3 ); + n.fromBufferAttribute( normalAttribute, v ); n2.copy( n ); const t = tan1[ v ]; @@ -11073,10 +10994,7 @@ var THREE = (async function (exports) { const test = tmp2.dot( tan2[ v ] ); const w = ( test < 0.0 ) ? - 1.0 : 1.0; - tangents[ v * 4 ] = tmp.x; - tangents[ v * 4 + 1 ] = tmp.y; - tangents[ v * 4 + 2 ] = tmp.z; - tangents[ v * 4 + 3 ] = w; + tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w ); } @@ -11089,9 +11007,9 @@ var THREE = (async function (exports) { for ( let j = start, jl = start + count; j < jl; j += 3 ) { - handleVertex( indices[ j + 0 ] ); - handleVertex( indices[ j + 1 ] ); - handleVertex( indices[ j + 2 ] ); + handleVertex( index.getX( j + 0 ) ); + handleVertex( index.getX( j + 1 ) ); + handleVertex( index.getX( j + 2 ) ); } @@ -11920,7 +11838,6 @@ var THREE = (async function (exports) { _uvC$1.fromBufferAttribute( uv1, c ); intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); - intersection.uv2 = intersection.uv1; // @deprecated, r152 } @@ -12271,7 +12188,8 @@ var THREE = (async function (exports) { fragDepth: false, // set to use fragment depth values drawBuffers: false, // set to use draw buffers shaderTextureLOD: false, // set to use shader texture LOD - clipCullDistance: false // set to use vertex shader clipping + clipCullDistance: false, // set to use vertex shader clipping + multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID }; // When rendered geometry doesn't include these attributes but the material does, @@ -12483,6 +12401,11 @@ var THREE = (async function (exports) { } + const _v3$1 = /*@__PURE__*/ new Vector3(); + const _minTarget = /*@__PURE__*/ new Vector2(); + const _maxTarget = /*@__PURE__*/ new Vector2(); + + class PerspectiveCamera extends Camera { constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { @@ -12581,6 +12504,34 @@ var THREE = (async function (exports) { } + /** + * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. + * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle. + */ + getViewBounds( distance, minTarget, maxTarget ) { + + _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + } + + /** + * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. + * Copies the result into the target Vector2, where x is width and y is height. + */ + getViewSize( distance, target ) { + + this.getViewBounds( distance, _minTarget, _maxTarget ); + + return target.subVectors( _maxTarget, _minTarget ); + + } + /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. @@ -12920,14 +12871,6 @@ var THREE = (async function (exports) { const image = { width: size, height: size, depth: 1 }; const images = [ image, image, image, image, image, image ]; - if ( options.encoding !== undefined ) { - - // @deprecated, r152 - warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' ); - options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) @@ -13573,7 +13516,7 @@ var THREE = (async function (exports) { function updateBuffer( buffer, attribute, bufferType ) { const array = attribute.array; - const updateRange = attribute._updateRange; // deprecated + const updateRange = attribute._updateRange; // @deprecated, r159 const updateRanges = attribute.updateRanges; gl.bindBuffer( bufferType, buffer ); @@ -13608,7 +13551,7 @@ var THREE = (async function (exports) { } - // deprecated + // @deprecated, r159 if ( updateRange.count !== - 1 ) { if ( isWebGL2 ) { @@ -13814,7 +13757,7 @@ var THREE = (async function (exports) { var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; - var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif"; var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; @@ -13836,7 +13779,7 @@ var THREE = (async function (exports) { var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; - var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif"; var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; @@ -13870,9 +13813,9 @@ var THREE = (async function (exports) { var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\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}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}"; - var 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, 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"; + var 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"; - var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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"; + var 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"; var 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"; @@ -13900,7 +13843,7 @@ var THREE = (async function (exports) { var 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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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"; - var 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, 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, 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"; + var 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"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; @@ -13940,11 +13883,13 @@ var THREE = (async function (exports) { var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + var 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"; + var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\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"; var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; - var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; @@ -14006,7 +13951,7 @@ var THREE = (async function (exports) { var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; - var 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 OptimizedCineonToneMapping( 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 CustomToneMapping( vec3 color ) { return color; }"; + var 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 OptimizedCineonToneMapping( 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\tfloat startCompression = 0.8 - 0.04;\n\tfloat 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(1, 1, 1), g);\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; var 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.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"; @@ -14026,67 +13971,67 @@ var THREE = (async function (exports) { const vertex$g = "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}"; - const fragment$g = "#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;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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}"; + const fragment$g = "#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}"; const vertex$f = "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}"; const fragment$f = "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}"; - const vertex$e = "#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#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}"; + const vertex$e = "#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}"; - const fragment$e = "#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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#endif\n}"; + const fragment$e = "#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#endif\n}"; - const vertex$d = "#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#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}"; + const vertex$d = "#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}"; - const fragment$d = "#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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}"; + const fragment$d = "#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}"; const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; const fragment$c = "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}"; - const vertex$b = "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}"; + const vertex$b = "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}"; - const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$b = "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}"; - const vertex$a = "#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#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}"; + const vertex$a = "#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}"; - const fragment$a = "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\t#include \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\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}"; + const fragment$a = "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}"; - const vertex$9 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + const vertex$9 = "#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}"; - const fragment$9 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$9 = "#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}"; - const vertex$8 = "#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\tvViewPosition = - mvPosition.xyz;\n}"; + const vertex$8 = "#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}"; - const fragment$8 = "#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\t#include \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\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}"; + const fragment$8 = "#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}"; - const vertex$7 = "#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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + const vertex$7 = "#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}"; - const fragment$7 = "#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\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + const fragment$7 = "#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}"; - const vertex$6 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + const vertex$6 = "#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}"; - const fragment$6 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$6 = "#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}"; - const vertex$5 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + const vertex$5 = "#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}"; - const fragment$5 = "#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_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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$5 = "#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_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}"; - const vertex$4 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + const vertex$4 = "#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}"; - const fragment$4 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$4 = "#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}"; - const vertex$3 = "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\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}"; + const vertex$3 = "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}"; - const fragment$3 = "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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$3 = "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}"; - const vertex$2 = "#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}"; + const vertex$2 = "#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}"; const fragment$2 = "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}"; const vertex$1 = "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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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}"; - const fragment$1 = "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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; + const fragment$1 = "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}"; const ShaderChunk = { alphahash_fragment: alphahash_fragment, @@ -14156,6 +14101,7 @@ var THREE = (async function (exports) { map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphinstance_vertex: morphinstance_vertex, morphcolor_vertex: morphcolor_vertex, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, @@ -14264,6 +14210,7 @@ var THREE = (async function (exports) { envmap: { envMap: { value: null }, + envMapRotation: { value: /*@__PURE__*/ new Matrix3() }, flipEnvMap: { value: - 1 }, reflectivity: { value: 1.0 }, // basic, lambert, phong ior: { value: 1.5 }, // physical @@ -14684,7 +14631,8 @@ var THREE = (async function (exports) { envMap: { value: null }, flipEnvMap: { value: - 1 }, backgroundBlurriness: { value: 0 }, - backgroundIntensity: { value: 1 } + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /*@__PURE__*/ new Matrix3() } }, vertexShader: ShaderChunk.backgroundCube_vert, @@ -14808,6 +14756,8 @@ var THREE = (async function (exports) { }; const _rgb = { r: 0, b: 0, g: 0 }; + const _e1$1 = /*@__PURE__*/ new Euler(); + const _m1$1 = /*@__PURE__*/ new Matrix4(); function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { @@ -14904,10 +14854,24 @@ var THREE = (async function (exports) { } + _e1$1.copy( scene.backgroundRotation ); + + // accommodate left-handed frame + _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1; + + if ( background.isCubeTexture && background.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1$1.y *= - 1; + _e1$1.z *= - 1; + + } + boxMesh.material.uniforms.envMap.value = background; boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) ); boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; if ( currentBackground !== background || @@ -16074,7 +16038,7 @@ var THREE = (async function (exports) { if ( image && image.height > 0 ) { - const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + const renderTarget = new WebGLCubeRenderTarget( image.height ); renderTarget.fromEquirectangularTexture( renderer, texture ); cubemaps.set( texture, renderTarget ); @@ -16372,6 +16336,7 @@ var THREE = (async function (exports) { * Generates a PMREM from an equirectangular texture, which can be either LDR * or HDR. The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. + * The smallest supported equirectangular image size is 64 x 32. */ fromEquirectangular( equirectangular, renderTarget = null ) { @@ -16383,6 +16348,7 @@ var THREE = (async function (exports) { * Generates a PMREM from an cubemap texture, which can be either LDR * or HDR. The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. + * The smallest supported cube size is 16 x 16. */ fromCubemap( cubemap, renderTarget = null ) { @@ -17890,24 +17856,31 @@ var THREE = (async function (exports) { } // + if ( object.isInstancedMesh === true && object.morphTexture !== null ) { - let morphInfluencesSum = 0; + program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures ); - for ( let i = 0; i < objectInfluences.length; i ++ ) { + } else { - morphInfluencesSum += objectInfluences[ i ]; + let morphInfluencesSum = 0; - } + for ( let i = 0; i < objectInfluences.length; i ++ ) { - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); - program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + } program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); - } else { // When object doesn't have morph target influences defined, we treat it as a 0-length array @@ -19456,6 +19429,10 @@ var THREE = (async function (exports) { toneMappingName = 'AgX'; break; + case NeutralToneMapping: + toneMappingName = 'Neutral'; + break; + case CustomToneMapping: toneMappingName = 'Custom'; break; @@ -19473,7 +19450,7 @@ var THREE = (async function (exports) { function generateExtensions( parameters ) { const chunks = [ - ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.alphaToCoverage || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' @@ -19486,7 +19463,8 @@ var THREE = (async function (exports) { function generateVertexExtensions( parameters ) { const chunks = [ - parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '' + parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '', + parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '', ]; return chunks.filter( filterEmptyLine ).join( '\n' ); @@ -19878,6 +19856,7 @@ var THREE = (async function (exports) { parameters.batching ? '#define USE_BATCHING' : '', parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', @@ -20009,6 +19988,12 @@ var THREE = (async function (exports) { '#endif', + '#ifdef USE_INSTANCING_MORPH', + + ' uniform sampler2D morphTexture;', + + '#endif', + 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', @@ -20097,6 +20082,7 @@ var THREE = (async function (exports) { parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', @@ -20298,6 +20284,8 @@ var THREE = (async function (exports) { console.error( 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Material Name: ' + self.name + '\n' + + 'Material Type: ' + self.type + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors @@ -20434,7 +20422,7 @@ var THREE = (async function (exports) { } - let _id$1 = 0; + let _id$1$1 = 0; class WebGLShaderCache { @@ -20548,7 +20536,7 @@ var THREE = (async function (exports) { constructor( code ) { - this.id = _id$1 ++; + this.id = _id$1$1 ++; this.code = code; this.usedTimes = 0; @@ -20561,6 +20549,7 @@ var THREE = (async function (exports) { const _programLayers = new Layers(); const _customShaders = new WebGLShaderCache(); + const _activeChannels = new Set(); const programs = []; const IS_WEBGL2 = capabilities.isWebGL2; @@ -20589,6 +20578,8 @@ var THREE = (async function (exports) { function getChannel( value ) { + _activeChannels.add( value ); + if ( value === 0 ) return 'uv'; return `uv${ value }`; @@ -20709,10 +20700,6 @@ var THREE = (async function (exports) { const HAS_EXTENSIONS = !! material.extensions; - const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1; - const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2; - const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3; - let toneMapping = NoToneMapping; if ( material.toneMapped ) { @@ -20748,9 +20735,11 @@ var THREE = (async function (exports) { batching: IS_BATCHEDMESH, instancing: IS_INSTANCEDMESH, instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ), + alphaToCoverage: !! material.alphaToCoverage, map: HAS_MAP, matcap: HAS_MATCAP, @@ -20796,7 +20785,7 @@ var THREE = (async function (exports) { gradientMap: HAS_GRADIENTMAP, - opaque: material.transparent === false && material.blending === NormalBlending, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, alphaMap: HAS_ALPHAMAP, alphaTest: HAS_ALPHATEST, @@ -20843,9 +20832,6 @@ var THREE = (async function (exports) { vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ), vertexColors: material.vertexColors, vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, - vertexUv1s: HAS_ATTRIBUTE_UV1, - vertexUv2s: HAS_ATTRIBUTE_UV2, - vertexUv3s: HAS_ATTRIBUTE_UV3, pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ), @@ -20907,7 +20893,8 @@ var THREE = (async function (exports) { extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true, extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true, extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true, - extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ), rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ), rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ), @@ -20918,6 +20905,14 @@ var THREE = (async function (exports) { }; + // the usage of getChannel() determines the active texture channels for this shader + + parameters.vertexUv1s = _activeChannels.has( 1 ); + parameters.vertexUv2s = _activeChannels.has( 2 ); + parameters.vertexUv3s = _activeChannels.has( 3 ); + + _activeChannels.clear(); + return parameters; } @@ -21027,38 +21022,40 @@ var THREE = (async function (exports) { _programLayers.enable( 2 ); if ( parameters.instancingColor ) _programLayers.enable( 3 ); - if ( parameters.matcap ) + if ( parameters.instancingMorph ) _programLayers.enable( 4 ); - if ( parameters.envMap ) + if ( parameters.matcap ) _programLayers.enable( 5 ); - if ( parameters.normalMapObjectSpace ) + if ( parameters.envMap ) _programLayers.enable( 6 ); - if ( parameters.normalMapTangentSpace ) + if ( parameters.normalMapObjectSpace ) _programLayers.enable( 7 ); - if ( parameters.clearcoat ) + if ( parameters.normalMapTangentSpace ) _programLayers.enable( 8 ); - if ( parameters.iridescence ) + if ( parameters.clearcoat ) _programLayers.enable( 9 ); - if ( parameters.alphaTest ) + if ( parameters.iridescence ) _programLayers.enable( 10 ); - if ( parameters.vertexColors ) + if ( parameters.alphaTest ) _programLayers.enable( 11 ); - if ( parameters.vertexAlphas ) + if ( parameters.vertexColors ) _programLayers.enable( 12 ); - if ( parameters.vertexUv1s ) + if ( parameters.vertexAlphas ) _programLayers.enable( 13 ); - if ( parameters.vertexUv2s ) + if ( parameters.vertexUv1s ) _programLayers.enable( 14 ); - if ( parameters.vertexUv3s ) + if ( parameters.vertexUv2s ) _programLayers.enable( 15 ); - if ( parameters.vertexTangents ) + if ( parameters.vertexUv3s ) _programLayers.enable( 16 ); - if ( parameters.anisotropy ) + if ( parameters.vertexTangents ) _programLayers.enable( 17 ); - if ( parameters.alphaHash ) + if ( parameters.anisotropy ) _programLayers.enable( 18 ); - if ( parameters.batching ) + if ( parameters.alphaHash ) _programLayers.enable( 19 ); + if ( parameters.batching ) + _programLayers.enable( 20 ); array.push( _programLayers.mask ); _programLayers.disableAll(); @@ -21103,6 +21100,8 @@ var THREE = (async function (exports) { _programLayers.enable( 18 ); if ( parameters.decodeVideoTexture ) _programLayers.enable( 19 ); + if ( parameters.alphaToCoverage ) + _programLayers.enable( 20 ); array.push( _programLayers.mask ); @@ -23161,33 +23160,19 @@ var THREE = (async function (exports) { } - if ( renderTarget.isWebGLMultipleRenderTargets ) { + const textures = renderTarget.textures; - const textures = renderTarget.texture; - - if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - - for ( let i = 0, il = textures.length; i < il; i ++ ) { - - drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; - - } + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - drawBuffers.length = textures.length; + for ( let i = 0, il = textures.length; i < il; i ++ ) { - needsUpdate = true; + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; } - } else { - - if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - - drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0; - - needsUpdate = true; + drawBuffers.length = textures.length; - } + needsUpdate = true; } @@ -23209,10 +23194,14 @@ var THREE = (async function (exports) { gl.drawBuffers( drawBuffers ); - } else { + } else if ( extensions.has( 'WEBGL_draw_buffers' ) === true ) { extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + } else { + + throw new Error( 'THREE.WebGLState: Usage of gl.drawBuffers() require WebGL2 or WEBGL_draw_buffers extension' ); + } } @@ -23999,6 +23988,7 @@ var THREE = (async function (exports) { const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + const _imageDimensions = new Vector2(); const _videoTextures = new WeakMap(); let _canvas; @@ -24036,11 +24026,13 @@ var THREE = (async function (exports) { let scale = 1; + const dimensions = getDimensions( image ); + // handle case if texture exceeds max size - if ( image.width > maxSize || image.height > maxSize ) { + if ( dimensions.width > maxSize || dimensions.height > maxSize ) { - scale = maxSize / Math.max( image.width, image.height ); + scale = maxSize / Math.max( dimensions.width, dimensions.height ); } @@ -24052,12 +24044,13 @@ var THREE = (async function (exports) { if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) || + ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) { const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; - const width = floor( scale * image.width ); - const height = floor( scale * image.height ); + const width = floor( scale * dimensions.width ); + const height = floor( scale * dimensions.height ); if ( _canvas === undefined ) _canvas = createCanvas( width, height ); @@ -24071,7 +24064,7 @@ var THREE = (async function (exports) { const context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, width, height ); - console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' ); return canvas; @@ -24079,7 +24072,7 @@ var THREE = (async function (exports) { if ( 'data' in image ) { - console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' ); } @@ -24095,7 +24088,9 @@ var THREE = (async function (exports) { function isPowerOfTwo$1( image ) { - return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + const dimensions = getDimensions( image ); + + return isPowerOfTwo( dimensions.width ) && isPowerOfTwo( dimensions.height ); } @@ -24162,6 +24157,17 @@ var THREE = (async function (exports) { } + if ( glFormat === _gl.RG_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I; + if ( glType === _gl.INT ) internalFormat = _gl.RG32I; + + } + if ( glFormat === _gl.RGBA ) { const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace ); @@ -24309,18 +24315,7 @@ var THREE = (async function (exports) { function deallocateRenderTarget( renderTarget ) { - const texture = renderTarget.texture; - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); - - if ( textureProperties.__webglTexture !== undefined ) { - - _gl.deleteTexture( textureProperties.__webglTexture ); - - info.memory.textures --; - - } if ( renderTarget.depthTexture ) { @@ -24375,27 +24370,24 @@ var THREE = (async function (exports) { } - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - for ( let i = 0, il = texture.length; i < il; i ++ ) { - - const attachmentProperties = properties.get( texture[ i ] ); + const textures = renderTarget.textures; - if ( attachmentProperties.__webglTexture ) { + for ( let i = 0, il = textures.length; i < il; i ++ ) { - _gl.deleteTexture( attachmentProperties.__webglTexture ); + const attachmentProperties = properties.get( textures[ i ] ); - info.memory.textures --; + if ( attachmentProperties.__webglTexture ) { - } + _gl.deleteTexture( attachmentProperties.__webglTexture ); - properties.remove( texture[ i ] ); + info.memory.textures --; } + properties.remove( textures[ i ] ); + } - properties.remove( texture ); properties.remove( renderTarget ); } @@ -24615,8 +24607,6 @@ var THREE = (async function (exports) { if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 @@ -24624,6 +24614,7 @@ var THREE = (async function (exports) { if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); properties.get( texture ).__currentAnisotropy = texture.anisotropy; @@ -24757,6 +24748,7 @@ var THREE = (async function (exports) { const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format ); const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; const levels = getMipLevels( texture, image, supportsMips ); if ( texture.isDepthTexture ) { @@ -24869,7 +24861,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -24891,7 +24887,11 @@ var THREE = (async function (exports) { } - state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } } else { @@ -24921,7 +24921,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + if ( dataReady ) { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } } else { @@ -24939,7 +24943,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } } else { @@ -24969,7 +24977,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } } else { @@ -24987,7 +24999,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -25011,7 +25027,11 @@ var THREE = (async function (exports) { } - state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } } else { @@ -25029,7 +25049,11 @@ var THREE = (async function (exports) { } - state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } } else { @@ -25074,7 +25098,9 @@ var THREE = (async function (exports) { if ( useTexStorage && allocateMemory ) { - state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + const dimensions = getDimensions( mipmaps[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); } @@ -25084,7 +25110,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } } else { @@ -25102,11 +25132,17 @@ var THREE = (async function (exports) { if ( allocateMemory ) { - state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + const dimensions = getDimensions( image ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); } - state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } } else { @@ -25187,6 +25223,7 @@ var THREE = (async function (exports) { const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; let levels = getMipLevels( texture, image, supportsMips ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); @@ -25215,7 +25252,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } } else { @@ -25233,7 +25274,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -25259,7 +25304,9 @@ var THREE = (async function (exports) { if ( mipmaps.length > 0 ) levels ++; - state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + const dimensions = getDimensions( cubeImage[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height ); } @@ -25269,7 +25316,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } } else { @@ -25284,7 +25335,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } } else { @@ -25298,7 +25353,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } } else { @@ -25312,7 +25371,11 @@ var THREE = (async function (exports) { if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } } else { @@ -25459,7 +25522,7 @@ var THREE = (async function (exports) { } else { - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; for ( let i = 0; i < textures.length; i ++ ) { @@ -25623,7 +25686,13 @@ var THREE = (async function (exports) { renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + const textures = renderTarget.textures; + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + if ( ! isMultipleRenderTargets ) { if ( textureProperties.__webglTexture === undefined ) { @@ -25636,10 +25705,6 @@ var THREE = (async function (exports) { } - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - // Setup framebuffer if ( isCube ) { @@ -25688,8 +25753,6 @@ var THREE = (async function (exports) { if ( capabilities.drawBuffers ) { - const textures = renderTarget.texture; - for ( let i = 0, il = textures.length; i < il; i ++ ) { const attachmentProperties = properties.get( textures[ i ] ); @@ -25714,8 +25777,6 @@ var THREE = (async function (exports) { if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - const textures = isMultipleRenderTargets ? texture : [ texture ]; - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); renderTargetProperties.__webglColorRenderbuffer = []; @@ -25788,8 +25849,6 @@ var THREE = (async function (exports) { } else if ( isMultipleRenderTargets ) { - const textures = renderTarget.texture; - for ( let i = 0, il = textures.length; i < il; i ++ ) { const attachment = textures[ i ]; @@ -25868,7 +25927,7 @@ var THREE = (async function (exports) { const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; for ( let i = 0, il = textures.length; i < il; i ++ ) { @@ -25893,14 +25952,14 @@ var THREE = (async function (exports) { if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; const width = renderTarget.width; const height = renderTarget.height; let mask = _gl.COLOR_BUFFER_BIT; const invalidationArray = []; const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; const renderTargetProperties = properties.get( renderTarget ); - const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); // If MRT we need to remove FBO attachments if ( isMultipleRenderTargets ) { @@ -26084,6 +26143,31 @@ var THREE = (async function (exports) { } + function getDimensions( image ) { + + if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) { + + // if intrinsic data are not available, fallback to width/height + + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + + } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) { + + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + + } else { + + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + + } + + return _imageDimensions; + + } + // this.allocateTextureUnit = allocateTextureUnit; @@ -26747,6 +26831,105 @@ var THREE = (async function (exports) { } + const _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + + const _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + + class WebXRDepthSensing { + + constructor() { + + this.texture = null; + this.mesh = null; + + this.depthNear = 0; + this.depthFar = 0; + + } + + init( renderer, depthData, renderState ) { + + if ( this.texture === null ) { + + const texture = new Texture(); + + const texProps = renderer.properties.get( texture ); + texProps.__webglTexture = depthData.texture; + + if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) { + + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + + } + + this.texture = texture; + + } + + } + + render( renderer, cameraXR ) { + + if ( this.texture !== null ) { + + if ( this.mesh === null ) { + + const viewport = cameraXR.cameras[ 0 ].viewport; + const material = new ShaderMaterial( { + extensions: { fragDepth: true }, + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + } ); + + this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material ); + + } + + renderer.render( this.mesh, cameraXR ); + + } + + } + + reset() { + + this.texture = null; + this.mesh = null; + + } + + } + class WebXRManager extends EventDispatcher { constructor( renderer, gl ) { @@ -26770,7 +26953,10 @@ var THREE = (async function (exports) { let glProjLayer = null; let glBaseLayer = null; let xrFrame = null; + + const depthSensing = new WebXRDepthSensing(); const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; let newRenderTarget = null; @@ -26900,6 +27086,8 @@ var THREE = (async function (exports) { _currentDepthNear = null; _currentDepthFar = null; + depthSensing.reset(); + // restore framebuffer/rendering state renderer.setRenderTarget( initialRenderTarget ); @@ -27258,6 +27446,13 @@ var THREE = (async function (exports) { if ( session === null ) return; + if ( depthSensing.texture !== null ) { + + camera.near = depthSensing.depthNear; + camera.far = depthSensing.depthFar; + + } + cameraXR.near = cameraR.near = cameraL.near = camera.near; cameraXR.far = cameraR.far = cameraL.far = camera.far; @@ -27273,6 +27468,15 @@ var THREE = (async function (exports) { _currentDepthNear = cameraXR.near; _currentDepthFar = cameraXR.far; + cameraL.near = _currentDepthNear; + cameraL.far = _currentDepthFar; + cameraR.near = _currentDepthNear; + cameraR.far = _currentDepthFar; + + cameraL.updateProjectionMatrix(); + cameraR.updateProjectionMatrix(); + camera.updateProjectionMatrix(); + } const parent = camera.parent; @@ -27374,6 +27578,12 @@ var THREE = (async function (exports) { }; + this.hasDepthSensing = function () { + + return depthSensing.texture !== null; + + }; + // Animation Loop let onAnimationFrameCallback = null; @@ -27466,6 +27676,22 @@ var THREE = (async function (exports) { } + // + + const enabledFeatures = session.enabledFeatures; + + if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) { + + const depthData = glBinding.getDepthInformation( views[ 0 ] ); + + if ( depthData && depthData.isValid && depthData.texture ) { + + depthSensing.init( renderer, depthData, session.renderState ); + + } + + } + } // @@ -27483,6 +27709,8 @@ var THREE = (async function (exports) { } + depthSensing.render( renderer, cameraXR ); + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); if ( frame.detectedPlanes ) { @@ -27511,6 +27739,9 @@ var THREE = (async function (exports) { } + const _e1 = /*@__PURE__*/ new Euler(); + const _m1 = /*@__PURE__*/ new Matrix4(); + function WebGLMaterials( renderer, properties ) { function refreshTransformUniform( map, uniform ) { @@ -27719,12 +27950,30 @@ var THREE = (async function (exports) { } - const envMap = properties.get( material ).envMap; + const materialProperties = properties.get( material ); + + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; if ( envMap ) { uniforms.envMap.value = envMap; + _e1.copy( envMapRotation ); + + // accommodate left-handed frame + _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1; + + if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1.y *= - 1; + _e1.z *= - 1; + + } + + uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) ); + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; uniforms.reflectivity.value = material.reflectivity; @@ -28892,7 +29141,7 @@ var THREE = (async function (exports) { } - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() ); }; @@ -28914,7 +29163,7 @@ var THREE = (async function (exports) { } - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() ); }; @@ -29610,7 +29859,11 @@ var THREE = (async function (exports) { // - background.render( currentRenderList, scene ); + if ( xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false ) { + + background.render( currentRenderList, scene ); + + } // render scene @@ -30011,6 +30264,7 @@ var THREE = (async function (exports) { materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; materialProperties.fog = scene.fog; materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation; if ( programs === undefined ) { @@ -30123,6 +30377,7 @@ var THREE = (async function (exports) { materialProperties.batching = parameters.batching; materialProperties.instancing = parameters.instancing; materialProperties.instancingColor = parameters.instancingColor; + materialProperties.instancingMorph = parameters.instancingMorph; materialProperties.skinning = parameters.skinning; materialProperties.morphTargets = parameters.morphTargets; materialProperties.morphNormals = parameters.morphNormals; @@ -30233,6 +30488,14 @@ var THREE = (async function (exports) { needsProgramChange = true; + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) { + + needsProgramChange = true; + } else if ( materialProperties.envMap !== envMap ) { needsProgramChange = true; @@ -30561,20 +30824,16 @@ var THREE = (async function (exports) { const renderTargetProperties = properties.get( renderTarget ); renderTargetProperties.__hasExternalTextures = true; - if ( renderTargetProperties.__hasExternalTextures ) { + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { - if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - // The multisample_render_to_texture extension doesn't work properly if there - // are midframe flushes and an external depth buffer. Disable use of the extension. - if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - - console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); - renderTargetProperties.__useRenderToTexture = false; - - } + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; } @@ -30834,8 +31093,8 @@ var THREE = (async function (exports) { } - const width = sourceBox.max.x - sourceBox.min.x + 1; - const height = sourceBox.max.y - sourceBox.min.y + 1; + const width = Math.round( sourceBox.max.x - sourceBox.min.x ); + const height = Math.round( sourceBox.max.y - sourceBox.min.y ); const depth = sourceBox.max.z - sourceBox.min.z + 1; const glFormat = utils.convert( dstTexture.format ); const glType = utils.convert( dstTexture.type ); @@ -30882,9 +31141,8 @@ var THREE = (async function (exports) { } else { - if ( srcTexture.isCompressedArrayTexture ) { + if ( dstTexture.isCompressedArrayTexture ) { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); } else { @@ -30973,20 +31231,6 @@ var THREE = (async function (exports) { } - get outputEncoding() { // @deprecated, r152 - - console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); - return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - - set outputEncoding( encoding ) { // @deprecated, r152 - - console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); - this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; - - } - get useLegacyLights() { // @deprecated, r155 console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' ); @@ -31090,6 +31334,8 @@ var THREE = (async function (exports) { this.backgroundBlurriness = 0; this.backgroundIntensity = 1; + this.backgroundRotation = new Euler(); + this.environmentRotation = new Euler(); this.overrideMaterial = null; @@ -31111,6 +31357,8 @@ var THREE = (async function (exports) { this.backgroundBlurriness = source.backgroundBlurriness; this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy( source.backgroundRotation ); + this.environmentRotation.copy( source.environmentRotation ); if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); @@ -31128,6 +31376,9 @@ var THREE = (async function (exports) { if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + data.object.backgroundRotation = this.backgroundRotation.toArray(); + data.object.environmentRotation = this.environmentRotation.toArray(); + return data; } @@ -31164,7 +31415,7 @@ var THREE = (async function (exports) { get updateRange() { - console.warn( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 + warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 return this._updateRange; } @@ -31379,6 +31630,26 @@ var THREE = (async function (exports) { } + getComponent( index, component ) { + + let value = this.array[ index * this.data.stride + this.offset + component ]; + + if ( this.normalized ) value = denormalize( value, this.array ); + + return value; + + } + + setComponent( index, component, value ) { + + if ( this.normalized ) value = normalize$1( value, this.array ); + + this.data.array[ index * this.data.stride + this.offset + component ] = value; + + return this; + + } + setX( index, x ) { if ( this.normalized ) x = normalize$1( x, this.array ); @@ -32651,6 +32922,7 @@ var THREE = (async function (exports) { this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); this.instanceColor = null; + this.morphTexture = null; this.count = count; @@ -32756,6 +33028,24 @@ var THREE = (async function (exports) { } + getMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const array = this.morphTexture.source.data.data; + + const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum + + const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + objectInfluences[ i ] = array[ dataIndex + i ]; + + } + + } + raycast( raycaster, intersects ) { const matrixWorld = this.matrixWorld; @@ -32826,6 +33116,38 @@ var THREE = (async function (exports) { } + setMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const len = objectInfluences.length + 1; // morphBaseInfluence + all influences + + if ( this.morphTexture === null ) { + + this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType ); + + } + + const array = this.morphTexture.source.data.data; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + const dataIndex = len * index; + + array[ dataIndex ] = morphBaseInfluence; + + array.set( objectInfluences, dataIndex + 1 ); + + } + updateMorphTargets() { } @@ -32896,7 +33218,7 @@ var THREE = (async function (exports) { } const ID_ATTR_NAME = 'batchId'; - const _matrix = /*@__PURE__*/ new Matrix4(); + const _matrix$1 = /*@__PURE__*/ new Matrix4(); const _invMatrixWorld = /*@__PURE__*/ new Matrix4(); const _identityMatrix = /*@__PURE__*/ new Matrix4(); const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4(); @@ -33119,8 +33441,8 @@ var THREE = (async function (exports) { if ( active[ i ] === false ) continue; - this.getMatrixAt( i, _matrix ); - this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix$1 ); boundingBox.union( _box$1 ); } @@ -33144,8 +33466,8 @@ var THREE = (async function (exports) { if ( active[ i ] === false ) continue; - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); boundingSphere.union( _sphere$2 ); } @@ -33735,7 +34057,7 @@ var THREE = (async function (exports) { .multiply( this.matrixWorld ); _frustum$1.setFromProjectionMatrix( _projScreenMatrix$2, - renderer.isWebGPURenderer ? WebGPUCoordinateSystem : WebGLCoordinateSystem + renderer.coordinateSystem ); } @@ -33752,8 +34074,8 @@ var THREE = (async function (exports) { if ( visibility[ i ] && active[ i ] ) { // get the bounds in world space - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); // determine whether the batched geometry is within the frustum let culled = false; @@ -33810,8 +34132,8 @@ var THREE = (async function (exports) { if ( perObjectFrustumCulled ) { // get the bounds in world space - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); culled = ! _frustum$1.intersectsSphere( _sphere$2 ); } @@ -34940,9 +35262,9 @@ var THREE = (async function (exports) { } - getPoint( t, optionalTarget ) { + getPoint( t, optionalTarget = new Vector2() ) { - const point = optionalTarget || new Vector2(); + const point = optionalTarget; const twoPi = Math.PI * 2; let deltaAngle = this.aEndAngle - this.aStartAngle; @@ -37402,7 +37724,7 @@ var THREE = (async function (exports) { const _v0 = /*@__PURE__*/ new Vector3(); const _v1$1 = /*@__PURE__*/ new Vector3(); - const _normal = /*@__PURE__*/ new Vector3(); + const _normal$2 = /*@__PURE__*/ new Vector3(); const _triangle = /*@__PURE__*/ new Triangle(); class EdgesGeometry extends BufferGeometry { @@ -37454,7 +37776,7 @@ var THREE = (async function (exports) { a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); - _triangle.getNormal( _normal ); + _triangle.getNormal( _normal$2 ); // create hashes for the edge from the vertices hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; @@ -37485,7 +37807,7 @@ var THREE = (async function (exports) { // if we found a sibling edge add it into the vertex array if // it meets the angle threshold and delete the edge from the map. - if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + if ( _normal$2.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { vertices.push( v0.x, v0.y, v0.z ); vertices.push( v1.x, v1.y, v1.z ); @@ -37501,7 +37823,7 @@ var THREE = (async function (exports) { index0: indexArr[ j ], index1: indexArr[ jNext ], - normal: _normal.clone(), + normal: _normal$2.clone(), }; @@ -37707,7 +38029,7 @@ var THREE = (async function (exports) { } - if ( last && equals( last, last.next ) ) { + if ( last && equals$1( last, last.next ) ) { removeNode( last ); last = last.next; @@ -37730,7 +38052,7 @@ var THREE = (async function (exports) { again = false; - if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { removeNode( p ); p = end = p.prev; @@ -37915,7 +38237,7 @@ var THREE = (async function (exports) { const a = p.prev, b = p.next.next; - if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { triangles.push( a.i / dim | 0 ); triangles.push( p.i / dim | 0 ); @@ -38238,7 +38560,7 @@ var THREE = (async function (exports) { return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case } @@ -38250,7 +38572,7 @@ var THREE = (async function (exports) { } // check if two points are equal - function equals( p1, p2 ) { + function equals$1( p1, p2 ) { return p1.x === p2.x && p1.y === p2.y; @@ -40599,6 +40921,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.envMapIntensity = 1.0; this.wireframe = false; @@ -40654,6 +40977,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.envMapIntensity = source.envMapIntensity; this.wireframe = source.wireframe; @@ -40931,6 +41255,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -40984,6 +41309,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -41195,6 +41521,7 @@ var THREE = (async function (exports) { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -41246,6 +41573,7 @@ var THREE = (async function (exports) { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -44088,10 +44416,6 @@ var THREE = (async function (exports) { texture.colorSpace = texData.colorSpace; - } else if ( texData.encoding !== undefined ) { // @deprecated, r152 - - texture.encoding = texData.encoding; - } if ( texData.flipY !== undefined ) { @@ -45327,6 +45651,7 @@ var THREE = (async function (exports) { if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation ); if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; @@ -46307,7 +46632,6 @@ var THREE = (async function (exports) { if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat; if ( data.type !== undefined ) texture.type = data.type; if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace; - if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152 if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); @@ -46446,6 +46770,8 @@ var THREE = (async function (exports) { if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation ); + if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation ); break; @@ -50756,7 +51082,7 @@ var THREE = (async function (exports) { } - let _id$3 = 0; + let _id$4 = 0; class UniformsGroup$1 extends EventDispatcher { @@ -50766,7 +51092,7 @@ var THREE = (async function (exports) { this.isUniformsGroup = true; - Object.defineProperty( this, 'id', { value: _id$3 ++ } ); + Object.defineProperty( this, 'id', { value: _id$4 ++ } ); this.name = ''; @@ -50954,6 +51280,8 @@ var THREE = (async function (exports) { } + const _matrix = /*@__PURE__*/ new Matrix4(); + class Raycaster { constructor( origin, direction, near = 0, far = Infinity ) { @@ -51006,9 +51334,20 @@ var THREE = (async function (exports) { } + setFromXRController( controller ) { + + _matrix.identity().extractRotation( controller.matrixWorld ); + + this.ray.origin.setFromMatrixPosition( controller.matrixWorld ); + this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix ); + + return this; + + } + intersectObject( object, recursive = true, intersects = [] ) { - intersectObject( object, this, intersects, recursive ); + intersect( object, this, intersects, recursive ); intersects.sort( ascSort ); @@ -51020,7 +51359,7 @@ var THREE = (async function (exports) { for ( let i = 0, l = objects.length; i < l; i ++ ) { - intersectObject( objects[ i ], this, intersects, recursive ); + intersect( objects[ i ], this, intersects, recursive ); } @@ -51038,7 +51377,7 @@ var THREE = (async function (exports) { } - function intersectObject( object, raycaster, intersects, recursive ) { + function intersect( object, raycaster, intersects, recursive ) { if ( object.layers.test( raycaster.layers ) ) { @@ -51052,7 +51391,7 @@ var THREE = (async function (exports) { for ( let i = 0, l = children.length; i < l; i ++ ) { - intersectObject( children[ i ], raycaster, intersects, true ); + intersect( children[ i ], raycaster, intersects, true ); } @@ -51526,7 +51865,6 @@ var THREE = (async function (exports) { this.light = light; - this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; this.color = color; @@ -51578,6 +51916,24 @@ var THREE = (async function (exports) { this.light.updateWorldMatrix( true, false ); this.light.target.updateWorldMatrix( true, false ); + // update the local matrix based on the parent and light target transforms + if ( this.parent ) { + + this.parent.updateWorldMatrix( true ); + + this.matrix + .copy( this.parent.matrixWorld ) + .invert() + .multiply( this.light.matrixWorld ); + + } else { + + this.matrix.copy( this.light.matrixWorld ); + + } + + this.matrixWorld.copy( this.light.matrixWorld ); + const coneLength = this.light.distance ? this.light.distance : 1000; const coneWidth = coneLength * Math.tan( this.light.angle ); @@ -53018,6 +53374,26 @@ var THREE = (async function (exports) { } + class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162 + + constructor( width = 1, height = 1, count = 1, options = {} ) { + + console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' ); + + super( width, height, { ...options, count } ); + + this.isWebGLMultipleRenderTargets = true; + + } + + get texture() { + + return this.textures; + + } + + } + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { @@ -53040,23 +53416,20 @@ var THREE = (async function (exports) { } - if ( window.GPUShaderStage === undefined ) { + if ( self.GPUShaderStage === undefined ) { - window.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; + self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; } - let isAvailable = false; - - if ( navigator.gpu !== undefined ) { + // statics - const adapter = await( navigator.gpu.requestAdapter()); + let isAvailable = navigator.gpu !== undefined; - if ( adapter !== null ) { - isAvailable = true; + if ( typeof window !== 'undefined' && isAvailable ) { - } + isAvailable = await( navigator.gpu.requestAdapter()); } @@ -53064,6 +53437,12 @@ var THREE = (async function (exports) { static isAvailable() { + return Boolean( isAvailable ); + + } + + static getStaticAdapter() { + return isAvailable; } @@ -53228,6 +53607,168 @@ var THREE = (async function (exports) { } + const _plane = new Plane(); + const _viewNormalMatrix = new Matrix3(); + + let _clippingContextVersion = 0; + + class ClippingContext { + + constructor() { + + this.version = ++ _clippingContextVersion; + + this.globalClippingCount = 0; + + this.localClippingCount = 0; + this.localClippingEnabled = false; + this.localClipIntersection = false; + + this.planes = []; + + this.parentVersion = 0; + + } + + projectPlanes( source, offset ) { + + const l = source.length; + const planes = this.planes; + + for ( let i = 0; i < l; i ++ ) { + + _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, _viewNormalMatrix ); + + const v = planes[ offset + i ]; + const normal = _plane.normal; + + v.x = - normal.x; + v.y = - normal.y; + v.z = - normal.z; + v.w = _plane.constant; + + } + + } + + updateGlobal( renderer, camera ) { + + const rendererClippingPlanes = renderer.clippingPlanes; + this.viewMatrix = camera.matrixWorldInverse; + + _viewNormalMatrix.getNormalMatrix( this.viewMatrix ); + + let update = false; + + if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) { + + const l = rendererClippingPlanes.length; + + if ( l !== this.globalClippingCount ) { + + const planes = []; + + for ( let i = 0; i < l; i ++ ) { + + planes.push( new Vector4() ); + + } + + this.globalClippingCount = l; + this.planes = planes; + + update = true; + + } + + this.projectPlanes( rendererClippingPlanes, 0 ); + + } else if ( this.globalClippingCount !== 0 ) { + + this.globalClippingCount = 0; + this.planes = []; + update = true; + + } + + if ( renderer.localClippingEnabled !== this.localClippingEnabled ) { + + this.localClippingEnabled = renderer.localClippingEnabled; + update = true; + + } + + if ( update ) this.version = _clippingContextVersion ++; + + } + + update( parent, material ) { + + let update = false; + + if ( this !== parent && parent.version !== this.parentVersion ) { + + this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount; + this.localClippingEnabled = parent.localClippingEnabled; + this.planes = Array.from( parent.planes ); + this.parentVersion = parent.version; + this.viewMatrix = parent.viewMatrix; + + + update = true; + + } + + if ( this.localClippingEnabled ) { + + const localClippingPlanes = material.clippingPlanes; + + if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) { + + const l = localClippingPlanes.length; + const planes = this.planes; + const offset = this.globalClippingCount; + + if ( update || l !== this.localClippingCount ) { + + planes.length = offset + l; + + for ( let i = 0; i < l; i ++ ) { + + planes[ offset + i ] = new Vector4(); + + } + + this.localClippingCount = l; + update = true; + + } + + this.projectPlanes( localClippingPlanes, offset ); + + + } else if ( this.localClippingCount !== 0 ) { + + this.localClippingCount = 0; + update = true; + + } + + if ( this.localClipIntersection !== material.clipIntersection ) { + + this.localClipIntersection = material.clipIntersection; + update = true; + + } + + } + + if ( update ) this.version = _clippingContextVersion ++; + + } + + } + let id$4 = 0; class RenderObject { @@ -53254,6 +53795,10 @@ var THREE = (async function (exports) { this.pipeline = null; this.vertexBuffers = null; + this.updateClipping( renderContext.clippingContext ); + + this.clippingContextVersion = this.clippingContext.version; + this.initialNodesCacheKey = this.getNodesCacheKey(); this.initialCacheKey = this.getCacheKey(); @@ -53274,6 +53819,41 @@ var THREE = (async function (exports) { } + updateClipping( parent ) { + + const material = this.material; + + let clippingContext = this.clippingContext; + + if ( Array.isArray( material.clippingPlanes ) ) { + + if ( clippingContext === parent || ! clippingContext ) { + + clippingContext = new ClippingContext(); + this.clippingContext = clippingContext; + + } + + clippingContext.update( parent, material ); + + } else if ( this.clippingContext !== parent ) { + + this.clippingContext = parent; + + } + + } + + clippingNeedsUpdate () { + + if ( this.clippingContext.version === this.clippingContextVersion ) return false; + + this.clippingContextVersion = this.clippingContext.version; + + return true; + + } + getNodeBuilderState() { return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) ); @@ -53361,9 +53941,11 @@ var THREE = (async function (exports) { } + cacheKey += this.clippingContextVersion + ','; + if ( object.skeleton ) { - cacheKey += object.skeleton.uuid + ','; + cacheKey += object.skeleton.bones.length + ','; } @@ -53437,7 +54019,9 @@ var THREE = (async function (exports) { } else { - if ( renderObject.version !== material.version || renderObject.needsUpdate ) { + renderObject.updateClipping( renderContext.clippingContext ); + + if ( renderObject.version !== material.version || renderObject.needsUpdate || renderObject.clippingNeedsUpdate() ) { if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) { @@ -53860,7 +54444,8 @@ var THREE = (async function (exports) { }; this.compute = { - calls: 0 + calls: 0, + computeCalls: 0 }; this.memory = { @@ -53868,6 +54453,11 @@ var THREE = (async function (exports) { textures: 0 }; + this.timestamp = { + compute: 0, + render: 0 + }; + } update( object, count, instanceCount ) { @@ -53894,6 +54484,20 @@ var THREE = (async function (exports) { } + updateTimestamp( type, time ) { + + this.timestamp[ type ] += time; + + } + + resetCompute() { + + this.compute.computeCalls = 0; + + this.timestamp.compute = 0; + + } + reset() { this.render.drawCalls = 0; @@ -53901,6 +54505,8 @@ var THREE = (async function (exports) { this.render.points = 0; this.render.lines = 0; + this.timestamp.render = 0; + } dispose() { @@ -53912,6 +54518,8 @@ var THREE = (async function (exports) { this.render.calls = 0; this.compute.calls = 0; + this.timestamp.compute = 0; + this.timestamp.render = 0; this.memory.geometries = 0; this.memory.textures = 0; @@ -53958,16 +54566,18 @@ var THREE = (async function (exports) { } - let _id = 0; + let _id$3 = 0; class ProgrammableStage { - constructor( code, type ) { + constructor( code, type, transforms = null, attributes = null ) { - this.id = _id ++; + this.id = _id$3 ++; this.code = code; this.stage = type; + this.transforms = transforms; + this.attributes = attributes; this.usedTimes = 0; @@ -54014,18 +54624,18 @@ var THREE = (async function (exports) { // get shader - const nodeBuilder = this.nodes.getForCompute( computeNode ); + const nodeBuilderState = this.nodes.getForCompute( computeNode ); // programmable stage - let stageCompute = this.programs.compute.get( nodeBuilder.computeShader ); + let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader ); if ( stageCompute === undefined ) { if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram ); - stageCompute = new ProgrammableStage( nodeBuilder.computeShader, 'compute' ); - this.programs.compute.set( nodeBuilder.computeShader, stageCompute ); + stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes ); + this.programs.compute.set( nodeBuilderState.computeShader, stageCompute ); backend.createProgram( stageCompute ); @@ -54061,7 +54671,7 @@ var THREE = (async function (exports) { } - getForRender( renderObject ) { + getForRender( renderObject, promises = null ) { const { backend } = this; @@ -54121,7 +54731,7 @@ var THREE = (async function (exports) { if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline ); - pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey ); + pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ); } else { @@ -54222,7 +54832,7 @@ var THREE = (async function (exports) { } - _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey ) { + _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) { // check for existing pipeline @@ -54238,7 +54848,7 @@ var THREE = (async function (exports) { renderObject.pipeline = pipeline; - this.backend.createRenderPipeline( renderObject ); + this.backend.createRenderPipeline( renderObject, promises ); } @@ -54338,7 +54948,7 @@ var THREE = (async function (exports) { const nodeBuilderState = this.nodes.getForCompute( computeNode ); - const bindings = nodeBuilderState.bindings.compute; + const bindings = nodeBuilderState.bindings; data.bindings = bindings; @@ -54479,6 +55089,7 @@ var THREE = (async function (exports) { VECTOR2: 'vec2', VECTOR3: 'vec3', VECTOR4: 'vec4', + MATRIX2: 'mat2', MATRIX3: 'mat3', MATRIX4: 'mat4' }; @@ -54744,7 +55355,7 @@ var THREE = (async function (exports) { } - updateReference() { + setReference( /*state*/ ) { return this; @@ -54852,12 +55463,20 @@ var THREE = (async function (exports) { } - analyze( builder ) { + increaseUsage( builder ) { const nodeData = builder.getDataFromNode( this ); - nodeData.dependenciesCount = nodeData.dependenciesCount === undefined ? 1 : nodeData.dependenciesCount + 1; + nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; + + return nodeData.usageCount; + + } - if ( nodeData.dependenciesCount === 1 ) { + analyze( builder ) { + + const usageCount = this.increaseUsage( builder ); + + if ( usageCount === 1 ) { // node flow children @@ -54921,6 +55540,8 @@ var THREE = (async function (exports) { if ( buildStage === 'setup' ) { + this.setReference( builder ); + const properties = builder.getNodeProperties( this ); if ( properties.initialized !== true || builder.context.tempRead === false ) { @@ -55176,114 +55797,60 @@ var THREE = (async function (exports) { } - class InputNode extends Node { - - constructor( value, nodeType = null ) { - - super( nodeType ); - - this.isInputNode = true; - - this.value = value; - this.precision = null; - - } - - getNodeType( /*builder*/ ) { - - if ( this.nodeType === null ) { - - return getValueType( this.value ); - - } - - return this.nodeType; - - } - - getInputType( builder ) { - - return this.getNodeType( builder ); - - } + class TempNode extends Node { - setPrecision( precision ) { + constructor( type ) { - this.precision = precision; + super( type ); - return this; + this.isTempNode = true; } - serialize( data ) { - - super.serialize( data ); - - data.value = this.value; - - if ( this.value && this.value.toArray ) data.value = this.value.toArray(); - - data.valueType = getValueType( this.value ); - data.nodeType = this.nodeType; - - if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + hasDependencies( builder ) { - data.precision = this.precision; + return builder.getDataFromNode( this ).usageCount > 1; } - deserialize( data ) { - - super.deserialize( data ); - - this.nodeType = data.nodeType; - this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; - - this.precision = data.precision || null; - - if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + build( builder, output ) { - } + const buildStage = builder.getBuildStage(); - generate( /*builder, output*/ ) { + if ( buildStage === 'generate' ) { - } + const type = builder.getVectorType( this.getNodeType( builder, output ) ); + const nodeData = builder.getDataFromNode( this ); - } + if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { - addNodeClass( 'InputNode', InputNode ); + return builder.format( nodeData.propertyName, type, output ); - class UniformGroupNode extends Node { + } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - constructor( name, shared = false ) { + const snippet = super.build( builder, type ); - super( 'string' ); + const nodeVar = builder.getVarFromNode( this, null, type ); + const propertyName = builder.getPropertyName( nodeVar ); - this.name = name; - this.version = 0; + builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - this.shared = shared; + nodeData.snippet = snippet; + nodeData.propertyName = propertyName; - this.isUniformGroup = true; + return builder.format( nodeData.propertyName, type, output ); - } + } - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + return super.build( builder, output ); } } - const uniformGroup = ( name ) => new UniformGroupNode( name ); - const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); - - const frameGroup = sharedUniformGroup( 'frame' ); - const renderGroup = sharedUniformGroup( 'render' ); - const objectGroup = uniformGroup( 'object' ); - - addNodeClass( 'UniformGroupNode', UniformGroupNode ); + addNodeClass( 'TempNode', TempNode ); class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute @@ -55379,61 +55946,6 @@ var THREE = (async function (exports) { addNodeClass( 'ConvertNode', ConvertNode ); - class TempNode extends Node { - - constructor( type ) { - - super( type ); - - this.isTempNode = true; - - } - - hasDependencies( builder ) { - - return builder.getDataFromNode( this ).dependenciesCount > 1; - - } - - build( builder, output ) { - - const buildStage = builder.getBuildStage(); - - if ( buildStage === 'generate' ) { - - const type = builder.getVectorType( this.getNodeType( builder, output ) ); - const nodeData = builder.getDataFromNode( this ); - - if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { - - return builder.format( nodeData.propertyName, type, output ); - - } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - - const snippet = super.build( builder, type ); - - const nodeVar = builder.getVarFromNode( this, null, type ); - const propertyName = builder.getPropertyName( nodeVar ); - - builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - - nodeData.snippet = snippet; - nodeData.propertyName = propertyName; - - return builder.format( nodeData.propertyName, type, output ); - - } - - } - - return super.build( builder, output ); - - } - - } - - addNodeClass( 'TempNode', TempNode ); - class JoinNode extends TempNode { constructor( nodes = [], nodeType = null ) { @@ -55461,7 +55973,7 @@ var THREE = (async function (exports) { const type = this.getNodeType( builder ); const nodes = this.nodes; - const primitiveType = builder.getPrimitiveType( type ); + const primitiveType = builder.getComponentType( type ); const snippetValues = []; @@ -55469,7 +55981,7 @@ var THREE = (async function (exports) { let inputSnippet = input.build( builder ); - const inputPrimitiveType = builder.getPrimitiveType( input.getNodeType( builder ) ); + const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) ); if ( inputPrimitiveType !== primitiveType ) { @@ -55520,15 +56032,15 @@ var THREE = (async function (exports) { } - getPrimitiveType( builder ) { + getComponentType( builder ) { - return builder.getPrimitiveType( this.node.getNodeType( builder ) ); + return builder.getComponentType( this.node.getNodeType( builder ) ); } getNodeType( builder ) { - return builder.getTypeFromLength( this.components.length, this.getPrimitiveType( builder ) ); + return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) ); } @@ -55549,7 +56061,7 @@ var THREE = (async function (exports) { // needed expand the input node - type = builder.getTypeFromLength( this.getVectorLength(), this.getPrimitiveType( builder ) ); + type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) ); } @@ -55656,6 +56168,83 @@ var THREE = (async function (exports) { addNodeClass( 'SetNode', SetNode ); + class InputNode extends Node { + + constructor( value, nodeType = null ) { + + super( nodeType ); + + this.isInputNode = true; + + this.value = value; + this.precision = null; + + } + + getNodeType( /*builder*/ ) { + + if ( this.nodeType === null ) { + + return getValueType( this.value ); + + } + + return this.nodeType; + + } + + getInputType( builder ) { + + return this.getNodeType( builder ); + + } + + setPrecision( precision ) { + + this.precision = precision; + + return this; + + } + + serialize( data ) { + + super.serialize( data ); + + data.value = this.value; + + if ( this.value && this.value.toArray ) data.value = this.value.toArray(); + + data.valueType = getValueType( this.value ); + data.nodeType = this.nodeType; + + if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + + data.precision = this.precision; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.nodeType = data.nodeType; + this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; + + this.precision = data.precision || null; + + if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + + } + + generate( /*builder, output*/ ) { + + } + + } + + addNodeClass( 'InputNode', InputNode ); + class ConstNode extends InputNode { constructor( value, nodeType = null ) { @@ -56241,6 +56830,11 @@ var THREE = (async function (exports) { const uvec4 = new ConvertType( 'uvec4' ); const bvec4 = new ConvertType( 'bvec4' ); + const mat2 = new ConvertType( 'mat2' ); + const imat2 = new ConvertType( 'imat2' ); + const umat2 = new ConvertType( 'umat2' ); + const bmat2 = new ConvertType( 'bmat2' ); + const mat3 = new ConvertType( 'mat3' ); const imat3 = new ConvertType( 'imat3' ); const umat3 = new ConvertType( 'umat3' ); @@ -56271,6 +56865,10 @@ var THREE = (async function (exports) { addNodeElement( 'ivec4', ivec4 ); addNodeElement( 'uvec4', uvec4 ); addNodeElement( 'bvec4', bvec4 ); + addNodeElement( 'mat2', mat2 ); + addNodeElement( 'imat2', imat2 ); + addNodeElement( 'umat2', umat2 ); + addNodeElement( 'bmat2', bmat2 ); addNodeElement( 'mat3', mat3 ); addNodeElement( 'imat3', imat3 ); addNodeElement( 'umat3', umat3 ); @@ -56291,159 +56889,118 @@ var THREE = (async function (exports) { addNodeElement( 'element', element ); addNodeElement( 'convert', convert ); - class UniformNode extends InputNode { - - constructor( value, nodeType = null ) { - - super( value, nodeType ); - - this.isUniformNode = true; - - this.groupNode = objectGroup; - - } + class AssignNode extends TempNode { - setGroup( group ) { + constructor( targetNode, sourceNode ) { - this.groupNode = group; + super(); - return this; + this.targetNode = targetNode; + this.sourceNode = sourceNode; } - getGroup() { + hasDependencies() { - return this.groupNode; + return false; } - getUniformHash( builder ) { + getNodeType( builder, output ) { - return this.getHash( builder ); + return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; } - generate( builder, output ) { + needsSplitAssign( builder ) { - const type = this.getNodeType( builder ); + const { targetNode } = this; - const hash = this.getUniformHash( builder ); + if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) { - let sharedNode = builder.getNodeFromHash( hash ); + const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) ); + const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components; - if ( sharedNode === undefined ) { - - builder.setHashNode( this, hash ); - - sharedNode = this; + return assignDiferentVector; } - const sharedNodeType = sharedNode.getInputType( builder ); - - const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); - const propertyName = builder.getPropertyName( nodeUniform ); - - if ( builder.context.label !== undefined ) delete builder.context.label; - - return builder.format( propertyName, type, output ); - - } - - } - - const uniform = ( arg1, arg2 ) => { - - const nodeType = getConstNodeType( arg2 || arg1 ); - - // @TODO: get ConstNode from .traverse() in the future - const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; - - return nodeObject( new UniformNode( value, nodeType ) ); - - }; - - addNodeClass( 'UniformNode', UniformNode ); - - class ArrayUniformNode extends UniformNode { - - constructor( nodes = [] ) { - - super(); - - this.isArrayUniformNode = true; - - this.nodes = nodes; + return false; } - getNodeType( builder ) { + generate( builder, output ) { - return this.nodes[ 0 ].getNodeType( builder ); + const { targetNode, sourceNode } = this; - } + const needsSplitAssign = this.needsSplitAssign( builder ); - } + const targetType = targetNode.getNodeType( builder ); - addNodeClass( 'ArrayUniformNode', ArrayUniformNode ); + const target = targetNode.context( { assign: true } ).build( builder ); + const source = sourceNode.build( builder, targetType ); - class AssignNode extends TempNode { + const sourceType = sourceNode.getNodeType( builder ); - constructor( targetNode, sourceNode ) { + const nodeData = builder.getDataFromNode( this ); - super(); + // - this.targetNode = targetNode; - this.sourceNode = sourceNode; + let snippet; - } + if ( nodeData.initialized === true ) { - hasDependencies() { + if ( output !== 'void' ) { - return false; + snippet = target; - } + } - getNodeType( builder, output ) { + } else if ( needsSplitAssign ) { - return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; + const sourceVar = builder.getVarFromNode( this, null, targetType ); + const sourceProperty = builder.getPropertyName( sourceVar ); - } + builder.addLineFlowCode( `${ sourceProperty } = ${ source }` ); - generate( builder, output ) { + const targetRoot = targetNode.node.context( { assign: true } ).build( builder ); - const targetNode = this.targetNode; - const sourceNode = this.sourceNode; + for ( let i = 0; i < targetNode.components.length; i ++ ) { - const targetType = targetNode.getNodeType( builder ); + const component = targetNode.components[ i ]; - const target = targetNode.build( builder ); - const source = sourceNode.build( builder, targetType ); + builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` ); - const snippet = `${ target } = ${ source }`; + } - if ( output === 'void' ) { + if ( output !== 'void' ) { - builder.addLineFlowCode( snippet ); + snippet = target; - return; + } } else { - const sourceType = sourceNode.getNodeType( builder ); + snippet = `${ target } = ${ source }`; - if ( sourceType === 'void' ) { + if ( output === 'void' || sourceType === 'void' ) { builder.addLineFlowCode( snippet ); - return target; + if ( output !== 'void' ) { - } + snippet = target; + + } - return builder.format( snippet, targetType, output ); + } } + nodeData.initialized = true; + + return builder.format( snippet, targetType, output ); + } } @@ -57199,6 +57756,12 @@ var THREE = (async function (exports) { } + isGlobal() { + + return true; + + } + setIncludes( includes ) { this.includes = includes; @@ -57383,6 +57946,112 @@ var THREE = (async function (exports) { addNodeClass( 'FunctionNode', FunctionNode ); + class UniformGroupNode extends Node { + + constructor( name, shared = false ) { + + super( 'string' ); + + this.name = name; + this.version = 0; + + this.shared = shared; + + this.isUniformGroup = true; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + } + + const uniformGroup = ( name ) => new UniformGroupNode( name ); + const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); + + const frameGroup = sharedUniformGroup( 'frame' ); + const renderGroup = sharedUniformGroup( 'render' ); + const objectGroup = uniformGroup( 'object' ); + + addNodeClass( 'UniformGroupNode', UniformGroupNode ); + + class UniformNode extends InputNode { + + constructor( value, nodeType = null ) { + + super( value, nodeType ); + + this.isUniformNode = true; + + this.groupNode = objectGroup; + + } + + setGroup( group ) { + + this.groupNode = group; + + return this; + + } + + getGroup() { + + return this.groupNode; + + } + + getUniformHash( builder ) { + + return this.getHash( builder ); + + } + + generate( builder, output ) { + + const type = this.getNodeType( builder ); + + const hash = this.getUniformHash( builder ); + + let sharedNode = builder.getNodeFromHash( hash ); + + if ( sharedNode === undefined ) { + + builder.setHashNode( this, hash ); + + sharedNode = this; + + } + + const sharedNodeType = sharedNode.getInputType( builder ); + + const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); + const propertyName = builder.getPropertyName( nodeUniform ); + + if ( builder.context.label !== undefined ) delete builder.context.label; + + return builder.format( propertyName, type, output ); + + } + + } + + const uniform = ( arg1, arg2 ) => { + + const nodeType = getConstNodeType( arg2 || arg1 ); + + // @TODO: get ConstNode from .traverse() in the future + const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; + + return nodeObject( new UniformNode( value, nodeType ) ); + + }; + + addNodeClass( 'UniformNode', UniformNode ); + class UVNode extends AttributeNode { constructor( index = 0 ) { @@ -57490,7 +58159,7 @@ var THREE = (async function (exports) { const bNode = this.bNode; const typeA = aNode.getNodeType( builder ); - const typeB = bNode.getNodeType( builder ); + const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( typeA === 'void' || typeB === 'void' ) { @@ -57500,11 +58169,11 @@ var THREE = (async function (exports) { return typeA; - } else if ( op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { + } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { return builder.getIntegerType( typeA ); - } else if ( op === '==' || op === '&&' || op === '||' || op === '^^' ) { + } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) { return 'bool'; @@ -57561,7 +58230,7 @@ var THREE = (async function (exports) { if ( type !== 'void' ) { typeA = aNode.getNodeType( builder ); - typeB = bNode.getNodeType( builder ); + typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) { @@ -57607,7 +58276,7 @@ var THREE = (async function (exports) { } const a = aNode.build( builder, typeA ); - const b = bNode.build( builder, typeB ); + const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null; const outputLength = builder.getTypeLength( output ); const fnOpSnippet = builder.getFunctionOperator( op ); @@ -57630,6 +58299,10 @@ var THREE = (async function (exports) { return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output ); + } else if ( op === '!' || op === '~' ) { + + return builder.format( `(${op}${a})`, typeA, output ); + } else if ( fnOpSnippet ) { return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output ); @@ -57687,8 +58360,10 @@ var THREE = (async function (exports) { const greaterThanEqual = nodeProxy( OperatorNode, '>=' ); const and = nodeProxy( OperatorNode, '&&' ); const or = nodeProxy( OperatorNode, '||' ); + const not = nodeProxy( OperatorNode, '!' ); const xor = nodeProxy( OperatorNode, '^^' ); const bitAnd = nodeProxy( OperatorNode, '&' ); + const bitNot = nodeProxy( OperatorNode, '~' ); const bitOr = nodeProxy( OperatorNode, '|' ); const bitXor = nodeProxy( OperatorNode, '^' ); const shiftLeft = nodeProxy( OperatorNode, '<<' ); @@ -57707,8 +58382,10 @@ var THREE = (async function (exports) { addNodeElement( 'greaterThanEqual', greaterThanEqual ); addNodeElement( 'and', and ); addNodeElement( 'or', or ); + addNodeElement( 'not', not ); addNodeElement( 'xor', xor ); addNodeElement( 'bitAnd', bitAnd ); + addNodeElement( 'bitNot', bitNot ); addNodeElement( 'bitOr', bitOr ); addNodeElement( 'bitXor', bitXor ); addNodeElement( 'shiftLeft', shiftLeft ); @@ -57770,6 +58447,14 @@ var THREE = (async function (exports) { return 'vec3'; + } else if ( method === MathNode.ALL ) { + + return 'bool'; + + } else if ( method === MathNode.EQUALS ) { + + return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' ); + } else if ( method === MathNode.MOD ) { return this.aNode.getNodeType( builder ); @@ -57908,6 +58593,10 @@ var THREE = (async function (exports) { // 1 input + MathNode.ALL = 'all'; + MathNode.ANY = 'any'; + MathNode.EQUALS = 'equals'; + MathNode.RADIANS = 'radians'; MathNode.DEGREES = 'degrees'; MathNode.EXP = 'exp'; @@ -57964,6 +58653,12 @@ var THREE = (async function (exports) { const EPSILON = float( 1e-6 ); const INFINITY = float( 1e6 ); + const PI = float( Math.PI ); + const PI2 = float( Math.PI * 2 ); + + const all = nodeProxy( MathNode, MathNode.ALL ); + const any = nodeProxy( MathNode, MathNode.ANY ); + const equals = nodeProxy( MathNode, MathNode.EQUALS ); const radians = nodeProxy( MathNode, MathNode.RADIANS ); const degrees = nodeProxy( MathNode, MathNode.DEGREES ); @@ -58013,6 +58708,7 @@ var THREE = (async function (exports) { const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ); const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) ); + const lengthSq = ( a ) => dot( a, a ); const mix = nodeProxy( MathNode, MathNode.MIX ); const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) ); const saturate = ( value ) => clamp( value ); @@ -58023,6 +58719,10 @@ var THREE = (async function (exports) { const mixElement = ( t, e1, e2 ) => mix( e1, e2, t ); const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x ); + addNodeElement( 'all', all ); + addNodeElement( 'any', any ); + addNodeElement( 'equals', equals ); + addNodeElement( 'radians', radians ); addNodeElement( 'degrees', degrees ); addNodeElement( 'exp', exp ); @@ -58044,6 +58744,7 @@ var THREE = (async function (exports) { addNodeElement( 'abs', abs ); addNodeElement( 'sign', sign ); addNodeElement( 'length', length ); + addNodeElement( 'lengthSq', lengthSq ); addNodeElement( 'negate', negate ); addNodeElement( 'oneMinus', oneMinus ); addNodeElement( 'dFdx', dFdx ); @@ -58297,7 +58998,7 @@ var THREE = (async function (exports) { } - updateReference( /*frame*/ ) { + setReference( /*state*/ ) { return this.value; @@ -58606,440 +59307,428 @@ var THREE = (async function (exports) { addNodeClass( 'TextureNode', TextureNode ); - class ReferenceNode extends Node { - - constructor( property, uniformType, object = null ) { + class BufferNode extends UniformNode { - super(); + constructor( value, bufferType, bufferCount = 0 ) { - this.property = property; - this.index = null; + super( value, bufferType ); - this.uniformType = uniformType; + this.isBufferNode = true; - this.object = object; - this.reference = null; + this.bufferType = bufferType; + this.bufferCount = bufferCount; - this.node = null; + } - this.updateType = NodeUpdateType.OBJECT; + getInputType( /*builder*/ ) { - this.setNodeType( uniformType ); + return 'buffer'; } - updateReference( frame ) { + } - this.reference = this.object !== null ? this.object : frame.object; + const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - return this.reference; + addNodeClass( 'BufferNode', BufferNode ); - } + class UniformsElementNode extends ArrayElementNode { - setIndex( index ) { + constructor( arrayBuffer, indexNode ) { - this.index = index; + super( arrayBuffer, indexNode ); - return this; + this.isArrayBufferElementNode = true; } - getIndex() { + getNodeType( builder ) { - return this.index; + return this.node.getElementType( builder ); } - setNodeType( uniformType ) { + generate( builder ) { - let node = null; + const snippet = super.generate( builder ); + const type = this.getNodeType(); - if ( uniformType === 'texture' ) { + return builder.format( snippet, 'vec4', type ); - node = texture( null ); + } - } else { + } - node = uniform( uniformType ); + class UniformsNode extends BufferNode { - } + constructor( value, elementType = null ) { - this.node = node; + super( null, 'vec4' ); - } + this.array = value; + this.elementType = elementType; - getNodeType( builder ) { + this._elementType = null; + this._elementLength = 0; - return this.node.getNodeType( builder ); + this.updateType = NodeUpdateType.RENDER; - } + this.isArrayBufferNode = true; - update( /*frame*/ ) { + } - let value = this.reference[ this.property ]; + getElementType() { - if ( this.index !== null ) { + return this.elementType || this._elementType; - value = value[ this.index ]; + } - } + getElementLength() { - this.node.value = value; + return this._elementLength; } - setup( /*builder*/ ) { + update( /*frame*/ ) { - return this.node; + const { array, value } = this; - } + const elementLength = this.getElementLength(); + const elementType = this.getElementType(); - } + if ( elementLength === 1 ) { - const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); - const referenceIndex = ( name, index, type, object ) => nodeObject( new ReferenceNode( name, type, object ).setIndex( index ) ); + for ( let i = 0; i < array.length; i ++ ) { - addNodeClass( 'ReferenceNode', ReferenceNode ); + const index = i * 4; - class MaterialReferenceNode extends ReferenceNode { + value[ index ] = array[ i ]; - constructor( property, inputType, material = null ) { + } - super( property, inputType, material ); + } else if ( elementType === 'color' ) { - this.material = material; + for ( let i = 0; i < array.length; i ++ ) { - //this.updateType = NodeUpdateType.RENDER; + const index = i * 4; + const vector = array[ i ]; - } + value[ index ] = vector.r; + value[ index + 1 ] = vector.g; + value[ index + 2 ] = vector.b || 0; + //value[ index + 3 ] = vector.a || 0; - /*setNodeType( node ) { + } - super.setNodeType( node ); + } else { - this.node.groupNode = renderGroup; + for ( let i = 0; i < array.length; i ++ ) { - }*/ + const index = i * 4; + const vector = array[ i ]; - updateReference( frame ) { + value[ index ] = vector.x; + value[ index + 1 ] = vector.y; + value[ index + 2 ] = vector.z || 0; + value[ index + 3 ] = vector.w || 0; - this.reference = this.material !== null ? this.material : frame.material; + } - return this.reference; + } } setup( builder ) { - const material = this.material !== null ? this.material : builder.material; + const length = this.array.length; - this.node.value = material[ this.property ]; + this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType; + this._elementLength = builder.getTypeLength( this._elementType ); + + this.value = new Float32Array( length * 4 ); + this.bufferCount = length; return super.setup( builder ); } - } + element( indexNode ) { - const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); + return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) ); - addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); - - class Object3DNode extends Node { + } - constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { + } - super(); + const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) ); - this.scope = scope; - this.object3d = object3d; + addNodeClass( 'UniformsNode', UniformsNode ); - this.updateType = NodeUpdateType.OBJECT; + class ReferenceElementNode extends ArrayElementNode { - this._uniformNode = new UniformNode( null ); + constructor( referenceNode, indexNode ) { - } + super( referenceNode, indexNode ); - getNodeType() { + this.referenceNode = referenceNode; - const scope = this.scope; + this.isReferenceElementNode = true; - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - return 'mat4'; + getNodeType() { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + return this.referenceNode.uniformType; - return 'mat3'; + } - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + generate( builder ) { - return 'vec3'; + const snippet = super.generate( builder ); + const arrayType = this.referenceNode.getNodeType(); + const elementType = this.getNodeType(); - } + return builder.format( snippet, arrayType, elementType ); } - update( frame ) { + } - const object = this.object3d; - const uniformNode = this._uniformNode; - const scope = this.scope; + class ReferenceNode extends Node { - if ( scope === Object3DNode.VIEW_MATRIX ) { + constructor( property, uniformType, object = null, count = null ) { - uniformNode.value = object.modelViewMatrix; + super(); - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + this.property = property; + this.uniformType = uniformType; + this.object = object; + this.count = count; - uniformNode.value = object.normalMatrix; + this.properties = property.split( '.' ); + this.reference = null; + this.node = null; - } else if ( scope === Object3DNode.WORLD_MATRIX ) { + this.updateType = NodeUpdateType.OBJECT; - uniformNode.value = object.matrixWorld; + } - } else if ( scope === Object3DNode.POSITION ) { + element( indexNode ) { - uniformNode.value = uniformNode.value || new Vector3(); + return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) ); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } - } else if ( scope === Object3DNode.SCALE ) { + setNodeType( uniformType ) { - uniformNode.value = uniformNode.value || new Vector3(); + let node = null; - uniformNode.value.setFromMatrixScale( object.matrixWorld ); + if ( this.count !== null ) { - } else if ( scope === Object3DNode.DIRECTION ) { + node = buffer( null, uniformType, this.count ); - uniformNode.value = uniformNode.value || new Vector3(); + } else if ( Array.isArray( this.getValueFromReference() ) ) { - object.getWorldDirection( uniformNode.value ); + node = uniforms( null, uniformType ); - } else if ( scope === Object3DNode.VIEW_POSITION ) { + } else if ( uniformType === 'texture' ) { - const camera = frame.camera; + node = texture( null ); - uniformNode.value = uniformNode.value || new Vector3(); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } else { - uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); + node = uniform( null, uniformType ); } + this.node = node; + } - generate( builder ) { + getNodeType( builder ) { - const scope = this.scope; + return this.node.getNodeType( builder ); - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - this._uniformNode.nodeType = 'mat4'; + getValueFromReference( object = this.reference ) { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + const { properties } = this; - this._uniformNode.nodeType = 'mat3'; + let value = object[ properties[ 0 ] ]; - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + for ( let i = 1; i < properties.length; i ++ ) { - this._uniformNode.nodeType = 'vec3'; + value = value[ properties[ i ] ]; } - return this._uniformNode.build( builder ); + return value; } - serialize( data ) { + setReference( state ) { - super.serialize( data ); + this.reference = this.object !== null ? this.object : state.object; - data.scope = this.scope; + return this.reference; } - deserialize( data ) { + setup() { - super.deserialize( data ); + this.updateValue(); - this.scope = data.scope; + return this.node; } - } + update( /*frame*/ ) { - Object3DNode.VIEW_MATRIX = 'viewMatrix'; - Object3DNode.NORMAL_MATRIX = 'normalMatrix'; - Object3DNode.WORLD_MATRIX = 'worldMatrix'; - Object3DNode.POSITION = 'position'; - Object3DNode.SCALE = 'scale'; - Object3DNode.VIEW_POSITION = 'viewPosition'; - Object3DNode.DIRECTION = 'direction'; + this.updateValue(); - const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION ); - const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX ); - const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX ); - const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ); - const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION ); - const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE ); - const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ); + } - addNodeClass( 'Object3DNode', Object3DNode ); + updateValue() { - //const cameraGroup = sharedUniformGroup( 'camera' ); + if ( this.node === null ) this.setNodeType( this.uniformType ); - class CameraNode extends Object3DNode { + const value = this.getValueFromReference(); - constructor( scope = CameraNode.POSITION ) { + if ( Array.isArray( value ) ) { - super( scope ); + this.node.array = value; - this.updateType = NodeUpdateType.RENDER; + } else { - //this._uniformNode.groupNode = cameraGroup; + this.node.value = value; + + } } - getNodeType( builder ) { + } - const scope = this.scope; + const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); + const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) ); - if ( scope === CameraNode.PROJECTION_MATRIX ) { + addNodeClass( 'ReferenceNode', ReferenceNode ); - return 'mat4'; + class MaterialReferenceNode extends ReferenceNode { - } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + constructor( property, inputType, material = null ) { - return 'float'; + super( property, inputType, material ); - } + this.material = material; - return super.getNodeType( builder ); + //this.updateType = NodeUpdateType.RENDER; } - update( frame ) { + /*setNodeType( node ) { - const camera = frame.camera; - const uniformNode = this._uniformNode; - const scope = this.scope; + super.setNodeType( node ); - //cameraGroup.needsUpdate = true; + this.node.groupNode = renderGroup; - if ( scope === CameraNode.VIEW_MATRIX ) { + }*/ - uniformNode.value = camera.matrixWorldInverse; + setReference( state ) { - } else if ( scope === CameraNode.PROJECTION_MATRIX ) { + this.reference = this.material !== null ? this.material : state.material; - uniformNode.value = camera.projectionMatrix; + return this.reference; - } else if ( scope === CameraNode.NEAR ) { + } - uniformNode.value = camera.near; + } - } else if ( scope === CameraNode.FAR ) { + const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); - uniformNode.value = camera.far; + addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); - } else if ( scope === CameraNode.LOG_DEPTH ) { + class Object3DNode extends Node { - uniformNode.value = 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ); + constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { - } else { + super(); - this.object3d = camera; + this.scope = scope; + this.object3d = object3d; - super.update( frame ); + this.updateType = NodeUpdateType.OBJECT; - } + this._uniformNode = new UniformNode( null ); } - generate( builder ) { + getNodeType() { const scope = this.scope; - if ( scope === CameraNode.PROJECTION_MATRIX ) { - - this._uniformNode.nodeType = 'mat4'; - - } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { - this._uniformNode.nodeType = 'float'; + return 'mat4'; - } + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - return super.generate( builder ); + return 'mat3'; - } + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { - } + return 'vec3'; - CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; - CameraNode.NEAR = 'near'; - CameraNode.FAR = 'far'; - CameraNode.LOG_DEPTH = 'logDepth'; + } - const cameraProjectionMatrix = label( nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ), 'projectionMatrix' ); - const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); - const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); - const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); - const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX ); - const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX ); - const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX ); - const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION ); + } - addNodeClass( 'CameraNode', CameraNode ); + update( frame ) { - class ModelNode extends Object3DNode { + const object = this.object3d; + const uniformNode = this._uniformNode; + const scope = this.scope; - constructor( scope = ModelNode.VIEW_MATRIX ) { + if ( scope === Object3DNode.VIEW_MATRIX ) { - super( scope ); + uniformNode.value = object.modelViewMatrix; - } + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - update( frame ) { + uniformNode.value = object.normalMatrix; - this.object3d = frame.object; + } else if ( scope === Object3DNode.WORLD_MATRIX ) { - super.update( frame ); + uniformNode.value = object.matrixWorld; - } + } else if ( scope === Object3DNode.POSITION ) { - } + uniformNode.value = uniformNode.value || new Vector3(); - const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION ); - const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' ); - const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX ); - const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX ); - const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION ); - const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE ); - const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION ); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); - addNodeClass( 'ModelNode', ModelNode ); + } else if ( scope === Object3DNode.SCALE ) { - class NormalNode extends Node { + uniformNode.value = uniformNode.value || new Vector3(); - constructor( scope = NormalNode.LOCAL ) { + uniformNode.value.setFromMatrixScale( object.matrixWorld ); - super( 'vec3' ); + } else if ( scope === Object3DNode.DIRECTION ) { - this.scope = scope; + uniformNode.value = uniformNode.value || new Vector3(); - } + object.getWorldDirection( uniformNode.value ); - isGlobal() { + } else if ( scope === Object3DNode.VIEW_POSITION ) { - return true; + const camera = frame.camera; - } + uniformNode.value = uniformNode.value || new Vector3(); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); - getHash( /*builder*/ ) { + uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); - return `normal-${this.scope}`; + } } @@ -59047,30 +59736,250 @@ var THREE = (async function (exports) { const scope = this.scope; - let outputNode = null; - - if ( scope === NormalNode.GEOMETRY ) { - - outputNode = attribute( 'normal', 'vec3' ); - - } else if ( scope === NormalNode.LOCAL ) { + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { - outputNode = varying( normalGeometry ); + this._uniformNode.nodeType = 'mat4'; - } else if ( scope === NormalNode.VIEW ) { + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - const vertexNode = modelNormalMatrix.mul( normalLocal ); - outputNode = normalize( varying( vertexNode ) ); + this._uniformNode.nodeType = 'mat3'; - } else if ( scope === NormalNode.WORLD ) { + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { - // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView ) - const vertexNode = normalView.transformDirection( cameraViewMatrix ); - outputNode = normalize( varying( vertexNode ) ); + this._uniformNode.nodeType = 'vec3'; } - return outputNode.build( builder, this.getNodeType( builder ) ); + return this._uniformNode.build( builder ); + + } + + serialize( data ) { + + super.serialize( data ); + + data.scope = this.scope; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.scope = data.scope; + + } + + } + + Object3DNode.VIEW_MATRIX = 'viewMatrix'; + Object3DNode.NORMAL_MATRIX = 'normalMatrix'; + Object3DNode.WORLD_MATRIX = 'worldMatrix'; + Object3DNode.POSITION = 'position'; + Object3DNode.SCALE = 'scale'; + Object3DNode.VIEW_POSITION = 'viewPosition'; + Object3DNode.DIRECTION = 'direction'; + + const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION ); + const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX ); + const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX ); + const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ); + const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION ); + const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE ); + const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ); + + addNodeClass( 'Object3DNode', Object3DNode ); + + //const cameraGroup = sharedUniformGroup( 'camera' ); + + class CameraNode extends Object3DNode { + + constructor( scope = CameraNode.POSITION ) { + + super( scope ); + + this.updateType = NodeUpdateType.RENDER; + + //this._uniformNode.groupNode = cameraGroup; + + } + + getNodeType( builder ) { + + const scope = this.scope; + + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + return 'mat4'; + + } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + + return 'float'; + + } + + return super.getNodeType( builder ); + + } + + update( frame ) { + + const camera = frame.camera; + const uniformNode = this._uniformNode; + const scope = this.scope; + + //cameraGroup.needsUpdate = true; + + if ( scope === CameraNode.VIEW_MATRIX ) { + + uniformNode.value = camera.matrixWorldInverse; + + } else if ( scope === CameraNode.PROJECTION_MATRIX ) { + + uniformNode.value = camera.projectionMatrix; + + } else if ( scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + uniformNode.value = camera.projectionMatrixInverse; + + } else if ( scope === CameraNode.NEAR ) { + + uniformNode.value = camera.near; + + } else if ( scope === CameraNode.FAR ) { + + uniformNode.value = camera.far; + + } else if ( scope === CameraNode.LOG_DEPTH ) { + + uniformNode.value = 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ); + + } else { + + this.object3d = camera; + + super.update( frame ); + + } + + } + + generate( builder ) { + + const scope = this.scope; + + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + this._uniformNode.nodeType = 'mat4'; + + } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + + this._uniformNode.nodeType = 'float'; + + } + + return super.generate( builder ); + + } + + } + + CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; + CameraNode.PROJECTION_MATRIX_INVERSE = 'projectionMatrixInverse'; + CameraNode.NEAR = 'near'; + CameraNode.FAR = 'far'; + CameraNode.LOG_DEPTH = 'logDepth'; + + const cameraProjectionMatrix = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ); + const cameraProjectionMatrixInverse = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX_INVERSE ); + const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); + const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); + const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); + const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX ); + const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX ); + const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX ); + const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION ); + + addNodeClass( 'CameraNode', CameraNode ); + + class ModelNode extends Object3DNode { + + constructor( scope = ModelNode.VIEW_MATRIX ) { + + super( scope ); + + } + + update( frame ) { + + this.object3d = frame.object; + + super.update( frame ); + + } + + } + + const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION ); + const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' ); + const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX ); + const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX ); + const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION ); + const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE ); + const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION ); + + addNodeClass( 'ModelNode', ModelNode ); + + class NormalNode extends Node { + + constructor( scope = NormalNode.LOCAL ) { + + super( 'vec3' ); + + this.scope = scope; + + } + + isGlobal() { + + return true; + + } + + getHash( /*builder*/ ) { + + return `normal-${this.scope}`; + + } + + generate( builder ) { + + const scope = this.scope; + + let outputNode = null; + + if ( scope === NormalNode.GEOMETRY ) { + + outputNode = attribute( 'normal', 'vec3' ); + + } else if ( scope === NormalNode.LOCAL ) { + + outputNode = varying( normalGeometry ); + + } else if ( scope === NormalNode.VIEW ) { + + const vertexNode = modelNormalMatrix.mul( normalLocal ); + outputNode = normalize( varying( vertexNode ) ); + + } else if ( scope === NormalNode.WORLD ) { + + // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView ) + const vertexNode = normalView.transformDirection( cameraViewMatrix ); + outputNode = normalize( varying( vertexNode ) ); + + } + + return outputNode.build( builder, this.getNodeType( builder ) ); } @@ -59330,11 +60239,11 @@ var THREE = (async function (exports) { } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) { - const iridescenceThicknessMaximum = reference( 1, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange ); if ( material.iridescenceThicknessMap ) { - const iridescenceThicknessMinimum = reference( 0, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange ); node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum ); @@ -59603,12 +60512,14 @@ var THREE = (async function (exports) { const nodeType = this.getNodeType( builder ); - const nodeUniform = builder.getBufferAttributeFromNode( this, nodeType ); - const propertyName = builder.getPropertyName( nodeUniform ); + const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType ); + const propertyName = builder.getPropertyName( nodeAttribute ); let output = null; - if ( builder.shaderStage === 'vertex' ) { + if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) { + + this.name = propertyName; output = propertyName; @@ -59721,31 +60632,6 @@ var THREE = (async function (exports) { addNodeClass( 'InstanceNode', InstanceNode ); - class BufferNode extends UniformNode { - - constructor( value, bufferType, bufferCount = 0 ) { - - super( value, bufferType ); - - this.isBufferNode = true; - - this.bufferType = bufferType; - this.bufferCount = bufferCount; - - } - - getInputType( /*builder*/ ) { - - return 'buffer'; - - } - - } - - const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - - addNodeClass( 'BufferNode', BufferNode ); - class TangentNode extends Node { constructor( scope = TangentNode.LOCAL ) { @@ -59787,13 +60673,19 @@ var THREE = (async function (exports) { outputNode = attribute( 'tangent', 'vec4' ); + if ( builder.geometry.hasAttribute( 'tangent' ) === false ) { + + builder.geometry.computeTangents(); + + } + } else if ( scope === TangentNode.LOCAL ) { outputNode = varying( tangentGeometry.xyz ); } else if ( scope === TangentNode.VIEW ) { - const vertexNode = modelViewMatrix.mul( tangentLocal ).xyz; + const vertexNode = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz; outputNode = normalize( varying( vertexNode ) ); } else if ( scope === TangentNode.WORLD ) { @@ -59841,11 +60733,12 @@ var THREE = (async function (exports) { class SkinningNode extends Node { - constructor( skinnedMesh ) { + constructor( skinnedMesh, useReference = false ) { super( 'void' ); this.skinnedMesh = skinnedMesh; + this.useReference = useReference; this.updateType = NodeUpdateType.OBJECT; @@ -59854,9 +60747,25 @@ var THREE = (async function (exports) { this.skinIndexNode = attribute( 'skinIndex', 'uvec4' ); this.skinWeightNode = attribute( 'skinWeight', 'vec4' ); - this.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); - this.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); - this.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode; + + if ( useReference ) { + + bindMatrixNode = reference( 'bindMatrix', 'mat4' ); + bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' ); + boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length ); + + } else { + + bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); + bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); + boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + + } + + this.bindMatrixNode = bindMatrixNode; + this.bindMatrixInverseNode = bindMatrixInverseNode; + this.boneMatricesNode = boneMatricesNode; } @@ -59918,18 +60827,214 @@ var THREE = (async function (exports) { } - update() { + update( frame ) { + + const object = this.useReference ? frame.object : this.skinnedMesh; - this.skinnedMesh.skeleton.update(); + object.skeleton.update(); } } - const skinning = nodeProxy( SkinningNode ); + const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) ); + const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) ); addNodeClass( 'SkinningNode', SkinningNode ); + class LoopNode extends Node { + + constructor( params = [] ) { + + super(); + + this.params = params; + + } + + getVarName( index ) { + + return String.fromCharCode( 'i'.charCodeAt() + index ); + + } + + getProperties( builder ) { + + const properties = builder.getNodeProperties( this ); + + if ( properties.stackNode !== undefined ) return properties; + + // + + const inputs = {}; + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + const param = this.params[ i ]; + + const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); + const type = ( param.isNode !== true && param.type ) || 'int'; + + inputs[ name ] = expression( name, type ); + + } + + properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); + properties.stackNode = builder.removeStack(); + + return properties; + + } + + getNodeType( builder ) { + + const { returnsNode } = this.getProperties( builder ); + + return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; + + } + + setup( builder ) { + + // setup properties + + this.getProperties( builder ); + + } + + generate( builder ) { + + const properties = this.getProperties( builder ); + + const contextData = { tempWrite: false }; + + const params = this.params; + const stackNode = properties.stackNode; + + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { + + const param = params[ i ]; + + let start = null, end = null, name = null, type = null, condition = null, update = null; + + if ( param.isNode ) { + + type = 'int'; + name = this.getVarName( i ); + start = '0'; + end = param.build( builder, type ); + condition = '<'; + + } else { + + type = param.type || 'int'; + name = param.name || this.getVarName( i ); + start = param.start; + end = param.end; + condition = param.condition; + update = param.update; + + if ( typeof start === 'number' ) start = start.toString(); + else if ( start && start.isNode ) start = start.build( builder, type ); + + if ( typeof end === 'number' ) end = end.toString(); + else if ( end && end.isNode ) end = end.build( builder, type ); + + if ( start !== undefined && end === undefined ) { + + start = start + ' - 1'; + end = '0'; + condition = '>='; + + } else if ( end !== undefined && start === undefined ) { + + start = '0'; + condition = '<'; + + } + + if ( condition === undefined ) { + + if ( Number( start ) > Number( end ) ) { + + condition = '>='; + + } else { + + condition = '<'; + + } + + } + + } + + const internalParam = { start, end, condition }; + + // + + const startSnippet = internalParam.start; + const endSnippet = internalParam.end; + + let declarationSnippet = ''; + let conditionalSnippet = ''; + let updateSnippet = ''; + + if ( ! update ) { + + if ( type === 'int' || type === 'uint' ) { + + if ( condition.includes( '<' ) ) update = '++'; + else update = '--'; + + } else { + + if ( condition.includes( '<' ) ) update = '+= 1.'; + else update = '-= 1.'; + + } + + } + + declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; + + conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; + updateSnippet += name + ' ' + update; + + const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; + + builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); + + } + + const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); + + const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; + + builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); + + } + + builder.addFlowTab(); + + return returnsSnippet; + + } + + } + + const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); + const Continue = () => expression( 'continue' ).append(); + const Break = () => expression( 'break' ).append(); + + addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); + + addNodeClass( 'LoopNode', LoopNode ); + const morphTextures = new WeakMap(); const morphVec4 = new Vector4(); @@ -60105,10 +61210,9 @@ var THREE = (async function (exports) { const width = int( size.width ); - for ( let i = 0; i < morphTargetsCount; i ++ ) { + loop( morphTargetsCount, ( { i } ) => { - const influence = referenceIndex( 'morphTargetInfluences', i, 'float' ); - const depth = int( i ); + const influence = reference( 'morphTargetInfluences', 'float' ).element( i ); if ( hasMorphPosition === true ) { @@ -60117,7 +61221,7 @@ var THREE = (async function (exports) { influence, stride, width, - depth, + depth: i, offset: int( 0 ) } ) ); @@ -60130,13 +61234,13 @@ var THREE = (async function (exports) { influence, stride, width, - depth, + depth: i, offset: int( 1 ) } ) ); } - } + } ); } @@ -60158,7 +61262,7 @@ var THREE = (async function (exports) { } - const morph = nodeProxy( MorphNode ); + const morphReference = nodeProxy( MorphNode ); addNodeClass( 'MorphNode', MorphNode ); @@ -60260,7 +61364,7 @@ var THREE = (async function (exports) { addNodeClass( 'LightingNode', LightingNode ); - let depthMaterial = null; + let overrideMaterial = null; class AnalyticLightNode extends LightingNode { @@ -60302,7 +61406,13 @@ var THREE = (async function (exports) { if ( shadowNode === null ) { - if ( depthMaterial === null ) depthMaterial = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ); + if ( overrideMaterial === null ) { + + overrideMaterial = builder.createNodeMaterial(); + overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); + overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode + + } const shadow = this.light.shadow; const rtt = builder.getRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); @@ -60390,8 +61500,10 @@ var THREE = (async function (exports) { */ // + const shadowColor = texture( rtt.texture, shadowCoord ); + this.rtt = rtt; - this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode ) ); + this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) ) ); this.shadowNode = shadowNode; @@ -60417,7 +61529,7 @@ var THREE = (async function (exports) { const currentOverrideMaterial = scene.overrideMaterial; - scene.overrideMaterial = depthMaterial; + scene.overrideMaterial = overrideMaterial; rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height ); @@ -60643,7 +61755,7 @@ var THREE = (async function (exports) { } const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) ); - const lightNodes = nodeProxy( LightsNode ); + const lightsNode = nodeProxy( LightsNode ); function addLightNode( lightClass, lightNodeClass ) { @@ -61021,8 +62133,6 @@ var THREE = (async function (exports) { const scope = this.scope; - if ( scope === ViewportNode.COORDINATE ) return; - let output = null; if ( scope === ViewportNode.RESOLUTION ) { @@ -61095,7 +62205,7 @@ var THREE = (async function (exports) { addNodeClass( 'ViewportNode', ViewportNode ); - const _size$1 = new Vector2(); + const _size$2 = new Vector2(); class ViewportTextureNode extends TextureNode { @@ -61121,16 +62231,16 @@ var THREE = (async function (exports) { updateBefore( frame ) { const renderer = frame.renderer; - renderer.getDrawingBufferSize( _size$1 ); + renderer.getDrawingBufferSize( _size$2 ); // const framebufferTexture = this.value; - if ( framebufferTexture.image.width !== _size$1.width || framebufferTexture.image.height !== _size$1.height ) { + if ( framebufferTexture.image.width !== _size$2.width || framebufferTexture.image.height !== _size$2.height ) { - framebufferTexture.image.width = _size$1.width; - framebufferTexture.image.height = _size$1.height; + framebufferTexture.image.width = _size$2.width; + framebufferTexture.image.height = _size$2.height; framebufferTexture.needsUpdate = true; } @@ -61171,9 +62281,6 @@ var THREE = (async function (exports) { if ( sharedDepthbuffer === null ) { sharedDepthbuffer = new DepthTexture(); - sharedDepthbuffer.minFilter = NearestMipmapNearestFilter; - sharedDepthbuffer.type = UnsignedIntType; - sharedDepthbuffer.format = DepthFormat; } @@ -61279,6 +62386,162 @@ var THREE = (async function (exports) { addNodeClass( 'ViewportDepthNode', ViewportDepthNode ); + class ClippingNode extends Node { + + constructor( scope = ClippingNode.DEFAULT ) { + + super(); + + this.scope = scope; + + } + + setup( builder ) { + + super.setup( builder ); + + const clippingContext = builder.clippingContext; + const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext; + + const numClippingPlanes = globalClippingCount + localClippingCount; + const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes; + + if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) { + + return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); + + } else { + + return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); + + } + + } + + setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + const distanceToPlane = property( 'float', 'distanceToPlane' ); + const distanceGradient = property( 'float', 'distanceToGradient' ); + + const clipOpacity = property( 'float', 'clipOpacity' ); + + clipOpacity.assign( 1 ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) ); + + clipOpacity.equal( 0.0 ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const unionClipOpacity = property( 'float', 'unionclipOpacity' ); + + unionClipOpacity.assign( 1 ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() ); + + } ); + + clipOpacity.mulAssign( unionClipOpacity.oneMinus() ); + + } + + diffuseColor.a.mulAssign( clipOpacity ); + + diffuseColor.a.equal( 0.0 ).discard(); + + } )(); + + } + + setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + positionView.dot( plane.xyz ).greaterThan( plane.w ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const clipped = property( 'bool', 'clipped' ); + + clipped.assign( true ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) ); + + } ); + + clipped.discard(); + } + + } )(); + + } + + } + + ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage'; + ClippingNode.DEFAULT = 'default'; + + const clipping = () => nodeObject( new ClippingNode() ); + + const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) ); + + class FrontFacingNode extends Node { + + constructor() { + + super( 'bool' ); + + this.isFrontFacingNode = true; + + } + + generate( builder ) { + + return builder.getFrontFacing(); + + } + + } + + const frontFacing = nodeImmutable( FrontFacingNode ); + const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); + + addNodeClass( 'FrontFacingNode', FrontFacingNode ); + const NodeMaterials = new Map(); class NodeMaterial extends ShaderMaterial { @@ -61312,6 +62575,7 @@ var THREE = (async function (exports) { this.positionNode = null; this.depthNode = null; + this.shadowNode = null; this.outputNode = null; @@ -61348,6 +62612,8 @@ var THREE = (async function (exports) { let resultNode; + const clippingNode = this.setupClipping( builder ); + if ( this.fragmentNode === null ) { if ( this.depthWrite === true ) this.setupDepth( builder ); @@ -61359,6 +62625,8 @@ var THREE = (async function (exports) { const outgoingLightNode = this.setupLighting( builder ); + if ( clippingNode !== null ) builder.stack.add( clippingNode ); + resultNode = this.setupOutput( builder, vec4( outgoingLightNode, diffuseColor.a ) ); // OUTPUT NODE @@ -61381,6 +62649,31 @@ var THREE = (async function (exports) { } + setupClipping( builder ) { + + const { globalClippingCount, localClippingCount } = builder.clippingContext; + + let result = null; + + if ( globalClippingCount || localClippingCount ) { + + if ( this.alphaToCoverage ) { + + // to be added to flow when the color/alpha value has been determined + result = clippingAlpha(); + + } else { + + builder.stack.add( clipping() ); + + } + + } + + return result; + + } + setupDepth( builder ) { const { renderer } = builder; @@ -61416,13 +62709,13 @@ var THREE = (async function (exports) { if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) { - morph( object ).append(); + morphReference( object ).append(); } if ( object.isSkinnedMesh === true ) { - skinning( object ).append(); + skinningReference( object ).append(); } @@ -61494,13 +62787,13 @@ var THREE = (async function (exports) { const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize(); - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } else { const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal; - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } @@ -61548,15 +62841,15 @@ var THREE = (async function (exports) { } - let lightsNode = this.lightsNode || builder.lightsNode; + let lightsN = this.lightsNode || builder.lightsNode; if ( materialLightsNode.length > 0 ) { - lightsNode = lightNodes( [ ...lightsNode.lightNodes, ...materialLightsNode ] ); + lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] ); } - return lightsNode; + return lightsN; } @@ -61755,6 +63048,7 @@ var THREE = (async function (exports) { this.positionNode = source.positionNode; this.depthNode = source.depthNode; + this.shadowNode = source.shadowNode; this.outputNode = source.outputNode; @@ -62114,23 +63408,45 @@ var THREE = (async function (exports) { } - generate( builder ) { + generate( builder, output ) { const type = this.getNodeType( builder ); const context$1 = { tempWrite: false }; + const nodeData = builder.getDataFromNode( this ); + + if ( nodeData.nodeProperty !== undefined ) { + + return nodeData.nodeProperty; + + } + const { ifNode, elseNode } = this; - const needsProperty = ifNode.getNodeType( builder ) !== 'void' || ( elseNode && elseNode.getNodeType( builder ) !== 'void' ); - const nodeProperty = needsProperty ? property( type ).build( builder ) : ''; + const needsOutput = output !== 'void'; + const nodeProperty = needsOutput ? property( type ).build( builder ) : ''; + + nodeData.nodeProperty = nodeProperty; const nodeSnippet = context( this.condNode/*, context*/ ).build( builder, 'bool' ); builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab(); - let ifSnippet = context( this.ifNode, context$1 ).build( builder, type ); + let ifSnippet = context( ifNode, context$1 ).build( builder, type ); + + if ( ifSnippet ) { + + if ( needsOutput ) { - ifSnippet = needsProperty ? nodeProperty + ' = ' + ifSnippet + ';' : ifSnippet; + ifSnippet = nodeProperty + ' = ' + ifSnippet + ';'; + + } else { + + ifSnippet = 'return ' + ifSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' ); @@ -62139,7 +63455,20 @@ var THREE = (async function (exports) { builder.addFlowCode( ' else {\n\n' ).addFlowTab(); let elseSnippet = context( elseNode, context$1 ).build( builder, type ); - elseSnippet = nodeProperty ? nodeProperty + ' = ' + elseSnippet + ';' : elseSnippet; + + if ( elseSnippet ) { + + if ( needsOutput ) { + + elseSnippet = nodeProperty + ' = ' + elseSnippet + ';'; + + } else { + + elseSnippet = 'return ' + elseSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' ); @@ -62149,7 +63478,7 @@ var THREE = (async function (exports) { } - return nodeProperty; + return builder.format( nodeProperty, type, output ); } @@ -62352,6 +63681,8 @@ var THREE = (async function (exports) { this.fogNode = null; this.toneMappingNode = null; + this.clippingContext = null; + this.vertexShader = null; this.fragmentShader = null; this.computeShader = null; @@ -62730,7 +64061,7 @@ var THREE = (async function (exports) { isReference( type ) { - return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture'; + return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture'; } @@ -62740,12 +64071,6 @@ var THREE = (async function (exports) { } - /** @deprecated, r152 */ - getTextureEncodingFromMap( map ) { - return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - getTextureColorSpaceFromMap( map ) { let colorSpace; @@ -62789,7 +64114,7 @@ var THREE = (async function (exports) { getVectorType( type ) { if ( type === 'color' ) return 'vec3'; - if ( type === 'texture' ) return 'vec4'; + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) return 'vec4'; return type; @@ -62841,6 +64166,7 @@ var THREE = (async function (exports) { if ( vecNum !== null ) return Number( vecNum[ 1 ] ); if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; + if ( /mat2/.test( type ) === true ) return 4; if ( /mat3/.test( type ) === true ) return 9; if ( /mat4/.test( type ) === true ) return 16; @@ -63429,24 +64755,12 @@ var THREE = (async function (exports) { } - createNodeMaterial( type ) { + createNodeMaterial( type = 'NodeMaterial' ) { return createNodeMaterialFromType( type ); } - getPrimitiveType( type ) { - - let primitiveType; - - if ( type[ 0 ] === 'i' ) primitiveType = 'int'; - else if ( type[ 0 ] === 'u' ) primitiveType = 'uint'; - else primitiveType = 'float'; - - return primitiveType; - - } - format( snippet, fromType, toType ) { fromType = this.getVectorType( fromType ); @@ -63506,7 +64820,7 @@ var THREE = (async function (exports) { // convert a number value to vector type, e.g: // vec3( 1u ) -> vec3( float( 1u ) ) - snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`; + snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; } @@ -63567,7 +64881,7 @@ var THREE = (async function (exports) { updateBeforeNode( node ) { const updateType = node.getUpdateBeforeType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -63575,9 +64889,11 @@ var THREE = (async function (exports) { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.updateBefore( this ) !== false ) { - node.updateBefore( this ); + frameMap.set( node, this.frameId ); + + } } @@ -63587,9 +64903,11 @@ var THREE = (async function (exports) { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.updateBefore( this ) !== false ) { - node.updateBefore( this ); + renderMap.set( node, this.renderId ); + + } } @@ -63604,7 +64922,7 @@ var THREE = (async function (exports) { updateNode( node ) { const updateType = node.getUpdateType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -63612,9 +64930,11 @@ var THREE = (async function (exports) { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.update( this ) !== false ) { + + frameMap.set( node, this.frameId ); - node.update( this ); + } } @@ -63624,9 +64944,11 @@ var THREE = (async function (exports) { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.update( this ) !== false ) { + + renderMap.set( node, this.renderId ); - node.update( this ); + } } @@ -63778,6 +65100,85 @@ var THREE = (async function (exports) { addNodeClass( 'HashNode', HashNode ); + // remapping functions https://iquilezles.org/articles/functions/ + const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); + const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); + const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); + const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); + + + addNodeElement( 'parabola', parabola ); + addNodeElement( 'gain', gain ); + addNodeElement( 'pcurve', pcurve ); + addNodeElement( 'sinc', sinc ); + + // https://github.com/cabbibo/glsl-tri-noise-3d + + const tri = tslFn( ( [ x ] ) => { + + return x.fract().sub( .5 ).abs(); + + } ); + + const tri3 = tslFn( ( [ p ] ) => { + + return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); + + } ); + + const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => { + + const p = vec3( p_immutable ).toVar(); + const z = float( 1.4 ).toVar(); + const rz = float( 0.0 ).toVar(); + const bp = vec3( p ).toVar(); + + loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { + + const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); + p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); + bp.mulAssign( 1.8 ); + z.mulAssign( 1.5 ); + p.mulAssign( 1.2 ); + + const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); + rz.addAssign( t.div( z ) ); + bp.addAssign( 0.14 ); + + } ); + + return rz; + + } ); + + // layouts + + tri.setLayout( { + name: 'tri', + type: 'float', + inputs: [ + { name: 'x', type: 'float' } + ] + } ); + + tri3.setLayout( { + name: 'tri3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] + } ); + + triNoise3D.setLayout( { + name: 'triNoise3D', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'spd', type: 'float' }, + { name: 'time', type: 'float' } + ] + } ); + let discardExpression; class DiscardNode extends CondNode { @@ -63890,197 +65291,6 @@ var THREE = (async function (exports) { addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode ); - class LoopNode extends Node { - - constructor( params = [] ) { - - super(); - - this.params = params; - - } - - getVarName( index ) { - - return String.fromCharCode( 'i'.charCodeAt() + index ); - - } - - getProperties( builder ) { - - const properties = builder.getNodeProperties( this ); - - if ( properties.stackNode !== undefined ) return properties; - - // - - const inputs = {}; - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - const param = this.params[ i ]; - - const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); - const type = ( param.isNode !== true && param.type ) || 'int'; - - inputs[ name ] = expression( name, type ); - - } - - properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); - properties.stackNode = builder.removeStack(); - - return properties; - - } - - getNodeType( builder ) { - - const { returnsNode } = this.getProperties( builder ); - - return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; - - } - - setup( builder ) { - - // setup properties - - this.getProperties( builder ); - - } - - generate( builder ) { - - const properties = this.getProperties( builder ); - - const contextData = { tempWrite: false }; - - const params = this.params; - const stackNode = properties.stackNode; - - for ( let i = 0, l = params.length - 1; i < l; i ++ ) { - - const param = params[ i ]; - - let start = null, end = null, name = null, type = null, condition = null, update = null; - - if ( param.isNode ) { - - type = 'int'; - name = this.getVarName( i ); - start = '0'; - end = param.build( builder, type ); - condition = '<'; - - } else { - - type = param.type || 'int'; - name = param.name || this.getVarName( i ); - start = param.start; - end = param.end; - condition = param.condition; - update = param.update; - - if ( typeof start === 'number' ) start = start.toString(); - else if ( start && start.isNode ) start = start.build( builder, type ); - - if ( typeof end === 'number' ) end = end.toString(); - else if ( end && end.isNode ) end = end.build( builder, type ); - - if ( start !== undefined && end === undefined ) { - - start = start + ' - 1'; - end = '0'; - condition = '>='; - - } else if ( end !== undefined && start === undefined ) { - - start = '0'; - condition = '<'; - - } - - if ( condition === undefined ) { - - if ( Number( start ) > Number( end ) ) { - - condition = '>='; - - } else { - - condition = '<'; - - } - - } - - } - - const internalParam = { start, end, condition }; - - // - - const startSnippet = internalParam.start; - const endSnippet = internalParam.end; - - let declarationSnippet = ''; - let conditionalSnippet = ''; - let updateSnippet = ''; - - if ( ! update ) { - - if ( type === 'int' ) { - - if ( condition.includes( '<' ) ) update = '++'; - else update = '--'; - - } else { - - if ( condition.includes( '<' ) ) update = '+= 1'; - else update = '-= 1'; - - } - - } - - declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; - - conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; - updateSnippet += name + ' ' + update; - - const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; - - builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); - - } - - const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); - - const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; - - builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); - - } - - builder.addFlowTab(); - - return returnsSnippet; - - } - - } - - const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); - - addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); - - addNodeClass( 'LoopNode', LoopNode ); - class MatcapUVNode extends TempNode { constructor() { @@ -64372,17 +65582,9 @@ var THREE = (async function (exports) { const { uvNode, rotationNode, centerNode } = this; - const cosAngle = rotationNode.cos(); - const sinAngle = rotationNode.sin(); - const vector = uvNode.sub( centerNode ); - const rotatedVector = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( vector )? - vec2( cosAngle, sinAngle ).dot( vector ), - vec2( sinAngle.negate(), cosAngle ).dot( vector ) - ); - - return rotatedVector.add( centerNode ); + return vector.rotate( rotationNode ).add( centerNode ); } @@ -64394,6 +65596,62 @@ var THREE = (async function (exports) { addNodeClass( 'RotateUVNode', RotateUVNode ); + class RotateNode extends TempNode { + + constructor( positionNode, rotationNode ) { + + super(); + + this.positionNode = positionNode; + this.rotationNode = rotationNode; + + } + + getNodeType( builder ) { + + return this.positionNode.getNodeType( builder ); + + } + + setup( builder ) { + + const { rotationNode, positionNode } = this; + + const nodeType = this.getNodeType( builder ); + + if ( nodeType === 'vec2' ) { + + const cosAngle = rotationNode.cos(); + const sinAngle = rotationNode.sin(); + + const rotationMatrix = mat2( + cosAngle, sinAngle, + sinAngle.negate(), cosAngle + ); + + return rotationMatrix.mul( positionNode ); + + } else { + + const rotation = rotationNode; + const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + + return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz; + + } + + } + + } + + const rotate = nodeProxy( RotateNode ); + + addNodeElement( 'rotate', rotate ); + + addNodeClass( 'RotateNode', RotateNode ); + class SpriteSheetUVNode extends Node { constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { @@ -64430,6 +65688,92 @@ var THREE = (async function (exports) { addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode ); + class StorageArrayElementNode extends ArrayElementNode { + + constructor( storageBufferNode, indexNode ) { + + super( storageBufferNode, indexNode ); + + this.isStorageArrayElementNode = true; + + } + + set storageBufferNode( value ) { + + this.node = value; + + } + + get storageBufferNode() { + + return this.node; + + } + + setup( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + if ( ! this.node.instanceIndex && this.node.bufferObject === true ) { + + builder.setupPBO( this.node ); + + } + + } + + return super.setup( builder ); + + } + + generate( builder, output ) { + + let snippet; + + const isAssignContext = builder.context.assign; + + // + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + const { node } = this; + + if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) { + + snippet = builder.generatePBO( this ); + + } else { + + snippet = node.build( builder ); + + } + + } else { + + snippet = super.generate( builder ); + + } + + if ( isAssignContext !== true ) { + + const type = this.getNodeType( builder ); + + snippet = builder.format( snippet, type, output ); + + } + + return snippet; + + } + + } + + const storageElement = nodeProxy( StorageArrayElementNode ); + + addNodeElement( 'storageElement', storageElement ); + + addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode ); + class TriplanarTexturesNode extends Node { constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { @@ -64484,6 +65828,225 @@ var THREE = (async function (exports) { addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode ); + const _reflectorPlane = new Plane(); + const _normal = new Vector3(); + const _reflectorWorldPosition = new Vector3(); + const _cameraWorldPosition = new Vector3(); + const _rotationMatrix = new Matrix4(); + const _lookAtPosition = new Vector3( 0, 0, - 1 ); + const clipPlane = new Vector4(); + + const _view = new Vector3(); + const _target = new Vector3(); + const _q = new Vector4(); + + const _size$1 = new Vector2(); + + const _defaultRT = new RenderTarget(); + const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y ); + + let _inReflector = false; + + class ReflectorNode extends TextureNode { + + constructor( parameters = {} ) { + + super( _defaultRT.texture, _defaultUV ); + + const { + target = new Object3D(), + resolution = 1, + generateMipmaps = false, + bounces = true + } = parameters; + + // + + this.target = target; + this.resolution = resolution; + this.generateMipmaps = generateMipmaps; + this.bounces = bounces; + + this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + + this.virtualCameras = new WeakMap(); + this.renderTargets = new WeakMap(); + + + } + + _updateResolution( renderTarget, renderer ) { + + const resolution = this.resolution; + + renderer.getDrawingBufferSize( _size$1 ); + + renderTarget.setSize( Math.round( _size$1.width * resolution ), Math.round( _size$1.height * resolution ) ); + + } + + setup( builder ) { + + this._updateResolution( _defaultRT, builder.renderer ); + + return super.setup( builder ); + + } + + getTextureNode() { + + return this.textureNode; + + } + + getVirtualCamera( camera ) { + + let virtualCamera = this.virtualCameras.get( camera ); + + if ( virtualCamera === undefined ) { + + virtualCamera = camera.clone(); + + this.virtualCameras.set( camera, virtualCamera ); + + } + + return virtualCamera; + + } + + getRenderTarget( camera ) { + + let renderTarget = this.renderTargets.get( camera ); + + if ( renderTarget === undefined ) { + + renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); + + if ( this.generateMipmaps === true ) { + + renderTarget.texture.minFilter = LinearMipMapLinearFilter; + renderTarget.texture.generateMipmaps = true; + + } + + this.renderTargets.set( camera, renderTarget ); + + } + + return renderTarget; + + } + + updateBefore( frame ) { + + if ( this.bounces === false && _inReflector ) return false; + + _inReflector = true; + + const { scene, camera, renderer, material } = frame; + const { target } = this; + + const virtualCamera = this.getVirtualCamera( camera ); + const renderTarget = this.getRenderTarget( virtualCamera ); + + renderer.getDrawingBufferSize( _size$1 ); + + this._updateResolution( renderTarget, renderer ); + + // + + _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); + _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); + + _rotationMatrix.extractRotation( target.matrixWorld ); + + _normal.set( 0, 0, 1 ); + _normal.applyMatrix4( _rotationMatrix ); + + _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); + + // Avoid rendering when reflector is facing away + + if ( _view.dot( _normal ) > 0 ) return; + + _view.reflect( _normal ).negate(); + _view.add( _reflectorWorldPosition ); + + _rotationMatrix.extractRotation( camera.matrixWorld ); + + _lookAtPosition.set( 0, 0, - 1 ); + _lookAtPosition.applyMatrix4( _rotationMatrix ); + _lookAtPosition.add( _cameraWorldPosition ); + + _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); + _target.reflect( _normal ).negate(); + _target.add( _reflectorWorldPosition ); + + // + + virtualCamera.coordinateSystem = camera.coordinateSystem; + virtualCamera.position.copy( _view ); + virtualCamera.up.set( 0, 1, 0 ); + virtualCamera.up.applyMatrix4( _rotationMatrix ); + virtualCamera.up.reflect( _normal ); + virtualCamera.lookAt( _target ); + + virtualCamera.near = camera.near; + virtualCamera.far = camera.far; + + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); + + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); + _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); + + clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); + + const projectionMatrix = virtualCamera.projectionMatrix; + + _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; + _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; + _q.z = - 1.0; + _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; + + // Calculate the scaled plane vector + clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); + + const clipBias = 0; + + // Replacing the third row of the projection matrix + projectionMatrix.elements[ 2 ] = clipPlane.x; + projectionMatrix.elements[ 6 ] = clipPlane.y; + projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias; + projectionMatrix.elements[ 14 ] = clipPlane.w; + + // + + this.value = renderTarget.texture; + + material.visible = false; + + const currentRenderTarget = renderer.getRenderTarget(); + + renderer.setRenderTarget( renderTarget ); + + renderer.render( scene, virtualCamera ); + + renderer.setRenderTarget( currentRenderTarget ); + + material.visible = true; + + _inReflector = false; + + } + + } + + const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); + class BitangentNode extends Node { constructor( scope = BitangentNode.LOCAL ) { @@ -64564,6 +66127,11 @@ var THREE = (async function (exports) { addNodeClass( 'BitangentNode', BitangentNode ); + const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); + + const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/; + const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) ); + class VertexColorNode extends AttributeNode { constructor( index = 0 ) { @@ -64787,6 +66355,11 @@ var THREE = (async function (exports) { this.isStorageBufferNode = true; + this.bufferObject = false; + + this._attribute = null; + this._varying = null; + } getInputType( /*builder*/ ) { @@ -64795,9 +66368,46 @@ var THREE = (async function (exports) { } + element( indexNode ) { + + return storageElement( this, indexNode ); + + } + + setBufferObject( value ) { + + this.bufferObject = value; + + return this; + + } + + generate( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) ) return super.generate( builder ); + + const nodeType = this.getNodeType( builder ); + + if ( this._attribute === null ) { + + this._attribute = bufferAttribute( this.value ); + this._varying = varying( this._attribute ); + + } + + + const output = this._varying.build( builder, nodeType ); + + builder.registerTransform( output, this._attribute ); + + return output; + + } + } const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); + const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); addNodeClass( 'StorageBufferNode', StorageBufferNode ); @@ -64813,15 +66423,68 @@ var THREE = (async function (exports) { } - getNodeType( /*builder*/ ) { + getInputType( /*builder*/ ) { + + return 'storageTexture'; + + } - return 'void'; + setup( builder ) { + + super.setup( builder ); + + const properties = builder.getNodeProperties( this ); + properties.storeNode = this.storeNode; + + } + + generate( builder, output ) { + + let snippet; + + if ( this.storeNode !== null ) { + + snippet = this.generateStore( builder ); + + } else { + + snippet = super.generate( builder, output ); + + } + + return snippet; + + } + + generateStore( builder ) { + + const properties = builder.getNodeProperties( this ); + + const { uvNode, storeNode } = properties; + + const textureProperty = super.generate( builder, 'property' ); + const uvSnippet = uvNode.build( builder, 'uvec2' ); + const storeSnippet = storeNode.build( builder, 'vec4' ); + + const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); + + builder.addLineFlowCode( snippet ); } } - const textureStore = nodeProxy( TextureStoreNode ); + const textureStoreBase = nodeProxy( TextureStoreNode ); + + const textureStore = ( value, uvNode, storeNode ) => { + + const node = textureStoreBase( value, uvNode, storeNode ); + + if ( storeNode !== null ) node.append(); + + return node; + + }; addNodeClass( 'TextureStoreNode', TextureStoreNode ); @@ -64855,6 +66518,13 @@ var THREE = (async function (exports) { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'burnColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const DodgeNode = tslFn( ( { base, blend } ) => { @@ -64863,6 +66533,13 @@ var THREE = (async function (exports) { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'dodgeColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const ScreenNode = tslFn( ( { base, blend } ) => { @@ -64871,14 +66548,29 @@ var THREE = (async function (exports) { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'screenColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const OverlayNode = tslFn( ( { base, blend } ) => { const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() ); + //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) ); return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); + } ).setLayout( { + name: 'overlayColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); class BlendModeNode extends TempNode { @@ -64942,29 +66634,6 @@ var THREE = (async function (exports) { addNodeClass( 'BlendModeNode', BlendModeNode ); - class FrontFacingNode extends Node { - - constructor() { - - super( 'bool' ); - - this.isFrontFacingNode = true; - - } - - generate( builder ) { - - return builder.getFrontFacing(); - - } - - } - - const frontFacing = nodeImmutable( FrontFacingNode ); - const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); - - addNodeClass( 'FrontFacingNode', FrontFacingNode ); - // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf @@ -65134,9 +66803,12 @@ var THREE = (async function (exports) { const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 ); const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma ); + const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); + addNodeElement( 'saturation', saturation ); addNodeElement( 'vibrance', vibrance ); addNodeElement( 'hue', hue ); + addNodeElement( 'threshold', threshold ); addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode ); @@ -65227,8 +66899,6 @@ var THREE = (async function (exports) { const normalMap = nodeProxy( NormalMapNode ); - const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); - addNodeElement( 'normalMap', normalMap ); addNodeClass( 'NormalMapNode', NormalMapNode ); @@ -65331,11 +67001,52 @@ var THREE = (async function (exports) { } ); + + + const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); + const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); + + const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => { + + const x = vec3( x_immutable ).toVar(); + const x2 = vec3( x.mul( x ) ).toVar(); + const x4 = vec3( x2.mul( x2 ) ).toVar(); + + return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); + + } ); + + const AGXToneMappingNode = tslFn( ( { color, exposure } ) => { + + const colortone = vec3( color ).toVar(); + const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); + const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); + const AgxMinEv = float( - 12.47393 ); + const AgxMaxEv = float( 4.026069 ); + colortone.mulAssign( exposure ); + colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); + colortone.assign( AgXInsetMatrix.mul( colortone ) ); + colortone.assign( max$1( colortone, 1e-10 ) ); + colortone.assign( log2( colortone ) ); + colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + colortone.assign( agxDefaultContrastApprox( colortone ) ); + colortone.assign( AgXOutsetMatrix.mul( colortone ) ); + colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); + colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + + return colortone; + + } ); + + const toneMappingLib = { [ LinearToneMapping ]: LinearToneMappingNode, [ ReinhardToneMapping ]: ReinhardToneMappingNode, [ CineonToneMapping ]: OptimizedCineonToneMappingNode, - [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode + [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode, + [ AgXToneMapping ]: AGXToneMappingNode }; class ToneMappingNode extends TempNode { @@ -65392,19 +67103,19 @@ var THREE = (async function (exports) { addNodeClass( 'ToneMappingNode', ToneMappingNode ); - let sharedFramebuffer = null; + let _sharedFramebuffer = null; class ViewportSharedTextureNode extends ViewportTextureNode { constructor( uvNode = viewportTopLeft, levelNode = null ) { - if ( sharedFramebuffer === null ) { + if ( _sharedFramebuffer === null ) { - sharedFramebuffer = new FramebufferTexture(); + _sharedFramebuffer = new FramebufferTexture(); } - super( uvNode, levelNode, sharedFramebuffer ); + super( uvNode, levelNode, _sharedFramebuffer ); } @@ -65416,6 +67127,179 @@ var THREE = (async function (exports) { addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode ); + class PassTextureNode extends TextureNode { + + constructor( passNode, texture ) { + + super( texture ); + + this.passNode = passNode; + + this.setUpdateMatrix( false ); + + } + + setup( builder ) { + + this.passNode.build( builder ); + + return super.setup( builder ); + + } + + clone() { + + return new this.constructor( this.passNode, this.value ); + + } + + } + + class PassNode extends TempNode { + + constructor( scope, scene, camera ) { + + super( 'vec4' ); + + this.scope = scope; + this.scene = scene; + this.camera = camera; + + this._pixelRatio = 1; + this._width = 1; + this._height = 1; + + const depthTexture = new DepthTexture(); + depthTexture.isRenderTargetTexture = true; + //depthTexture.type = FloatType; + depthTexture.name = 'PostProcessingDepth'; + + const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); + renderTarget.texture.name = 'PostProcessing'; + renderTarget.depthTexture = depthTexture; + + this.renderTarget = renderTarget; + + this.updateBeforeType = NodeUpdateType.FRAME; + + this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); + this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); + + this._depthNode = null; + this._cameraNear = uniform( 0 ); + this._cameraFar = uniform( 0 ); + + this.isPassNode = true; + + } + + isGlobal() { + + return true; + + } + + getTextureNode() { + + return this._textureNode; + + } + + getTextureDepthNode() { + + return this._depthTextureNode; + + } + + getDepthNode() { + + if ( this._depthNode === null ) { + + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; + + this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + + } + + return this._depthNode; + + } + + setup() { + + return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + + } + + updateBefore( frame ) { + + const { renderer } = frame; + const { scene, camera } = this; + + this._pixelRatio = renderer.getPixelRatio(); + + const size = renderer.getSize( new Vector2() ); + + this.setSize( size.width, size.height ); + + const currentToneMapping = renderer.toneMapping; + const currentToneMappingNode = renderer.toneMappingNode; + const currentRenderTarget = renderer.getRenderTarget(); + + this._cameraNear.value = camera.near; + this._cameraFar.value = camera.far; + + renderer.toneMapping = NoToneMapping; + renderer.toneMappingNode = null; + renderer.setRenderTarget( this.renderTarget ); + + renderer.render( scene, camera ); + + renderer.toneMapping = currentToneMapping; + renderer.toneMappingNode = currentToneMappingNode; + renderer.setRenderTarget( currentRenderTarget ); + + } + + setSize( width, height ) { + + this._width = width; + this._height = height; + + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; + + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + + } + + setPixelRatio( pixelRatio ) { + + this._pixelRatio = pixelRatio; + + this.setSize( this._width, this._height ); + + } + + dispose() { + + this.renderTarget.dispose(); + + } + + + } + + PassNode.COLOR = 'color'; + PassNode.DEPTH = 'depth'; + + const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); + const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); + const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + + addNodeClass( 'PassNode', PassNode ); + // Helper for passes that need to fill the viewport with a single quad. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); @@ -65453,9 +67337,9 @@ var THREE = (async function (exports) { } - render( renderer ) { + async renderAsync( renderer ) { - renderer.render( this._mesh, _camera ); + await renderer.renderAsync( this._mesh, _camera ); } @@ -65471,6 +67355,12 @@ var THREE = (async function (exports) { } + get render() { + + return this.renderAsync; + + } + } // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that @@ -65483,7 +67373,7 @@ var THREE = (async function (exports) { constructor( textureNode, sigma = 2 ) { - super( textureNode ); + super( 'vec4' ); this.textureNode = textureNode; this.sigma = sigma; @@ -65498,6 +67388,8 @@ var THREE = (async function (exports) { this._verticalRT = new RenderTarget(); this._verticalRT.texture.name = 'GaussianBlurNode.vertical'; + this._textureNode = texturePass( this, this._verticalRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; this.resolution = new Vector2( 1, 1 ); @@ -65530,6 +67422,11 @@ var THREE = (async function (exports) { this.setSize( map.image.width, map.image.height ); + const textureType = map.type; + + this._horizontalRT.texture.type = textureType; + this._verticalRT.texture.type = textureType; + // horizontal renderer.setRenderTarget( this._horizontalRT ); @@ -65554,6 +67451,12 @@ var THREE = (async function (exports) { } + getTextureNode() { + + return this._textureNode; + + } + setup( builder ) { const textureNode = this.textureNode; @@ -65602,7 +67505,7 @@ var THREE = (async function (exports) { // - const material = this._material || ( this._material = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const material = this._material || ( this._material = builder.createNodeMaterial() ); material.fragmentNode = blur(); // @@ -65612,7 +67515,7 @@ var THREE = (async function (exports) { // - return texture( this._verticalRT.texture ); + return this._textureNode; } @@ -65654,10 +67557,18 @@ var THREE = (async function (exports) { this._oldRT = new RenderTarget(); this._oldRT.texture.name = 'AfterImageNode.old'; + this._textureNode = texturePass( this, this._compRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; } + getTextureNode() { + + return this._textureNode; + + } + setSize( width, height ) { this._compRT.setSize( width, height ); @@ -65670,6 +67581,12 @@ var THREE = (async function (exports) { const { renderer } = frame; const textureNode = this.textureNode; + const map = textureNode.value; + + const textureType = map.type; + + this._compRT.texture.type = textureType; + this._oldRT.texture.type = textureType; const currentRenderTarget = renderer.getRenderTarget(); const currentTexture = textureNode.value; @@ -65686,7 +67603,6 @@ var THREE = (async function (exports) { this._compRT = temp; // set size before swapping fails - const map = currentTexture; this.setSize( map.image.width, map.image.height ); renderer.setRenderTarget( currentRenderTarget ); @@ -65734,7 +67650,7 @@ var THREE = (async function (exports) { // - const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() ); materialComposed.fragmentNode = afterImg(); quadMeshComp.material = materialComposed; @@ -65746,7 +67662,7 @@ var THREE = (async function (exports) { // - return texture( this._compRT.texture ); + return this._textureNode; } @@ -65756,177 +67672,138 @@ var THREE = (async function (exports) { addNodeElement( 'afterImage', afterImage ); - class PassTextureNode extends TextureNode { + const quadMesh = new QuadMesh(); - constructor( passNode, texture ) { + class AnamorphicNode extends TempNode { - super( texture ); + constructor( textureNode, tresholdNode, scaleNode, samples ) { - this.passNode = passNode; + super( 'vec4' ); - this.setUpdateMatrix( false ); + this.textureNode = textureNode; + this.tresholdNode = tresholdNode; + this.scaleNode = scaleNode; + this.colorNode = vec3( 0.1, 0.0, 1.0 ); + this.samples = samples; + this.resolution = new Vector2( 1, 1 ); - } + this._renderTarget = new RenderTarget(); + this._renderTarget.texture.name = 'anamorphic'; - setup( builder ) { + this._invSize = uniform( new Vector2() ); - this.passNode.build( builder ); + this._textureNode = texturePass( this, this._renderTarget.texture ); - return super.setup( builder ); + this.updateBeforeType = NodeUpdateType.RENDER; } - clone() { + getTextureNode() { - return new this.constructor( this.passNode, this.value ); + return this._textureNode; } - } - - class PassNode extends TempNode { - - constructor( scope, scene, camera ) { - - super( 'vec4' ); - - this.scope = scope; - this.scene = scene; - this.camera = camera; - - this._pixelRatio = 1; - this._width = 1; - this._height = 1; - - const depthTexture = new DepthTexture(); - depthTexture.isRenderTargetTexture = true; - depthTexture.type = FloatType; - depthTexture.name = 'PostProcessingDepth'; - - const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); - renderTarget.texture.name = 'PostProcessing'; - renderTarget.depthTexture = depthTexture; - - this.renderTarget = renderTarget; - - this.updateBeforeType = NodeUpdateType.FRAME; - - this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); - this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); - - this._depthNode = null; - this._cameraNear = uniform( 0 ); - this._cameraFar = uniform( 0 ); - - this.isPassNode = true; + setSize( width, height ) { - } + this._invSize.value.set( 1 / width, 1 / height ); - isGlobal() { + width = Math.max( Math.round( width * this.resolution.x ), 1 ); + height = Math.max( Math.round( height * this.resolution.y ), 1 ); - return true; + this._renderTarget.setSize( width, height ); } - getTextureNode() { + updateBefore( frame ) { - return this._textureNode; + const { renderer } = frame; - } + const textureNode = this.textureNode; + const map = textureNode.value; - getTextureDepthNode() { + this._renderTarget.texture.type = map.type; - return this._depthTextureNode; + const currentRenderTarget = renderer.getRenderTarget(); + const currentTexture = textureNode.value; - } + quadMesh.material = this._material; - getDepthNode() { + this.setSize( map.image.width, map.image.height ); - if ( this._depthNode === null ) { + // render - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; + renderer.setRenderTarget( this._renderTarget ); - this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + quadMesh.render( renderer ); - } + // restore - return this._depthNode; + renderer.setRenderTarget( currentRenderTarget ); + textureNode.value = currentTexture; } - setup() { - - return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + setup( builder ) { - } + const textureNode = this.textureNode; - updateBefore( frame ) { + if ( textureNode.isTextureNode !== true ) { - const { renderer } = frame; - const { scene, camera } = this; + return vec4(); - this._pixelRatio = renderer.getPixelRatio(); + } - const size = renderer.getSize( new Vector2() ); + // - this.setSize( size.width, size.height ); + const uvNode = textureNode.uvNode || uv(); - const currentToneMapping = renderer.toneMapping; - const currentToneMappingNode = renderer.toneMappingNode; - const currentRenderTarget = renderer.getRenderTarget(); + const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } ); - this._cameraNear.value = camera.near; - this._cameraFar.value = camera.far; + const anamorph = tslFn( () => { - renderer.toneMapping = NoToneMapping; - renderer.toneMappingNode = null; - renderer.setRenderTarget( this.renderTarget ); + const samples = this.samples; + const halfSamples = Math.floor( samples / 2 ); - renderer.render( scene, camera ); + const total = vec3( 0 ).toVar(); - renderer.toneMapping = currentToneMapping; - renderer.toneMappingNode = currentToneMappingNode; - renderer.setRenderTarget( currentRenderTarget ); + loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => { - } + const softness = float( i ).abs().div( halfSamples ).oneMinus(); - setSize( width, height ) { + const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y ); + const color = sampleTexture( uv ); + const pass = threshold( color, this.tresholdNode ).mul( softness ); - this._width = width; - this._height = height; + total.addAssign( pass ); - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; + } ); - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + return total.mul( this.colorNode ); - } + } ); - setPixelRatio( pixelRatio ) { + // - this._pixelRatio = pixelRatio; + const material = this._material || ( this._material = builder.createNodeMaterial() ); + material.fragmentNode = anamorph(); - this.setSize( this._width, this._height ); + // - } + const properties = builder.getNodeProperties( this ); + properties.textureNode = textureNode; - dispose() { + // - this.renderTarget.dispose(); + return this._textureNode; } - } - PassNode.COLOR = 'color'; - PassNode.DEPTH = 'depth'; + const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ), nodeObject( threshold ), nodeObject( scale ), samples ) ); - const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); - const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); - - addNodeClass( 'PassNode', PassNode ); + addNodeElement( 'anamorphic', anamorphic ); class FunctionCallNode extends TempNode { @@ -66678,7 +68555,7 @@ var THREE = (async function (exports) { mixAssign( outputNode ) { - return this.mix( outputNode, this.colorNode ); + return mix( outputNode, this.colorNode, this ); } @@ -69208,13 +71085,7 @@ var THREE = (async function (exports) { const rotation = float( rotationNode || materialRotation ); - const cosAngle = rotation.cos(); - const sinAngle = rotation.sin(); - - const rotatedPosition = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( alignedPosition )? - vec2( cosAngle, sinAngle.negate() ).dot( alignedPosition ), - vec2( sinAngle, cosAngle ).dot( alignedPosition ) - ); + const rotatedPosition = alignedPosition.rotate( rotation ); mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw ); @@ -71419,6 +73290,8 @@ var THREE = (async function (exports) { this.width = 0; this.height = 0; + this.isRenderContext = true; + } } @@ -71443,19 +73316,8 @@ var THREE = (async function (exports) { } else { - let format, count; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - format = renderTarget.texture[ 0 ].format; - count = renderTarget.texture.length; - - } else { - - format = renderTarget.texture.format; - count = 1; - - } + const format = renderTarget.texture.format; + const count = renderTarget.count; attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; @@ -71497,10 +73359,11 @@ var THREE = (async function (exports) { class Textures extends DataMap { - constructor( backend, info ) { + constructor( renderer, backend, info ) { super(); + this.renderer = renderer; this.backend = backend; this.info = info; @@ -71513,19 +73376,8 @@ var THREE = (async function (exports) { const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); - let texture, textures; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - textures = renderTarget.texture; - texture = renderTarget.texture[ 0 ]; - - } else { - - textures = [ renderTarget.texture ]; - texture = renderTarget.texture; - - } + const texture = renderTarget.texture; + const textures = renderTarget.textures; const size = this.getSize( texture ); @@ -71538,8 +73390,8 @@ var THREE = (async function (exports) { if ( depthTexture === undefined ) { depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; + depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; + depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; depthTexture.image.width = mipWidth; depthTexture.image.height = mipHeight; @@ -71563,6 +73415,7 @@ var THREE = (async function (exports) { renderTargetData.depthTexture = depthTexture; renderTargetData.depth = renderTarget.depthBuffer; renderTargetData.stencil = renderTarget.stencilBuffer; + renderTargetData.renderTarget = renderTarget; if ( renderTargetData.sampleCount !== sampleCount ) { @@ -71644,6 +73497,25 @@ var THREE = (async function (exports) { // + if ( texture.isFramebufferTexture ) { + + const renderer = this.renderer; + const renderTarget = renderer.getRenderTarget(); + + if ( renderTarget ) { + + texture.type = renderTarget.texture.type; + + } else { + + texture.type = UnsignedByteType; + + } + + } + + // + const { width, height, depth } = this.getSize( texture ); options.width = width; @@ -71697,7 +73569,7 @@ var THREE = (async function (exports) { } - backend.updateTexture( texture, options ); + if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); @@ -71898,7 +73770,7 @@ var THREE = (async function (exports) { const backgroundMeshNode = context( vec4( backgroundNode ), { // @TODO: Add Texture2D support using node context getUV: () => normalWorld, - getTextureLevel: () => backgroundBlurriness + getTextureLevel: ( textureNode ) => backgroundBlurriness.mul( maxMipLevel( textureNode ) ) } ).mul( backgroundIntensity ); let viewProj = modelViewProjection(); @@ -71974,11 +73846,12 @@ var THREE = (async function (exports) { class NodeBuilderState { - constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes ) { + constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, transforms = [] ) { this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; this.computeShader = computeShader; + this.transforms = transforms; this.nodeAttributes = nodeAttributes; this.bindings = bindings; @@ -72124,6 +73997,7 @@ var THREE = (async function (exports) { nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene ); nodeBuilder.fogNode = this.getFogNode( renderObject.scene ); nodeBuilder.toneMappingNode = this.getToneMappingNode(); + nodeBuilder.clippingContext = renderObject.clippingContext; nodeBuilder.build(); nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); @@ -72174,7 +74048,7 @@ var THREE = (async function (exports) { nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); - computeData.nodeBuilderState = nodeBuilder; + computeData.nodeBuilderState = nodeBuilderState; } @@ -72191,7 +74065,8 @@ var THREE = (async function (exports) { nodeBuilder.getAttributesArray(), nodeBuilder.getBindings(), nodeBuilder.updateNodes, - nodeBuilder.updateBeforeNodes + nodeBuilder.updateBeforeNodes, + nodeBuilder.transforms ); } @@ -72534,6 +74409,8 @@ var THREE = (async function (exports) { this.depth = true; this.stencil = true; + this.clippingPlanes = []; + this.info = new Info(); // internals @@ -72577,9 +74454,13 @@ var THREE = (async function (exports) { this._renderObjectFunction = null; this._currentRenderObjectFunction = null; + this._handleObjectFunction = this._renderObjectDirect; + this._initialized = false; this._initPromise = null; + this._compilationPromises = null; + // backwards compatibility this.shadowMap = { @@ -72627,7 +74508,7 @@ var THREE = (async function (exports) { this._attributes = new Attributes( backend ); this._background = new Background( this, this._nodes ); this._geometries = new Geometries( this._attributes, this.info ); - this._textures = new Textures( backend, this.info ); + this._textures = new Textures( this, backend, this.info ); this._pipelines = new Pipelines( backend, this._nodes ); this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); @@ -72652,14 +74533,154 @@ var THREE = (async function (exports) { } - async compile( /*scene, camera*/ ) { + async compileAsync( scene, camera, targetScene = null ) { + + if ( this._initialized === false ) await this.init(); + + // preserve render tree + + const nodeFrame = this._nodes.nodeFrame; + + const previousRenderId = nodeFrame.renderId; + const previousRenderContext = this._currentRenderContext; + const previousRenderObjectFunction = this._currentRenderObjectFunction; + const previousCompilationPromises = this._compilationPromises; + + // + + const sceneRef = ( scene.isScene === true ) ? scene : _scene; + + if ( targetScene === null ) targetScene = scene; + + const renderTarget = this._renderTarget; + const renderContext = this._renderContexts.get( targetScene, camera, renderTarget ); + const activeMipmapLevel = this._activeMipmapLevel; + + const compilationPromises = []; + + this._currentRenderContext = renderContext; + this._currentRenderObjectFunction = this.renderObject; + + this._handleObjectFunction = this._createObjectPipeline; + + this._compilationPromises = compilationPromises; + + nodeFrame.renderId ++; + + // + + nodeFrame.update(); + + // + + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; + + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); + + // + + sceneRef.onBeforeRender( this, scene, camera, renderTarget ); + + // + + const renderList = this._renderLists.get( scene, camera ); + renderList.begin(); + + this._projectObject( scene, camera, 0, renderList ); + + // include lights from target scene + if ( targetScene !== scene ) { + + targetScene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + renderList.pushLight( object ); + + } + + } ); + + } + + renderList.finish(); + + // + + if ( renderTarget !== null ) { + + this._textures.updateRenderTarget( renderTarget, activeMipmapLevel ); + + const renderTargetData = this._textures.get( renderTarget ); + + renderContext.textures = renderTargetData.textures; + renderContext.depthTexture = renderTargetData.depthTexture; + + } else { + + renderContext.textures = null; + renderContext.depthTexture = null; + + } + + // + + this._nodes.updateScene( sceneRef ); + + // + + this._background.update( sceneRef, renderList, renderContext ); + + // process render lists + + const opaqueObjects = renderList.opaque; + const transparentObjects = renderList.transparent; + const lightsNode = renderList.lightsNode; + + if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode ); + if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode ); + + // restore render tree + + nodeFrame.renderId = previousRenderId; + + this._currentRenderContext = previousRenderContext; + this._currentRenderObjectFunction = previousRenderObjectFunction; + this._compilationPromises = previousCompilationPromises; + + this._handleObjectFunction = this._renderObjectDirect; + + // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete + + await Promise.all( compilationPromises ); } - async render( scene, camera ) { + async renderAsync( scene, camera ) { if ( this._initialized === false ) await this.init(); + const renderContext = this._renderContext( scene, camera ); + + await this.backend.resolveTimestampAsync( renderContext, 'render' ); + + } + + render( scene, camera ) { + + if ( this._initialized === false ) { + return; + + } + + this._renderContext( scene, camera ); + + } + + _renderContext( scene, camera ) { + // preserve render tree const nodeFrame = this._nodes.nodeFrame; @@ -72740,8 +74761,8 @@ var THREE = (async function (exports) { renderContext.scissorValue.width >>= activeMipmapLevel; renderContext.scissorValue.height >>= activeMipmapLevel; - renderContext.depth = this.depth; - renderContext.stencil = this.stencil; + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); // @@ -72778,6 +74799,8 @@ var THREE = (async function (exports) { renderContext.width = renderTargetData.width; renderContext.height = renderTargetData.height; renderContext.renderTarget = renderTarget; + renderContext.depth = renderTarget.depthBuffer; + renderContext.stencil = renderTarget.stencilBuffer; } else { @@ -72785,6 +74808,8 @@ var THREE = (async function (exports) { renderContext.depthTexture = null; renderContext.width = this.domElement.width; renderContext.height = this.domElement.height; + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; } @@ -72830,6 +74855,10 @@ var THREE = (async function (exports) { sceneRef.onAfterRender( this, scene, camera, renderTarget ); + // + + return renderContext; + } getMaxAnisotropy() { @@ -72990,6 +75019,8 @@ var THREE = (async function (exports) { this._scissorTest = boolean; + this.backend.setScissorTest( boolean ); + } getViewport( target ) { @@ -73093,19 +75124,45 @@ var THREE = (async function (exports) { clearColor() { - this.clear( true, false, false ); + return this.clear( true, false, false ); } clearDepth() { - this.clear( false, true, false ); + return this.clear( false, true, false ); } clearStencil() { - this.clear( false, false, true ); + return this.clear( false, false, true ); + + } + + async clearAsync( color = true, depth = true, stencil = true ) { + + if ( this._initialized === false ) await this.init(); + + this.clear( color, depth, stencil ); + + } + + clearColorAsync() { + + return this.clearAsync( true, false, false ); + + } + + clearDepthAsync() { + + return this.clearAsync( false, true, false ); + + } + + clearStencilAsync() { + + return this.clearAsync( false, false, true ); } @@ -73169,7 +75226,7 @@ var THREE = (async function (exports) { } - async compute( computeNodes ) { + async computeAsync( computeNodes ) { if ( this._initialized === false ) await this.init(); @@ -73181,10 +75238,12 @@ var THREE = (async function (exports) { this.info.calls ++; this.info.compute.calls ++; + this.info.compute.computeCalls ++; nodeFrame.renderId = this.info.calls; // + if ( this.info.autoReset === true ) this.info.resetCompute(); const backend = this.backend; const pipelines = this._pipelines; @@ -73236,12 +75295,20 @@ var THREE = (async function (exports) { backend.finishCompute( computeNodes ); + await this.backend.resolveTimestampAsync( computeNodes, 'compute' ); + // nodeFrame.renderId = previousRenderId; } + hasFeatureAsync( name ) { + + return this.backend.hasFeatureAsync( name ); + + } + hasFeature( name ) { return this.backend.hasFeature( name ); @@ -73415,6 +75482,7 @@ var THREE = (async function (exports) { renderObject( object, scene, camera, geometry, material, group, lightsNode ) { let overridePositionNode; + let overrideFragmentNode; // @@ -73436,6 +75504,45 @@ var THREE = (async function (exports) { } + if ( overrideMaterial.isShadowNodeMaterial ) { + + overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide; + + if ( material.shadowNode && material.shadowNode.isNode ) { + + overrideFragmentNode = overrideMaterial.fragmentNode; + overrideMaterial.fragmentNode = material.shadowNode; + + } + + if ( this.localClippingEnabled ) { + + if ( material.clipShadows ) { + + if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) { + + overrideMaterial.clippingPlanes = material.clippingPlanes; + overrideMaterial.needsUpdate = true; + + } + + if ( overrideMaterial.clipIntersection !== material.clipIntersection ) { + + overrideMaterial.clipIntersection = material.clipIntersection; + + } + + } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) { + + overrideMaterial.clippingPlanes = null; + overrideMaterial.needsUpdate = true; + + } + + } + + } + material = overrideMaterial; } @@ -73445,16 +75552,16 @@ var THREE = (async function (exports) { if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { material.side = BackSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id material.side = FrontSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode ); // use default pass id material.side = DoubleSide; } else { - this._renderObjectDirect( object, material, scene, camera, lightsNode ); + this._handleObjectFunction( object, material, scene, camera, lightsNode ); } @@ -73466,6 +75573,12 @@ var THREE = (async function (exports) { } + if ( overrideFragmentNode !== undefined ) { + + scene.overrideMaterial.fragmentNode = overrideFragmentNode; + + } + // object.onAfterRender( this, scene, camera, geometry, material, group ); @@ -73498,6 +75611,36 @@ var THREE = (async function (exports) { } + _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) { + + const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId ); + + // + + this._nodes.updateBefore( renderObject ); + + // + + this._nodes.updateForRender( renderObject ); + this._geometries.updateForRender( renderObject ); + this._bindings.updateForRender( renderObject ); + + this._pipelines.getForRender( renderObject, this._compilationPromises ); + + } + + get compute() { + + return this.computeAsync; + + } + + get compile() { + + return this.compileAsync; + + } + } class Binding { @@ -73532,24 +75675,6 @@ var THREE = (async function (exports) { } - function getVectorLength( count, vectorLength = 4 ) { - - const strideLength = getStrideLength( vectorLength ); - - const floatLength = strideLength * count; - - return getFloatLength( floatLength ); - - } - - function getStrideLength( vectorLength ) { - - const strideLength = 4; - - return vectorLength + ( ( strideLength - ( vectorLength % strideLength ) ) % strideLength ); - - } - class Buffer extends Binding { constructor( name, buffer = null ) { @@ -73596,6 +75721,26 @@ var THREE = (async function (exports) { } + let _id$2 = 0; + + class NodeUniformBuffer extends UniformBuffer { + + constructor( nodeUniform ) { + + super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + + } + class UniformsGroup extends UniformBuffer { constructor( name ) { @@ -73658,6 +75803,8 @@ var THREE = (async function (exports) { const uniform = this.uniforms[ i ]; + const { boundary, itemSize } = uniform; + // offset within a single chunk in bytes const chunkOffset = offset % GPU_CHUNK_BYTES; @@ -73665,23 +75812,23 @@ var THREE = (async function (exports) { // conformance tests - if ( chunkOffset !== 0 && ( remainingSizeInChunk - uniform.boundary ) < 0 ) { + if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) { // check for chunk overflow offset += ( GPU_CHUNK_BYTES - chunkOffset ); - } else if ( chunkOffset % uniform.boundary !== 0 ) { + } else if ( chunkOffset % boundary !== 0 ) { // check for correct alignment - offset += ( chunkOffset % uniform.boundary ); + offset += ( chunkOffset % boundary ); } uniform.offset = ( offset / this.bytesPerElement ); - offset += ( uniform.itemSize * this.bytesPerElement ); + offset += ( itemSize * this.bytesPerElement ); } @@ -74022,7 +76169,8 @@ var THREE = (async function (exports) { const glslMethods = { [ MathNode.ATAN2 ]: 'atan', - textureDimensions: 'textureSize' + textureDimensions: 'textureSize', + equals: 'equal' }; const precisionLib = { @@ -74032,7 +76180,8 @@ var THREE = (async function (exports) { }; const supports$1 = { - instance: true + instance: true, + swizzleAssign: true }; const defaultPrecisions = ` @@ -74049,6 +76198,7 @@ precision lowp sampler2DShadow; super( object, renderer, new GLSLNodeParser(), scene ); this.uniformGroups = {}; + this.transforms = []; } @@ -74096,6 +76246,130 @@ ${ flowData.code } } + setupPBO( storageBufferNode ) { + + const attribute = storageBufferNode.value; + + if ( attribute.pbo === undefined ) { + + const originalArray = attribute.array; + const numElements = attribute.count * attribute.itemSize; + + const { itemSize } = attribute; + let format = RedFormat; + + if ( itemSize === 2 ) { + + format = RGFormat; + + } else if ( itemSize === 3 ) { + + format = 6407; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization + + } else if ( itemSize === 4 ) { + + format = RGBAFormat; + + } + + const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) ); + let height = Math.ceil( ( numElements / itemSize ) / width ); + if ( width * height * itemSize < numElements ) height ++; // Ensure enough space + + const newSize = width * height * itemSize; + + const newArray = new Float32Array( newSize ); + + newArray.set( originalArray, 0 ); + + attribute.array = newArray; + + const pboTexture = new DataTexture( attribute.array, width, height, format, FloatType ); + pboTexture.needsUpdate = true; + pboTexture.isPBOTexture = true; + + const pbo = new UniformNode( pboTexture ); + pbo.setPrecision( 'high' ); + + attribute.pboNode = pbo; + attribute.pbo = pbo.value; + + this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + + } + + } + + generatePBO( storageArrayElementNode ) { + + const { node, indexNode } = storageArrayElementNode; + const attribute = node.value; + + if ( this.renderer.backend.has( attribute ) ) { + + const attributeData = this.renderer.backend.get( attribute ); + attributeData.pbo = attribute.pbo; + + } + + + const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + const textureName = this.getPropertyName( nodeUniform ); + + indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y + const indexSnippet = indexNode.build( this, 'uint' ); + + const elementNodeData = this.getDataFromNode( storageArrayElementNode ); + + let propertyName = elementNodeData.propertyName; + + if ( propertyName === undefined ) { + + // property element + + const nodeVar = this.getVarFromNode( storageArrayElementNode ); + + propertyName = this.getPropertyName( nodeVar ); + + // property size + + const bufferNodeData = this.getDataFromNode( node ); + + let propertySizeName = bufferNodeData.propertySizeName; + + if ( propertySizeName === undefined ) { + + propertySizeName = propertyName + 'Size'; + + this.getVarFromNode( node, propertySizeName, 'uint' ); + + this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` ); + + bufferNodeData.propertySizeName = propertySizeName; + + } + + // + + const { itemSize } = attribute; + + const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize ); + const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`; + + const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' ); + + // + + this.addLineFlowCode( `${ propertyName } = ${ snippet + channel }` ); + + elementNodeData.propertyName = propertyName; + + } + + return propertyName; + + } + generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) { if ( depthSnippet ) { @@ -74288,7 +76562,7 @@ ${ flowData.code } let snippet = ''; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { const attributes = this.getAttributesArray(); @@ -74355,10 +76629,11 @@ ${ flowData.code } const varyings = this.varyings; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { for ( const varying of varyings ) { + if ( shaderStage === 'compute' ) varying.needsInterpolation = true; const type = varying.type; const flat = type === 'int' || type === 'uint' ? 'flat ' : ''; @@ -74423,13 +76698,38 @@ ${ flowData.code } } - isFlipY() { return true; } + registerTransform( varyingName, attributeNode ) { + + this.transforms.push( { varyingName, attributeNode } ); + + } + + getTransforms( /* shaderStage */ ) { + + const transforms = this.transforms; + + let snippet = ''; + + for ( let i = 0; i < transforms.length; i ++ ) { + + const transform = transforms[ i ]; + + const attributeName = this.getPropertyName( transform.attributeNode ); + + snippet += `${ transform.varyingName } = ${ attributeName };\n\t`; + + } + + return snippet; + + } + _getGLSLUniformStruct( name, vars ) { return ` @@ -74465,6 +76765,9 @@ void main() { // vars ${shaderData.vars} + // transforms + ${shaderData.transforms} + // flow ${shaderData.flow} @@ -74567,6 +76870,7 @@ void main() { stageData.vars = this.getVars( shaderStage ); stageData.structs = this.getStructs( shaderStage ); stageData.codes = this.getCodes( shaderStage ); + stageData.transforms = this.getTransforms( shaderStage ); stageData.flow = flow; } @@ -74576,6 +76880,10 @@ void main() { this.vertexShader = this._getGLSLVertexCode( shadersData.vertex ); this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment ); + } else { + + this.computeShader = this._getGLSLVertexCode( shadersData.compute ); + } } @@ -74603,11 +76911,11 @@ void main() { } else if ( type === 'buffer' ) { - node.name = `NodeBuffer_${node.id}`; - - const buffer = new UniformBuffer( node.name, node.value ); + node.name = `NodeBuffer_${ node.id }`; + uniformNode.name = `buffer${ node.id }`; - uniformNode.name = `buffer${node.id}`; + const buffer = new NodeUniformBuffer( node ); + buffer.name = node.name; this.bindings[ shaderStage ].push( buffer ); @@ -74738,6 +77046,10 @@ void main() { // utils + resolveTimestampAsync( renderContext, type ) { } + + hasFeatureAsync( name ) { } // return Boolean + hasFeature( name ) { } // return Boolean getInstanceCount( renderObject ) { @@ -74764,6 +77076,8 @@ void main() { } + setScissorTest( boolean ) { } + getClearColor() { const renderer = this.renderer; @@ -74820,6 +77134,12 @@ void main() { } + has( object ) { + + return this.data.has( object ); + + } + delete( object ) { this.data.delete( object ); @@ -74828,6 +77148,52 @@ void main() { } + let _id$1 = 0; + + class DualAttributeData { + + constructor( attributeData, dualBuffer ) { + + this.buffers = [ attributeData.bufferGPU, dualBuffer ]; + this.type = attributeData.type; + this.bufferType = attributeData.bufferType; + this.pbo = attributeData.pbo; + this.byteLength = attributeData.byteLength; + this.bytesPerElement = attributeData.BYTES_PER_ELEMENT; + this.version = attributeData.version; + this.isInteger = attributeData.isInteger; + this.activeBufferIndex = 0; + this.baseId = attributeData.id; + + } + + + get id() { + + return `${ this.baseId }|${ this.activeBufferIndex }`; + + } + + get bufferGPU() { + + return this.buffers[ this.activeBufferIndex ]; + + } + + get transformBuffer() { + + return this.buffers[ this.activeBufferIndex ^ 1 ]; + + } + + switchBuffers() { + + this.activeBufferIndex ^= 1; + + } + + } + class WebGLAttributeUtils { constructor( backend ) { @@ -74851,11 +77217,7 @@ void main() { if ( bufferGPU === undefined ) { - bufferGPU = gl.createBuffer(); - - gl.bindBuffer( bufferType, bufferGPU ); - gl.bufferData( bufferType, array, usage ); - gl.bindBuffer( bufferType, null ); + bufferGPU = this._createBuffer( gl, bufferType, array, usage ); bufferData.bufferGPU = bufferGPU; bufferData.bufferType = bufferType; @@ -74913,13 +77275,27 @@ void main() { } - backend.set( attribute, { + let attributeData = { bufferGPU, + bufferType, type, + byteLength: array.byteLength, bytesPerElement: array.BYTES_PER_ELEMENT, version: attribute.version, - isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType - } ); + pbo: attribute.pbo, + isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType, + id: _id$1 ++ + }; + + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) { + + // create buffer for tranform feedback use + const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage ); + attributeData = new DualAttributeData( attributeData, bufferGPUDual ); + + } + + backend.set( attribute, attributeData ); } @@ -75013,6 +77389,18 @@ void main() { } + _createBuffer( gl, bufferType, array, usage ) { + + const bufferGPU = gl.createBuffer(); + + gl.bindBuffer( bufferType, bufferGPU ); + gl.bufferData( bufferType, array, usage ); + gl.bindBuffer( bufferType, null ); + + return bufferGPU; + + } + } let initialized$1 = false, equationToGL, factorToGL; @@ -75770,6 +78158,7 @@ void main() { } if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === gl.RGB ) return gl.RGB; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization if ( p === RGBAFormat ) return gl.RGBA; if ( p === LuminanceFormat ) return gl.LUMINANCE; if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA; @@ -76149,6 +78538,17 @@ void main() { } + if ( glFormat === gl.RGB ) { + + if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F; + if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F; + if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8; + if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565; + if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1; + if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4; + + } + if ( glFormat === gl.RGBA ) { if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F; @@ -76186,7 +78586,9 @@ void main() { setTextureParameters( textureType, texture ) { - const { gl, extensions } = this; + const { gl, extensions, backend } = this; + + const { currentAnisotropy } = backend.get( texture ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); @@ -76201,7 +78603,7 @@ void main() { // follow WebGPU backend mapping for texture filtering - const minFilter = texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; + const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] ); @@ -76214,13 +78616,17 @@ void main() { if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - //extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 - if ( texture.anisotropy > 1 /*|| properties.get( texture ).__currentAnisotropy*/ ) ; + if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) ); + backend.get( texture ).currentAnisotropy = texture.anisotropy; + + } } @@ -76298,6 +78704,41 @@ void main() { } + copyBufferToTexture( buffer, texture ) { + + const { gl, backend } = this; + + const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture ); + + const { width, height } = texture.source.data; + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer ); + + backend.state.bindTexture( glTextureType, textureGPU ); + + gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false ); + gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false ); + gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 ); + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null ); + + backend.state.unbindTexture(); + // debug + // const framebuffer = gl.createFramebuffer(); + // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer ); + // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 ); + + // const readout = new Float32Array( width * height * 4 ); + + // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ); + // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ); + + // gl.readPixels( 0, 0, width, height, altFormat, altType, readout ); + // gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + // console.log( readout ); + + } + updateTexture( texture, options ) { const { gl } = this; @@ -76487,21 +78928,25 @@ void main() { const width = texture.image.width; const height = texture.image.height; - state.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); - if ( texture.isDepthTexture ) { - const fb = gl.createFramebuffer(); + let mask = gl.DEPTH_BUFFER_BIT; + + if ( renderContext.stencil ) { - gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); + mask |= gl.STENCIL_BUFFER_BIT; + + } + + const fb = gl.createFramebuffer(); + state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, textureGPU, 0 ); - gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST ); + gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST ); gl.deleteFramebuffer( fb ); - } else { state.bindTexture( gl.TEXTURE_2D, textureGPU ); @@ -76621,10 +79066,11 @@ void main() { if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array; - if ( glType === gl.UNSIGNED_INT ) return Uint32Array; - if ( glType === gl.UNSIGNED_FLOAT ) return Float32Array; + if ( glType === gl.FLOAT ) return Float32Array; + + throw new Error( `Unsupported WebGL type: ${glType}` ); } @@ -76753,7 +79199,12 @@ void main() { this.state = new WebGLState( this ); this.utils = new WebGLUtils( this ); + this.vaoCache = {}; + this.transformFeedbackCache = {}; + this.discard = false; + this.extensions.get( 'EXT_color_buffer_float' ); + this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' ); this._currentContext = null; } @@ -76790,7 +79241,7 @@ void main() { this._setFramebuffer( renderContext ); - this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext ); + this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false ); // if ( renderContext.viewport ) { @@ -76803,6 +79254,14 @@ void main() { } + if ( renderContext.scissor ) { + + const { x, y, width, height } = renderContext.scissorValue; + + gl.scissor( x, y, width, height ); + + } + const occlusionQueryCount = renderContext.occlusionQueryCount; if ( occlusionQueryCount > 0 ) { @@ -76995,7 +79454,23 @@ void main() { } - clear( color, depth, stencil, descriptor = null ) { + setScissorTest( boolean ) { + + const gl = this.gl; + + if ( boolean ) { + + gl.enable( gl.SCISSOR_TEST ); + + } else { + + gl.disable( gl.SCISSOR_TEST ); + + } + + } + + clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) { const { gl } = this; @@ -77018,7 +79493,7 @@ void main() { if ( clear !== 0 ) { - const clearColor = descriptor.clearColorValue; + const clearColor = descriptor.clearColorValue || this.getClearColor(); if ( depth ) this.state.setDepthMask( true ); @@ -77029,6 +79504,8 @@ void main() { } else { + if ( setFrameBuffer ) this._setFramebuffer( descriptor ); + if ( color ) { for ( let i = 0; i < descriptor.textures.length; i ++ ) { @@ -77061,20 +79538,95 @@ void main() { beginCompute( /*computeGroup*/ ) { + const gl = this.gl; + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + } - compute( /*computeGroup, computeNode, bindings, pipeline*/ ) { + compute( computeGroup, computeNode, bindings, pipeline ) { + + const gl = this.gl; + + if ( ! this.discard ) { + + // required here to handle async behaviour of render.compute() + gl.enable( gl.RASTERIZER_DISCARD ); + this.discard = true; + + } + + const { programGPU, transformBuffers, attributes } = this.get( pipeline ); + + const vaoKey = this._getVaoKey( null, attributes ); + + const vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + this._createVao( null, attributes ); + + } else { + + gl.bindVertexArray( vaoGPU ); + + } + + gl.useProgram( programGPU ); + + this._bindUniforms( bindings ); + + const transformFeedbackGPU = this._getTransformFeedback( transformBuffers ); + + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); + gl.beginTransformFeedback( gl.POINTS ); + + if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) { + + gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count ); + + } else { + + gl.drawArrays( gl.POINTS, 0, computeNode.count ); + + } + + gl.endTransformFeedback(); + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); + + // switch active buffers + + for ( let i = 0; i < transformBuffers.length; i ++ ) { + + const dualAttributeData = transformBuffers[ i ]; + + if ( dualAttributeData.pbo ) { + + this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo ); + + } + + dualAttributeData.switchBuffers(); + + + } } finishCompute( /*computeGroup*/ ) { + const gl = this.gl; + + this.discard = false; + + gl.disable( gl.RASTERIZER_DISCARD ); + } draw( renderObject, info ) { const { pipeline, material, context } = renderObject; - const { programGPU, vaoGPU } = this.get( pipeline ); + const { programGPU } = this.get( pipeline ); const { gl, state } = this; @@ -77082,28 +79634,34 @@ void main() { // - const bindings = renderObject.getBindings(); + this._bindUniforms( renderObject.getBindings() ); - for ( const binding of bindings ) { + state.setMaterial( material ); - const bindingData = this.get( binding ); - const index = bindingData.index; + gl.useProgram( programGPU ); - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + // - gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); + let vaoGPU = renderObject.staticVao; - } else if ( binding.isSampledTexture ) { + if ( vaoGPU === undefined ) { - state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); + const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() ); + + vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + let staticVao; + + ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) ); + + if ( staticVao ) renderObject.staticVao = vaoGPU; } } - state.setMaterial( material ); - - gl.useProgram( programGPU ); gl.bindVertexArray( vaoGPU ); // @@ -77185,7 +79743,6 @@ void main() { } - info.update( object, indexCount, 1 ); } else { @@ -77209,8 +79766,6 @@ void main() { } - - // gl.bindVertexArray( null ); @@ -77291,7 +79846,7 @@ void main() { const gl = this.gl; const { stage, code } = program; - const shader = stage === 'vertex' ? gl.createShader( gl.VERTEX_SHADER ) : gl.createShader( gl.FRAGMENT_SHADER ); + const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER ); gl.shaderSource( shader, code ); gl.compileShader( shader ); @@ -77306,7 +79861,7 @@ void main() { } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const gl = this.gl; const pipeline = renderObject.pipeline; @@ -77324,39 +79879,487 @@ void main() { gl.attachShader( programGPU, vertexShader ); gl.linkProgram( programGPU ); + this.set( pipeline, { + programGPU, + fragmentShader, + vertexShader + } ); + + if ( promises !== null && this.parallel ) { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + const parallel = this.parallel; + const checkStatus = () => { + + if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) { + + this._completeCompile( renderObject, pipeline ); + resolve(); + + } else { + + requestAnimationFrame( checkStatus ); + + } + + }; + + checkStatus(); + + } ); + + promises.push( p ); + + return; + + } + + this._completeCompile( renderObject, pipeline ); + + } + + _completeCompile( renderObject, pipeline ) { + + const gl = this.gl; + const pipelineData = this.get( pipeline ); + const { programGPU, fragmentShader, vertexShader } = pipelineData; + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; gl.useProgram( programGPU ); // Bindings - const bindings = renderObject.getBindings(); + this._setupBindings( renderObject.getBindings(), programGPU ); - for ( const binding of bindings ) { + // - const bindingData = this.get( binding ); - const index = bindingData.index; + this.set( pipeline, { + programGPU + } ); + + } + + createComputePipeline( computePipeline, bindings ) { + + const gl = this.gl; + + // Program + + const fragmentProgram = { + stage: 'fragment', + code: '#version 300 es\nprecision highp float;\nvoid main() {}' + }; + + this.createProgram( fragmentProgram ); + + const { computeProgram } = computePipeline; + + const programGPU = gl.createProgram(); + + const fragmentShader = this.get( fragmentProgram ).shaderGPU; + const vertexShader = this.get( computeProgram ).shaderGPU; + + const transforms = computeProgram.transforms; + + const transformVaryingNames = []; + const transformAttributeNodes = []; + + for ( let i = 0; i < transforms.length; i ++ ) { + + const transform = transforms[ i ]; + + transformVaryingNames.push( transform.varyingName ); + transformAttributeNodes.push( transform.attributeNode ); + + } + + gl.attachShader( programGPU, fragmentShader ); + gl.attachShader( programGPU, vertexShader ); + + gl.transformFeedbackVaryings( + programGPU, + transformVaryingNames, + gl.SEPARATE_ATTRIBS, + ); + + gl.linkProgram( programGPU ); + + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; + + gl.useProgram( programGPU ); + + // Bindings + + this.createBindings( bindings ); + + this._setupBindings( bindings, programGPU ); + + const attributeNodes = computeProgram.attributes; + const attributes = []; + const transformBuffers = []; + + for ( let i = 0; i < attributeNodes.length; i ++ ) { + + const attribute = attributeNodes[ i ].node.attribute; + + attributes.push( attribute ); + + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + } + + for ( let i = 0; i < transformAttributeNodes.length; i ++ ) { + + const attribute = transformAttributeNodes[ i ].attribute; + + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + const attributeData = this.get( attribute ); + + transformBuffers.push( attributeData ); + + } + + // + + this.set( computePipeline, { + programGPU, + transformBuffers, + attributes + } ); + + } + + createBindings( bindings ) { + + this.updateBindings( bindings ); + + } + + updateBindings( bindings ) { + + const { gl } = this; + + let groupIndex = 0; + let textureIndex = 0; + + for ( const binding of bindings ) { if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - const location = gl.getUniformBlockIndex( programGPU, binding.name ); - gl.uniformBlockBinding( programGPU, location, index ); + const bufferGPU = gl.createBuffer(); + const data = binding.buffer; + + gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); + gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU ); + + this.set( binding, { + index: groupIndex ++, + bufferGPU + } ); } else if ( binding.isSampledTexture ) { - const location = gl.getUniformLocation( programGPU, binding.name ); - gl.uniform1i( location, index ); + const { textureGPU, glTextureType } = this.get( binding.texture ); + + this.set( binding, { + index: textureIndex ++, + textureGPU, + glTextureType + } ); } } - // VAO + } + + updateBinding( binding ) { + + const gl = this.gl; + + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + + const bindingData = this.get( binding ); + const bufferGPU = bindingData.bufferGPU; + const data = binding.buffer; + + gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); + gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + + } + + } + + // attributes + + createIndexAttribute( attribute ) { + + const gl = this.gl; + + this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + + } + + createAttribute( attribute ) { + + if ( this.has( attribute ) ) return; + + const gl = this.gl; + + this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + } + + createStorageAttribute( attribute ) { + + //console.warn( 'Abstract class.' ); + + } + + updateAttribute( attribute ) { + + this.attributeUtils.updateAttribute( attribute ); + + } + + destroyAttribute( attribute ) { + + this.attributeUtils.destroyAttribute( attribute ); + + } + + updateSize() { + + //console.warn( 'Abstract class.' ); + + } + + async hasFeatureAsync( name ) { + + return this.hasFeature( name ); + + } + + hasFeature( name ) { + + const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); + + const extensions = this.extensions; + + for ( let i = 0; i < keysMatching.length; i ++ ) { + + + if ( extensions.has( keysMatching[ i ] ) ) return true; + + } + + return false; + + } + + + getMaxAnisotropy() { + + return this.capabilities.getMaxAnisotropy(); + + } + + copyFramebufferToTexture( texture, renderContext ) { + + this.textureUtils.copyFramebufferToTexture( texture, renderContext ); + + } + + _setFramebuffer( renderContext ) { + + const { gl, state } = this; + + let currentFrameBuffer = null; + + if ( renderContext.textures !== null ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetContextData = this.get( renderTarget ); + const { samples, depthBuffer, stencilBuffer } = renderTarget; + const cubeFace = this.renderer._activeCubeFace; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + + let msaaFb = renderTargetContextData.msaaFrameBuffer; + let depthRenderbuffer = renderTargetContextData.depthRenderbuffer; + + let fb; + + if ( isCube ) { + + if ( renderTargetContextData.cubeFramebuffers === undefined ) { + + renderTargetContextData.cubeFramebuffers = []; + + } + + fb = renderTargetContextData.cubeFramebuffers[ cubeFace ]; + + } else { + + fb = renderTargetContextData.framebuffer; + + } + + if ( fb === undefined ) { + + fb = gl.createFramebuffer(); + + state.bindFramebuffer( gl.FRAMEBUFFER, fb ); + + const textures = renderContext.textures; + + if ( isCube ) { + + renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb; + const { textureGPU } = this.get( textures[ 0 ] ); + + gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 ); + + } else { + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + const textureData = this.get( texture ); + textureData.renderTarget = renderContext.renderTarget; + + const attachment = gl.COLOR_ATTACHMENT0 + i; + + gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 ); + + } + + renderTargetContextData.framebuffer = fb; + + state.drawBuffers( renderContext, fb ); + + } + + if ( renderContext.depthTexture !== null ) { + + const textureData = this.get( renderContext.depthTexture ); + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + + gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 ); + + } + + } + + if ( samples > 0 ) { + + if ( msaaFb === undefined ) { + + const invalidationArray = []; + + msaaFb = gl.createFramebuffer(); + + state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb ); + + const msaaRenderbuffers = []; + + const textures = renderContext.textures; + + for ( let i = 0; i < textures.length; i ++ ) { + + + msaaRenderbuffers[ i ] = gl.createRenderbuffer(); + + gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); + + invalidationArray.push( gl.COLOR_ATTACHMENT0 + i ); + + if ( depthBuffer ) { + + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + invalidationArray.push( depthStyle ); + + } + + const texture = renderContext.textures[ i ]; + const textureData = this.get( texture ); + + gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height ); + gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); + + + } + + renderTargetContextData.msaaFrameBuffer = msaaFb; + renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers; + + if ( depthRenderbuffer === undefined ) { + + depthRenderbuffer = gl.createRenderbuffer(); + this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext ); + + renderTargetContextData.depthRenderbuffer = depthRenderbuffer; + + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + invalidationArray.push( depthStyle ); + + } + + renderTargetContextData.invalidationArray = invalidationArray; + + } + + currentFrameBuffer = renderTargetContextData.msaaFrameBuffer; + + } else { + + currentFrameBuffer = fb; + + } + + } + + state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer ); + + } + + + _getVaoKey( index, attributes ) { + + let key = []; + + if ( index !== null ) { + + const indexData = this.get( index ); + + key += ':' + indexData.id; + + } + + for ( let i = 0; i < attributes.length; i ++ ) { + + const attributeData = this.get( attributes[ i ] ); + + key += ':' + attributeData.id; + + } + + return key; + + } + + _createVao( index, attributes ) { + + const { gl } = this; const vaoGPU = gl.createVertexArray(); + let key = ''; - const index = renderObject.getIndex(); - const attributes = renderObject.getAttributes(); + let staticVao = true; gl.bindVertexArray( vaoGPU ); @@ -77366,6 +80369,8 @@ void main() { gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU ); + key += ':' + indexData.id; + } for ( let i = 0; i < attributes.length; i ++ ) { @@ -77373,9 +80378,13 @@ void main() { const attribute = attributes[ i ]; const attributeData = this.get( attribute ); + key += ':' + attributeData.id; + gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU ); gl.enableVertexAttribArray( i ); + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false; + let stride, offset; if ( attribute.isInterleavedBufferAttribute === true ) { @@ -77412,304 +80421,101 @@ void main() { } - gl.bindVertexArray( null ); - - // - - this.set( pipeline, { - programGPU, - vaoGPU - } ); + gl.bindBuffer( gl.ARRAY_BUFFER, null ); - } + this.vaoCache[ key ] = vaoGPU; - createComputePipeline( /*computePipeline, bindings*/ ) { + return { vaoGPU, staticVao }; } - createBindings( bindings ) { - - this.updateBindings( bindings ); - - } - - updateBindings( bindings ) { - - const { gl } = this; - - let groupIndex = 0; - let textureIndex = 0; - - for ( const binding of bindings ) { + _getTransformFeedback( transformBuffers ) { - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + let key = ''; - const bufferGPU = gl.createBuffer(); - const data = binding.buffer; + for ( let i = 0; i < transformBuffers.length; i ++ ) { - gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); - gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); - gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU ); - - this.set( binding, { - index: groupIndex ++, - bufferGPU - } ); - - } else if ( binding.isSampledTexture ) { - - const { textureGPU, glTextureType } = this.get( binding.texture ); - - this.set( binding, { - index: textureIndex ++, - textureGPU, - glTextureType - } ); - - } + key += ':' + transformBuffers[ i ].id; } - } + let transformFeedbackGPU = this.transformFeedbackCache[ key ]; - updateBinding( binding ) { + if ( transformFeedbackGPU !== undefined ) { - const gl = this.gl; - - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - - const bindingData = this.get( binding ); - const bufferGPU = bindingData.bufferGPU; - const data = binding.buffer; - - gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); - gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + return transformFeedbackGPU; } - } - - // attributes - - createIndexAttribute( attribute ) { - const gl = this.gl; - this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - - } + transformFeedbackGPU = gl.createTransformFeedback(); - createAttribute( attribute ) { + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); - const gl = this.gl; + for ( let i = 0; i < transformBuffers.length; i ++ ) { - this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + const attributeData = transformBuffers[ i ]; - } + gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer ); - createStorageAttribute( /*attribute*/ ) { + } - } + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); - updateAttribute( attribute ) { + this.transformFeedbackCache[ key ] = transformFeedbackGPU; - this.attributeUtils.updateAttribute( attribute ); + return transformFeedbackGPU; } - destroyAttribute( attribute ) { - - this.attributeUtils.destroyAttribute( attribute ); - } - - updateSize() { + _setupBindings( bindings, programGPU ) { - //console.warn( 'Abstract class.' ); + const gl = this.gl; - } + for ( const binding of bindings ) { - hasFeature( name ) { + const bindingData = this.get( binding ); + const index = bindingData.index; - const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - const extensions = this.extensions; + const location = gl.getUniformBlockIndex( programGPU, binding.name ); + gl.uniformBlockBinding( programGPU, location, index ); - for ( let i = 0; i < keysMatching.length; i ++ ) { + } else if ( binding.isSampledTexture ) { + const location = gl.getUniformLocation( programGPU, binding.name ); + gl.uniform1i( location, index ); - if ( extensions.has( keysMatching[ i ] ) ) return true; + } } - return false; - } - - getMaxAnisotropy() { - - return this.capabilities.getMaxAnisotropy(); - - } - - copyFramebufferToTexture( texture, renderContext ) { - - this.textureUtils.copyFramebufferToTexture( texture, renderContext ); - - } - - _setFramebuffer( renderContext ) { + _bindUniforms( bindings ) { const { gl, state } = this; - let currentFrameBuffer = null; - - if ( renderContext.textures !== null ) { - - const renderTarget = renderContext.renderTarget; - const renderTargetContextData = this.get( renderTarget ); - const { samples, depthBuffer, stencilBuffer } = renderTarget; - const cubeFace = this.renderer._activeCubeFace; - const isCube = renderTarget.isWebGLCubeRenderTarget === true; - - let msaaFb = renderTargetContextData.msaaFrameBuffer; - let depthRenderbuffer = renderTargetContextData.depthRenderbuffer; - - let fb; - - if ( isCube ) { - - if ( renderTargetContextData.cubeFramebuffers === undefined ) { - - renderTargetContextData.cubeFramebuffers = []; - - } - - fb = renderTargetContextData.cubeFramebuffers[ cubeFace ]; - - } else { - - fb = renderTargetContextData.framebuffer; - - } - - if ( fb === undefined ) { - - fb = gl.createFramebuffer(); - - state.bindFramebuffer( gl.FRAMEBUFFER, fb ); - - const textures = renderContext.textures; - - if ( isCube ) { - - renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb; - const { textureGPU } = this.get( textures[ 0 ] ); - - gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 ); - - } else { - - for ( let i = 0; i < textures.length; i ++ ) { - - const texture = textures[ i ]; - const textureData = this.get( texture ); - textureData.renderTarget = renderContext.renderTarget; - - const attachment = gl.COLOR_ATTACHMENT0 + i; - - gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 ); - - } - - renderTargetContextData.framebuffer = fb; - - state.drawBuffers( renderContext, fb ); - - } - - if ( renderContext.depthTexture !== null ) { - - const textureData = this.get( renderContext.depthTexture ); - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - - gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 ); - - } - - } - - if ( samples > 0 ) { - - if ( msaaFb === undefined ) { - - const invalidationArray = []; - - msaaFb = gl.createFramebuffer(); - - state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb ); - - const msaaRenderbuffers = []; - - const textures = renderContext.textures; - - for ( let i = 0; i < textures.length; i ++ ) { - - - msaaRenderbuffers[ i ] = gl.createRenderbuffer(); - - gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); - - invalidationArray.push( gl.COLOR_ATTACHMENT0 + i ); - - if ( depthBuffer ) { - - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - invalidationArray.push( depthStyle ); - - } - - const texture = renderContext.textures[ i ]; - const textureData = this.get( texture ); - - gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height ); - gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); - - - } - - renderTargetContextData.msaaFrameBuffer = msaaFb; - renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers; - - if ( depthRenderbuffer === undefined ) { - - depthRenderbuffer = gl.createRenderbuffer(); - this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext ); - - renderTargetContextData.depthRenderbuffer = depthRenderbuffer; - - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - invalidationArray.push( depthStyle ); - - } + for ( const binding of bindings ) { - renderTargetContextData.invalidationArray = invalidationArray; + const bindingData = this.get( binding ); + const index = bindingData.index; - } + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - currentFrameBuffer = renderTargetContextData.msaaFrameBuffer; + gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); - } else { + } else if ( binding.isSampledTexture ) { - currentFrameBuffer = fb; + state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); } } - state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer ); - } } @@ -78041,6 +80847,26 @@ void main() { } + let _id = 0; + + class NodeStorageBuffer extends StorageBuffer { + + constructor( nodeUniform ) { + + super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + + } + class WebGPUTexturePassUtils { constructor( device ) { @@ -78631,13 +81457,13 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { if ( texture.isDataTexture || texture.isData3DTexture ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, false ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY ); } else if ( texture.isDataArrayTexture ) { for ( let i = 0; i < options.image.depth; i ++ ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, false, i ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i ); } @@ -78678,6 +81504,9 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { const format = textureData.textureDescriptorGPU.format; const bytesPerTexel = this._getBytesPerTexel( format ); + let bytesPerRow = width * bytesPerTexel; + bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes + const readBuffer = device.createBuffer( { size: width * height * bytesPerTexel, @@ -78694,7 +81523,7 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { }, { buffer: readBuffer, - bytesPerRow: width * bytesPerTexel + bytesPerRow: bytesPerRow }, { width: width, @@ -78983,15 +81812,57 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { _getBytesPerTexel( format ) { - if ( format === GPUTextureFormat.R8Unorm ) return 1; - if ( format === GPUTextureFormat.R16Float ) return 2; - if ( format === GPUTextureFormat.RG8Unorm ) return 2; - if ( format === GPUTextureFormat.RG16Float ) return 4; - if ( format === GPUTextureFormat.R32Float ) return 4; - if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4; - if ( format === GPUTextureFormat.RG32Float ) return 8; - if ( format === GPUTextureFormat.RGBA16Float ) return 8; - if ( format === GPUTextureFormat.RGBA32Float ) return 16; + // 8-bit formats + if ( format === GPUTextureFormat.R8Unorm || + format === GPUTextureFormat.R8Snorm || + format === GPUTextureFormat.R8Uint || + format === GPUTextureFormat.R8Sint ) return 1; + + // 16-bit formats + if ( format === GPUTextureFormat.R16Uint || + format === GPUTextureFormat.R16Sint || + format === GPUTextureFormat.R16Float || + format === GPUTextureFormat.RG8Unorm || + format === GPUTextureFormat.RG8Snorm || + format === GPUTextureFormat.RG8Uint || + format === GPUTextureFormat.RG8Sint ) return 2; + + // 32-bit formats + if ( format === GPUTextureFormat.R32Uint || + format === GPUTextureFormat.R32Sint || + format === GPUTextureFormat.R32Float || + format === GPUTextureFormat.RG16Uint || + format === GPUTextureFormat.RG16Sint || + format === GPUTextureFormat.RG16Float || + format === GPUTextureFormat.RGBA8Unorm || + format === GPUTextureFormat.RGBA8UnormSRGB || + format === GPUTextureFormat.RGBA8Snorm || + format === GPUTextureFormat.RGBA8Uint || + format === GPUTextureFormat.RGBA8Sint || + format === GPUTextureFormat.BGRA8Unorm || + format === GPUTextureFormat.BGRA8UnormSRGB || + // Packed 32-bit formats + format === GPUTextureFormat.RGB9E5UFloat || + format === GPUTextureFormat.RGB10A2Unorm || + format === GPUTextureFormat.RG11B10UFloat || + format === GPUTextureFormat.Depth32Float || + format === GPUTextureFormat.Depth24Plus || + format === GPUTextureFormat.Depth24PlusStencil8 || + format === GPUTextureFormat.Depth32FloatStencil8 ) return 4; + + // 64-bit formats + if ( format === GPUTextureFormat.RG32Uint || + format === GPUTextureFormat.RG32Sint || + format === GPUTextureFormat.RG32Float || + format === GPUTextureFormat.RGBA16Uint || + format === GPUTextureFormat.RGBA16Sint || + format === GPUTextureFormat.RGBA16Float ) return 8; + + // 128-bit formats + if ( format === GPUTextureFormat.RGBA32Uint || + format === GPUTextureFormat.RGBA32Sint || + format === GPUTextureFormat.RGBA32Float ) return 16; + } @@ -79017,6 +81888,9 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { if ( format === GPUTextureFormat.RG16Sint ) return Int16Array; if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array; if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array; + if ( format === GPUTextureFormat.R16Float ) return Float32Array; + if ( format === GPUTextureFormat.RG16Float ) return Float32Array; + if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array; if ( format === GPUTextureFormat.R32Uint ) return Uint32Array; @@ -79029,6 +81903,17 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array; if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array; + if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array; + if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array; + if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array; + if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array; + if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array; + + if ( format === GPUTextureFormat.Depth32Float ) return Float32Array; + if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array; + if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array; + if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array; + } _getDimension( texture ) { @@ -79059,7 +81944,7 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { let formatGPU; - if ( /*texture.isRenderTargetTexture === true ||*/ texture.isFramebufferTexture === true ) { + if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) { formatGPU = GPUTextureFormat.BGRA8Unorm; @@ -79368,7 +82253,7 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { } // GPUShaderStage is not defined in browsers not supporting WebGPU - const GPUShaderStage = window.GPUShaderStage; + const GPUShaderStage = self.GPUShaderStage; const gpuShaderStageLib = { 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1, @@ -79377,7 +82262,8 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { }; const supports = { - instance: true + instance: true, + storageBuffer: true }; const wgslFnOpLib = { @@ -79406,6 +82292,11 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { uvec4: 'vec4', bvec4: 'vec4', + mat2: 'mat2x2', + imat2: 'mat2x2', + umat2: 'mat2x2', + bmat2: 'mat2x2', + mat3: 'mat3x3', imat3: 'mat3x3', umat3: 'mat3x3', @@ -79424,6 +82315,10 @@ fn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 { mod_vec2: 'threejs_mod_vec2', mod_vec3: 'threejs_mod_vec3', mod_vec4: 'threejs_mod_vec4', + equals_bool: 'threejs_equals_bool', + equals_bvec2: 'threejs_equals_bvec2', + equals_bvec3: 'threejs_equals_bvec3', + equals_bvec4: 'threejs_equals_bvec4', lessThanEqual: 'threejs_lessThanEqual', greaterThan: 'threejs_greaterThan', inversesqrt: 'inverseSqrt', @@ -79456,6 +82351,10 @@ fn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 { mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ), mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ), mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ), + equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ), + equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }' ), + equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }' ), + equals_bvec4: new CodeNode( 'fn threejs_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: new CodeNode( ` fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 { @@ -79555,6 +82454,12 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 } + generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) { + + return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`; + + } + isUnfilterable( texture ) { return texture.isDataTexture === true && texture.type === FloatType; @@ -79626,7 +82531,7 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 const name = node.name; const type = node.type; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { return name; @@ -79679,11 +82584,11 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 const bindings = this.bindings[ shaderStage ]; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { let texture = null; - if ( type === 'texture' ) { + if ( type === 'texture' || type === 'storageTexture' ) { texture = new NodeSampledTexture( uniformNode.name, uniformNode.node ); @@ -79715,8 +82620,8 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 } else if ( type === 'buffer' || type === 'storageBuffer' ) { - const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer; - const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value ); + const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer; + const buffer = new bufferClass( node ); buffer.setVisibility( gpuShaderStageLib[ shaderStage ] ); bindings.push( buffer ); @@ -79743,31 +82648,9 @@ fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 } - if ( node.isArrayUniformNode === true ) { - - uniformGPU = []; - - for ( const uniformNode of node.nodes ) { - - const uniformNodeGPU = this.getNodeUniform( uniformNode, type ); - - // fit bounds to buffer - uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize ); - uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize ); - - uniformsGroup.addUniform( uniformNodeGPU ); - - uniformGPU.push( uniformNodeGPU ); - - } - - } else { - - uniformGPU = this.getNodeUniform( uniformNode, type ); - - uniformsGroup.addUniform( uniformGPU ); + uniformGPU = this.getNodeUniform( uniformNode, type ); - } + uniformsGroup.addUniform( uniformGPU ); } @@ -80066,7 +82949,7 @@ ${ flowData.code } for ( const uniform of uniforms ) { - if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' ) { + if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) { const texture = uniform.node.value; @@ -80138,17 +83021,7 @@ ${ flowData.code } snippets: [] } ); - if ( Array.isArray( uniform.value ) === true ) { - - const length = uniform.value.length; - - group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` ); - - } else { - - group.snippets.push( `\t${uniform.name} : ${ vectorType}` ); - - } + group.snippets.push( `\t${ uniform.name } : ${ vectorType }` ); } @@ -80563,7 +83436,21 @@ var<${access}> ${name} : ${structName};`; const device = backend.device; - const array = bufferAttribute.array; + let array = bufferAttribute.array; + + if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) { + + bufferAttribute.itemSize = 4; + array = new array.constructor( bufferAttribute.count * 4 ); + + for ( let i = 0; i < bufferAttribute.count; i ++ ) { + + array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 ); + + } + + } + const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441 buffer = device.createBuffer( { @@ -81033,7 +83920,7 @@ var<${access}> ${name} : ${structName};`; } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const { object, material, geometry, pipeline } = renderObject; const { vertexProgram, fragmentProgram } = pipeline; @@ -81127,7 +84014,7 @@ var<${access}> ${name} : ${structName};`; } - pipelineData.pipeline = device.createRenderPipeline( { + const pipelineDescriptor = { vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ), fragment: Object.assign( {}, fragmentModule, { targets } ), primitive: primitiveState, @@ -81147,7 +84034,28 @@ var<${access}> ${name} : ${structName};`; layout: device.createPipelineLayout( { bindGroupLayouts: [ bindingsData.layout ] } ) - } ); + }; + + if ( promises === null ) { + + pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor ); + + } else { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => { + + pipelineData.pipeline = pipeline; + resolve(); + + } ); + + } ); + + promises.push( p ); + + } } @@ -81558,16 +84466,6 @@ var<${access}> ${name} : ${structName};`; import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js'; //*/ - // statics - - let _staticAdapter = null; - - if ( navigator.gpu !== undefined ) { - - _staticAdapter = await( navigator.gpu.requestAdapter()); - - } - // class WebGPUBackend extends Backend { @@ -81595,10 +84493,13 @@ var<${access}> ${name} : ${structName};`; this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits; + this.trackTimestamp = ( parameters.trackTimestamp === true ); + this.adapter = null; this.device = null; this.context = null; this.colorBuffer = null; + this.defaultRenderPassdescriptor = null; this.utils = new WebGPUUtils( this ); this.attributeUtils = new WebGPUAttributeUtils( this ); @@ -81689,60 +84590,88 @@ var<${access}> ${name} : ${structName};`; } - beginRender( renderContext ) { + _getDefaultRenderPassDescriptor() { - const renderContextData = this.get( renderContext ); + let descriptor = this.defaultRenderPassdescriptor; - const device = this.device; - const occlusionQueryCount = renderContext.occlusionQueryCount; + const antialias = this.parameters.antialias; - let occlusionQuerySet; + if ( descriptor === null ) { - if ( occlusionQueryCount > 0 ) { + const renderer = this.renderer; - if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); - if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + descriptor = { + colorAttachments: [ { + view: null + } ], + depthStencilAttachment: { + view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() + } + }; - // Get a reference to the array of objects with queries. The renderContextData property - // can be changed by another render pass before the buffer.mapAsyc() completes. - renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; - renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; - renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + const colorAttachment = descriptor.colorAttachments[ 0 ]; - // + if ( antialias === true ) { - occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + colorAttachment.view = this.colorBuffer.createView(); - renderContextData.occlusionQuerySet = occlusionQuerySet; - renderContextData.occlusionQueryIndex = 0; - renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + } else { - renderContextData.lastOcclusionObject = null; + colorAttachment.resolveTarget = undefined; - } + } - const descriptor = { - colorAttachments: [ { - view: null - } ], - depthStencilAttachment: { - view: null - }, - occlusionQuerySet - }; + this.defaultRenderPassdescriptor = descriptor; + + } const colorAttachment = descriptor.colorAttachments[ 0 ]; - const depthStencilAttachment = descriptor.depthStencilAttachment; - const antialias = this.parameters.antialias; + if ( antialias === true ) { - if ( renderContext.textures !== null ) { + colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - const textures = renderContext.textures; + } else { - descriptor.colorAttachments = []; + colorAttachment.view = this.context.getCurrentTexture().createView(); - const colorAttachments = descriptor.colorAttachments; + } + + return descriptor; + + } + + _getRenderPassDescriptor( renderContext ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetData = this.get( renderTarget ); + + let descriptors = renderTargetData.descriptors; + + if ( descriptors === undefined ) { + + descriptors = []; + + renderTargetData.descriptors = descriptors; + + } + + if ( renderTargetData.width !== renderTarget.width || + renderTargetData.height !== renderTarget.height || + renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel || + renderTargetData.samples !== renderTarget.samples + ) { + + descriptors.length = 0; + + } + + let descriptor = descriptors[ renderContext.activeCubeFace ]; + + if ( descriptor === undefined ) { + + const textures = renderContext.textures; + const colorAttachments = []; for ( let i = 0; i < textures.length; i ++ ) { @@ -81780,32 +84709,78 @@ var<${access}> ${name} : ${structName};`; const depthTextureData = this.get( renderContext.depthTexture ); - depthStencilAttachment.view = depthTextureData.texture.createView(); + const depthStencilAttachment = { + view: depthTextureData.texture.createView(), + }; - if ( renderContext.stencil && renderContext.depthTexture.format === DepthFormat ) { + descriptor = { + colorAttachments, + depthStencilAttachment + }; - renderContext.stencil = false; + descriptors[ renderContext.activeCubeFace ] = descriptor; - } + renderTargetData.width = renderTarget.width; + renderTargetData.height = renderTarget.height; + renderTargetData.samples = renderTarget.samples; + renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel; - } else { + } - if ( antialias === true ) { + return descriptor; - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); + } - } else { + beginRender( renderContext ) { - colorAttachment.view = this.context.getCurrentTexture().createView(); - colorAttachment.resolveTarget = undefined; + const renderContextData = this.get( renderContext ); - } + const device = this.device; + const occlusionQueryCount = renderContext.occlusionQueryCount; - depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ).createView(); + let occlusionQuerySet; + + if ( occlusionQueryCount > 0 ) { + + if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); + if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + + // Get a reference to the array of objects with queries. The renderContextData property + // can be changed by another render pass before the buffer.mapAsyc() completes. + renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; + renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; + renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + + // + + occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + + renderContextData.occlusionQuerySet = occlusionQuerySet; + renderContextData.occlusionQueryIndex = 0; + renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + + renderContextData.lastOcclusionObject = null; } + let descriptor; + + if ( renderContext.textures === null ) { + + descriptor = this._getDefaultRenderPassDescriptor(); + + } else { + + descriptor = this._getRenderPassDescriptor( renderContext ); + + } + + this.initTimestampQuery( renderContext, descriptor ); + + descriptor.occlusionQuerySet = occlusionQuerySet; + + const depthStencilAttachment = descriptor.depthStencilAttachment; + if ( renderContext.textures !== null ) { const colorAttachments = descriptor.colorAttachments; @@ -81829,9 +84804,10 @@ var<${access}> ${name} : ${structName};`; } - } else { + const colorAttachment = descriptor.colorAttachments[ 0 ]; + if ( renderContext.clearColor ) { colorAttachment.clearValue = renderContext.clearColorValue; @@ -81968,8 +84944,11 @@ var<${access}> ${name} : ${structName};`; } + this.prepareTimestampBuffer( renderContext, renderContextData.encoder ); + this.device.queue.submit( [ renderContextData.encoder.finish() ] ); + // if ( renderContext.textures !== null ) { @@ -82020,7 +84999,7 @@ var<${access}> ${name} : ${structName};`; const buffer = currentOcclusionQueryBuffer.getMappedRange(); const results = new BigUint64Array( buffer ); - for ( let i = 0; i < currentOcclusionQueryObjects.length; i++ ) { + for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) { if ( results[ i ] !== 0n ) { @@ -82041,7 +85020,7 @@ var<${access}> ${name} : ${structName};`; updateViewport( renderContext ) { const { currentPass } = this.get( renderContext ); - let { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; + const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth ); @@ -82052,7 +85031,7 @@ var<${access}> ${name} : ${structName};`; const device = this.device; const renderer = this.renderer; - const colorAttachments = []; + let colorAttachments = []; let depthStencilAttachment; let clearValue; @@ -82073,39 +85052,23 @@ var<${access}> ${name} : ${structName};`; supportsDepth = renderer.depth; supportsStencil = renderer.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; + const descriptor = this._getDefaultRenderPassDescriptor(); if ( color ) { - const antialias = this.parameters.antialias; - - const colorAttachment = {}; + colorAttachments = descriptor.colorAttachments; - if ( antialias === true ) { - - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - - } else { - - colorAttachment.view = this.context.getCurrentTexture().createView(); - - } + const colorAttachment = colorAttachments[ 0 ]; colorAttachment.clearValue = clearValue; colorAttachment.loadOp = GPULoadOp.Clear; colorAttachment.storeOp = GPUStoreOp.Store; - colorAttachments.push( colorAttachment ); - } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { - depthStencilAttachment = { - view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() - }; + depthStencilAttachment = descriptor.depthStencilAttachment; } @@ -82114,9 +85077,6 @@ var<${access}> ${name} : ${structName};`; supportsDepth = renderTargetData.depth; supportsStencil = renderTargetData.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; - if ( color ) { for ( const texture of renderTargetData.textures ) { @@ -82150,7 +85110,7 @@ var<${access}> ${name} : ${structName};`; } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { const depthTextureData = this.get( renderTargetData.depthTexture ); @@ -82164,7 +85124,7 @@ var<${access}> ${name} : ${structName};`; // - if ( depthStencilAttachment !== undefined ) { + if ( supportsDepth ) { if ( depth ) { @@ -82179,7 +85139,11 @@ var<${access}> ${name} : ${structName};`; } - // + } + + // + + if ( supportsStencil ) { if ( stencil ) { @@ -82216,8 +85180,14 @@ var<${access}> ${name} : ${structName};`; const groupGPU = this.get( computeGroup ); - groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( {} ); - groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass(); + + const descriptor = {}; + + this.initTimestampQuery( computeGroup, descriptor ); + + groupGPU.cmdEncoderGPU = this.device.createCommandEncoder(); + + groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor ); } @@ -82244,6 +85214,9 @@ var<${access}> ${name} : ${structName};`; const groupData = this.get( computeGroup ); groupData.passEncoderGPU.end(); + + this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU ); + this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] ); } @@ -82320,7 +85293,7 @@ var<${access}> ${name} : ${structName};`; // occlusion queries - handle multiple consecutive draw calls for an object - if ( contextData.occlusionQuerySet !== undefined ) { + if ( contextData.occlusionQuerySet !== undefined ) { const lastObject = contextData.lastOcclusionObject; @@ -82404,7 +85377,8 @@ var<${access}> ${name} : ${structName};`; data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage || data.sampleCount !== sampleCount || data.colorSpace !== colorSpace || data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat || - data.primitiveTopology !== primitiveTopology + data.primitiveTopology !== primitiveTopology || + data.clippingContextVersion !== renderObject.clippingContextVersion ) { data.material = material; data.materialVersion = material.version; @@ -82422,6 +85396,7 @@ var<${access}> ${name} : ${structName};`; data.colorFormat = colorFormat; data.depthStencilFormat = depthStencilFormat; data.primitiveTopology = primitiveTopology; + data.clippingContextVersion = renderObject.clippingContextVersion; needsUpdate = true; @@ -82450,7 +85425,8 @@ var<${access}> ${name} : ${structName};`; material.side, utils.getSampleCount( renderContext ), utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ), - utils.getPrimitiveTopology( object, material ) + utils.getPrimitiveTopology( object, material ), + renderObject.clippingContextVersion ].join(); } @@ -82505,6 +85481,87 @@ var<${access}> ${name} : ${structName};`; } + + initTimestampQuery( renderContext, descriptor ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + if ( ! renderContextData.timeStampQuerySet ) { + + // Create a GPUQuerySet which holds 2 timestamp query results: one for the + // beginning and one for the end of compute pass execution. + const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } ); + + const timestampWrites = { + querySet: timeStampQuerySet, + beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins. + endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends. + }; + Object.assign( descriptor, { + timestampWrites, + } ); + renderContextData.timeStampQuerySet = timeStampQuerySet; + + } + + } + + // timestamp utils + + prepareTimestampBuffer( renderContext, encoder ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + const size = 2 * BigInt64Array.BYTES_PER_ELEMENT; + const resolveBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC, + } ); + + const resultBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + } ); + + encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 ); + encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size ); + + renderContextData.currentTimestampQueryBuffer = resultBuffer; + + } + + async resolveTimestampAsync( renderContext, type = 'render' ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + // handle timestamp query results + + const { currentTimestampQueryBuffer } = renderContextData; + + if ( currentTimestampQueryBuffer ) { + + renderContextData.currentTimestampQueryBuffer = null; + + await currentTimestampQueryBuffer.mapAsync( GPUMapMode.READ ); + + const times = new BigUint64Array( currentTimestampQueryBuffer.getMappedRange() ); + + const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000; + // console.log( `Compute ${type} duration: ${Number( times[ 1 ] - times[ 0 ] ) / 1000000}ms` ); + this.renderer.info.updateTimestamp( type, duration ); + + currentTimestampQueryBuffer.unmap(); + + } + + } + // node builder createNodeBuilder( object, renderer, scene = null ) { @@ -82534,9 +85591,9 @@ var<${access}> ${name} : ${structName};`; // pipelines - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { - this.pipelineUtils.createRenderPipeline( renderObject ); + this.pipelineUtils.createRenderPipeline( renderObject, promises ); } @@ -82603,7 +85660,8 @@ var<${access}> ${name} : ${structName};`; updateSize() { this.colorBuffer = this.textureUtils.getColorBuffer(); - + this.defaultRenderPassdescriptor = null; + } // utils public @@ -82614,9 +85672,9 @@ var<${access}> ${name} : ${structName};`; } - hasFeature( name ) { + async hasFeatureAsync( name ) { - const adapter = this.adapter || _staticAdapter; + const adapter = this.adapter || await WebGPU.getStaticAdapter(); // @@ -82624,6 +85682,18 @@ var<${access}> ${name} : ${structName};`; } + hasFeature( name ) { + + if ( ! this.adapter ) { + + return false; + + } + + return this.adapter.features.has( name ); + + } + copyFramebufferToTexture( texture, renderContext ) { const renderContextData = this.get( renderContext ); @@ -82632,18 +85702,40 @@ var<${access}> ${name} : ${structName};`; let sourceGPU = null; - if ( texture.isFramebufferTexture ) { + if ( renderContext.renderTarget ) { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.get( renderContext.depthTexture ).texture; + + } else { + + sourceGPU = this.get( renderContext.textures[ 0 ] ).texture; + + } + + } else { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); - sourceGPU = this.context.getCurrentTexture(); + } else { - } else if ( texture.isDepthTexture ) { + sourceGPU = this.context.getCurrentTexture(); - sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); + } } const destinationGPU = this.get( texture ).texture; + if ( sourceGPU.format !== destinationGPU.format ) { + + return; + + } + renderContextData.currentPass.end(); encoder.copyTextureToTexture( @@ -82693,7 +85785,11 @@ var<${access}> ${name} : ${structName};`; let BackendClass; - if ( WebGPU.isAvailable() ) { + if ( parameters.forceWebGL ) { + + BackendClass = WebGLBackend; + + } else if ( WebGPU.isAvailable() ) { BackendClass = WebGPUBackend; @@ -82759,6 +85855,7 @@ var<${access}> ${name} : ${structName};`; exports.AmbientLight = AmbientLight; exports.AmbientLightNode = AmbientLightNode; exports.AnalyticLightNode = AnalyticLightNode; + exports.AnamorphicNode = AnamorphicNode; exports.AnimationAction = AnimationAction; exports.AnimationClip = AnimationClip; exports.AnimationLoader = AnimationLoader; @@ -82768,7 +85865,6 @@ var<${access}> ${name} : ${structName};`; exports.ArcCurve = ArcCurve; exports.ArrayCamera = ArrayCamera; exports.ArrayElementNode = ArrayElementNode; - exports.ArrayUniformNode = ArrayUniformNode; exports.ArrowHelper = ArrowHelper; exports.AssignNode = AssignNode; exports.AttachedBindMode = AttachedBindMode; @@ -82794,6 +85890,7 @@ var<${access}> ${name} : ${structName};`; exports.Box3Helper = Box3Helper; exports.BoxGeometry = BoxGeometry; exports.BoxHelper = BoxHelper; + exports.Break = Break; exports.BufferAttribute = BufferAttribute; exports.BufferAttributeNode = BufferAttributeNode; exports.BufferGeometry = BufferGeometry; @@ -82832,6 +85929,7 @@ var<${access}> ${name} : ${structName};`; exports.ConstantAlphaFactor = ConstantAlphaFactor; exports.ConstantColorFactor = ConstantColorFactor; exports.ContextNode = ContextNode; + exports.Continue = Continue; exports.ConvertNode = ConvertNode; exports.CubeCamera = CubeCamera; exports.CubeReflectionMapping = CubeReflectionMapping; @@ -82898,7 +85996,6 @@ var<${access}> ${name} : ${structName};`; exports.FileLoader = FileLoader; exports.Float16BufferAttribute = Float16BufferAttribute; exports.Float32BufferAttribute = Float32BufferAttribute; - exports.Float64BufferAttribute = Float64BufferAttribute; exports.FloatType = FloatType; exports.Fog = Fog; exports.FogExp2 = FogExp2; @@ -82988,7 +86085,6 @@ var<${access}> ${name} : ${structName};`; exports.LineLoop = LineLoop; exports.LineSegments = LineSegments; exports.LinearDisplayP3ColorSpace = LinearDisplayP3ColorSpace; - exports.LinearEncoding = LinearEncoding; exports.LinearFilter = LinearFilter; exports.LinearInterpolant = LinearInterpolant; exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; @@ -83050,6 +86146,7 @@ var<${access}> ${name} : ${structName};`; exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter; exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter; + exports.NeutralToneMapping = NeutralToneMapping; exports.NeverCompare = NeverCompare; exports.NeverDepth = NeverDepth; exports.NeverStencilFunc = NeverStencilFunc; @@ -83102,6 +86199,8 @@ var<${access}> ${name} : ${structName};`; exports.P3Primaries = P3Primaries; exports.PCFShadowMap = PCFShadowMap; exports.PCFSoftShadowMap = PCFSoftShadowMap; + exports.PI = PI; + exports.PI2 = PI2; exports.PMREMGenerator = PMREMGenerator; exports.PackingNode = PackingNode; exports.ParameterNode = ParameterNode; @@ -83179,6 +86278,7 @@ var<${access}> ${name} : ${structName};`; exports.RedIntegerFormat = RedIntegerFormat; exports.ReferenceNode = ReferenceNode; exports.ReflectVectorNode = ReflectVectorNode; + exports.ReflectorNode = ReflectorNode; exports.ReinhardToneMapping = ReinhardToneMapping; exports.RemapNode = RemapNode; exports.RenderTarget = RenderTarget; @@ -83186,6 +86286,7 @@ var<${access}> ${name} : ${structName};`; exports.ReplaceStencilOp = ReplaceStencilOp; exports.ReverseSubtractEquation = ReverseSubtractEquation; exports.RingGeometry = RingGeometry; + exports.RotateNode = RotateNode; exports.RotateUVNode = RotateUVNode; exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format; exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format; @@ -83234,6 +86335,7 @@ var<${access}> ${name} : ${structName};`; exports.StaticDrawUsage = StaticDrawUsage; exports.StaticReadUsage = StaticReadUsage; exports.StereoCamera = StereoCamera; + exports.StorageArrayElementNode = StorageArrayElementNode; exports.StorageBufferNode = StorageBufferNode; exports.StreamCopyUsage = StreamCopyUsage; exports.StreamDrawUsage = StreamDrawUsage; @@ -83273,6 +86375,7 @@ var<${access}> ${name} : ${structName};`; exports.UniformNode = UniformNode; exports.UniformsGroup = UniformsGroup$1; exports.UniformsLib = UniformsLib; + exports.UniformsNode = UniformsNode; exports.UniformsUtils = UniformsUtils; exports.UnsignedByteType = UnsignedByteType; exports.UnsignedInt248Type = UnsignedInt248Type; @@ -83324,7 +86427,10 @@ var<${access}> ${name} : ${structName};`; exports.addNodeElement = addNodeElement; exports.addNodeMaterial = addNodeMaterial; exports.afterImage = afterImage; + exports.all = all; + exports.anamorphic = anamorphic; exports.and = and; + exports.any = any; exports.append = append; exports.arrayBuffer = arrayBuffer; exports.asin = asin; @@ -83335,6 +86441,7 @@ var<${access}> ${name} : ${structName};`; exports.backgroundBlurriness = backgroundBlurriness; exports.backgroundIntensity = backgroundIntensity; exports.bitAnd = bitAnd; + exports.bitNot = bitNot; exports.bitOr = bitOr; exports.bitXor = bitXor; exports.bitangentGeometry = bitangentGeometry; @@ -83342,6 +86449,7 @@ var<${access}> ${name} : ${structName};`; exports.bitangentView = bitangentView; exports.bitangentWorld = bitangentWorld; exports.bitcast = bitcast; + exports.bmat2 = bmat2; exports.bmat3 = bmat3; exports.bmat4 = bmat4; exports.bool = bool; @@ -83361,6 +86469,7 @@ var<${access}> ${name} : ${structName};`; exports.cameraNormalMatrix = cameraNormalMatrix; exports.cameraPosition = cameraPosition; exports.cameraProjectionMatrix = cameraProjectionMatrix; + exports.cameraProjectionMatrixInverse = cameraProjectionMatrixInverse; exports.cameraViewMatrix = cameraViewMatrix; exports.cameraWorldMatrix = cameraWorldMatrix; exports.cbrt = cbrt; @@ -83405,6 +86514,7 @@ var<${access}> ${name} : ${structName};`; exports.dynamicBufferAttribute = dynamicBufferAttribute; exports.element = element; exports.equal = equal; + exports.equals = equals; exports.equirectUV = equirectUV; exports.exp = exp; exports.exp2 = exp2; @@ -83419,6 +86529,7 @@ var<${access}> ${name} : ${structName};`; exports.frameId = frameId; exports.frontFacing = frontFacing; exports.fwidth = fwidth; + exports.gain = gain; exports.gapSize = gapSize; exports.gaussianBlur = gaussianBlur; exports.getConstNodeType = getConstNodeType; @@ -83433,6 +86544,7 @@ var<${access}> ${name} : ${structName};`; exports.greaterThanEqual = greaterThanEqual; exports.hash = hash; exports.hue = hue; + exports.imat2 = imat2; exports.imat3 = imat3; exports.imat4 = imat4; exports.instance = instance; @@ -83450,12 +86562,13 @@ var<${access}> ${name} : ${structName};`; exports.js = js; exports.label = label; exports.length = length; + exports.lengthSq = lengthSq; exports.lessThan = lessThan; exports.lessThanEqual = lessThanEqual; - exports.lightNodes = lightNodes; exports.lightTargetDirection = lightTargetDirection; exports.lightingContext = lightingContext; exports.lights = lights; + exports.lightsNode = lightsNode; exports.linearToColorSpace = linearToColorSpace; exports.linearTosRGB = linearTosRGB; exports.log = log; @@ -83463,6 +86576,7 @@ var<${access}> ${name} : ${structName};`; exports.loop = loop; exports.lumaCoeffs = lumaCoeffs; exports.luminance = luminance; + exports.mat2 = mat2; exports.mat3 = mat3; exports.mat4 = mat4; exports.matcapUV = matcapUV; @@ -83507,7 +86621,7 @@ var<${access}> ${name} : ${structName};`; exports.modelViewPosition = modelViewPosition; exports.modelViewProjection = modelViewProjection; exports.modelWorldMatrix = modelWorldMatrix; - exports.morph = morph; + exports.morphReference = morphReference; exports.mul = mul; exports.mx_aastep = mx_aastep; exports.mx_cell_noise_float = mx_cell_noise_float; @@ -83543,6 +86657,7 @@ var<${access}> ${name} : ${structName};`; exports.normalView = normalView; exports.normalWorld = normalWorld; exports.normalize = normalize; + exports.not = not; exports.objectDirection = objectDirection; exports.objectGroup = objectGroup; exports.objectNormalMatrix = objectNormalMatrix; @@ -83562,8 +86677,12 @@ var<${access}> ${name} : ${structName};`; exports.outputStruct = outputStruct; exports.overlay = overlay; exports.overloadingFn = overloadingFn; + exports.parabola = parabola; + exports.parallaxDirection = parallaxDirection; + exports.parallaxUV = parallaxUV; exports.parameter = parameter; exports.pass = pass; + exports.pcurve = pcurve; exports.perspectiveDepthToViewZ = perspectiveDepthToViewZ; exports.pointUV = pointUV; exports.pointWidth = pointWidth; @@ -83584,18 +86703,19 @@ var<${access}> ${name} : ${structName};`; exports.rangeFog = rangeFog; exports.reciprocal = reciprocal; exports.reference = reference; - exports.referenceIndex = referenceIndex; + exports.referenceBuffer = referenceBuffer; exports.reflect = reflect; exports.reflectVector = reflectVector; + exports.reflector = reflector; exports.refract = refract; exports.remainder = remainder; exports.remap = remap; exports.remapClamp = remapClamp; exports.renderGroup = renderGroup; + exports.rotate = rotate; exports.rotateUV = rotateUV; exports.roughness = roughness; exports.round = round; - exports.sRGBEncoding = sRGBEncoding; exports.sRGBToLinear = sRGBToLinear; exports.sampler = sampler; exports.saturate = saturate; @@ -83613,6 +86733,7 @@ var<${access}> ${name} : ${structName};`; exports.shininess = shininess; exports.sign = sign; exports.sin = sin; + exports.sinc = sinc; exports.skinning = skinning; exports.smoothstep = smoothstep; exports.specularColor = specularColor; @@ -83623,6 +86744,7 @@ var<${access}> ${name} : ${structName};`; exports.stack = stack; exports.step = step; exports.storage = storage; + exports.storageObject = storageObject; exports.string = string; exports.sub = sub; exports.tan = tan; @@ -83635,6 +86757,7 @@ var<${access}> ${name} : ${structName};`; exports.textureBicubic = textureBicubic; exports.textureLoad = textureLoad; exports.textureStore = textureStore; + exports.threshold = threshold; exports.timerDelta = timerDelta; exports.timerGlobal = timerGlobal; exports.timerLocal = timerLocal; @@ -83647,15 +86770,18 @@ var<${access}> ${name} : ${structName};`; exports.transformedNormalWorld = transformedNormalWorld; exports.transformedTangentView = transformedTangentView; exports.transformedTangentWorld = transformedTangentWorld; + exports.triNoise3D = triNoise3D; exports.triplanarTexture = triplanarTexture; exports.triplanarTextures = triplanarTextures; exports.trunc = trunc; exports.tslFn = tslFn; exports.uint = uint; + exports.umat2 = umat2; exports.umat3 = umat3; exports.umat4 = umat4; exports.uniform = uniform; exports.uniformGroup = uniformGroup; + exports.uniforms = uniforms; exports.userData = userData; exports.uv = uv; exports.uvec2 = uvec2; diff --git a/build/three-webgpu.module.js b/build/three-webgpu.module.js index f32bef0..30b06f2 100644 --- a/build/three-webgpu.module.js +++ b/build/three-webgpu.module.js @@ -3,7 +3,7 @@ * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ -const REVISION = '161dev'; +const REVISION = '162'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; @@ -62,6 +62,7 @@ const CineonToneMapping = 3; const ACESFilmicToneMapping = 4; const CustomToneMapping = 5; const AgXToneMapping = 6; +const NeutralToneMapping = 7; const AttachedBindMode = 'attached'; const DetachedBindMode = 'detached'; @@ -153,10 +154,6 @@ const AdditiveAnimationBlendMode = 2501; const TrianglesDrawMode = 0; const TriangleStripDrawMode = 1; const TriangleFanDrawMode = 2; -/** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */ -const LinearEncoding = 3000; -/** @deprecated Use SRGBColorSpace in three.js r152+. */ -const sRGBEncoding = 3001; const BasicDepthPacking = 3200; const RGBADepthPacking = 3201; const TangentSpaceNormalMap = 0; @@ -1838,6 +1835,7 @@ class Source { this.uuid = generateUUID(); this.data = data; + this.dataReady = true; this.version = 0; @@ -1995,17 +1993,7 @@ class Texture extends EventDispatcher { this.flipY = true; this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - if ( typeof colorSpace === 'string' ) { - - this.colorSpace = colorSpace; - - } else { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - + this.colorSpace = colorSpace; this.userData = {}; @@ -2244,20 +2232,6 @@ class Texture extends EventDispatcher { } - get encoding() { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - - set encoding( encoding ) { // @deprecated, r152 - - warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' ); - this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - } Texture.DEFAULT_IMAGE = null; @@ -2931,14 +2905,6 @@ class RenderTarget extends EventDispatcher { const image = { width: width, height: height, depth: 1 }; - if ( options.encoding !== undefined ) { - - // @deprecated, r152 - warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' ); - options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - options = Object.assign( { generateMipmaps: false, internalFormat: null, @@ -2946,15 +2912,25 @@ class RenderTarget extends EventDispatcher { depthBuffer: true, stencilBuffer: false, depthTexture: null, - samples: 0 + samples: 0, + count: 1 }, options ); - this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); - this.texture.isRenderTargetTexture = true; + const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); + + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + + this.textures = []; - this.texture.flipY = false; - this.texture.generateMipmaps = options.generateMipmaps; - this.texture.internalFormat = options.internalFormat; + const count = options.count; + for ( let i = 0; i < count; i ++ ) { + + this.textures[ i ] = texture.clone(); + this.textures[ i ].isRenderTargetTexture = true; + + } this.depthBuffer = options.depthBuffer; this.stencilBuffer = options.stencilBuffer; @@ -2965,6 +2941,18 @@ class RenderTarget extends EventDispatcher { } + get texture() { + + return this.textures[ 0 ]; + + } + + set texture( value ) { + + this.textures[ 0 ] = value; + + } + setSize( width, height, depth = 1 ) { if ( this.width !== width || this.height !== height || this.depth !== depth ) { @@ -2973,9 +2961,13 @@ class RenderTarget extends EventDispatcher { this.height = height; this.depth = depth; - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = depth; + for ( let i = 0, il = this.textures.length; i < il; i ++ ) { + + this.textures[ i ].image.width = width; + this.textures[ i ].image.height = height; + this.textures[ i ].image.depth = depth; + + } this.dispose(); @@ -3003,8 +2995,14 @@ class RenderTarget extends EventDispatcher { this.viewport.copy( source.viewport ); - this.texture = source.texture.clone(); - this.texture.isRenderTargetTexture = true; + this.textures.length = 0; + + for ( let i = 0, il = source.textures.length; i < il; i ++ ) { + + this.textures[ i ] = source.textures[ i ].clone(); + this.textures[ i ].isRenderTargetTexture = true; + + } // ensure image object is not shared, see #20328 @@ -3132,85 +3130,6 @@ class WebGL3DRenderTarget extends WebGLRenderTarget { } -class WebGLMultipleRenderTargets extends WebGLRenderTarget { - - constructor( width = 1, height = 1, count = 1, options = {} ) { - - super( width, height, options ); - - this.isWebGLMultipleRenderTargets = true; - - const texture = this.texture; - - this.texture = []; - - for ( let i = 0; i < count; i ++ ) { - - this.texture[ i ] = texture.clone(); - this.texture[ i ].isRenderTargetTexture = true; - - } - - } - - setSize( width, height, depth = 1 ) { - - if ( this.width !== width || this.height !== height || this.depth !== depth ) { - - this.width = width; - this.height = height; - this.depth = depth; - - for ( let i = 0, il = this.texture.length; i < il; i ++ ) { - - this.texture[ i ].image.width = width; - this.texture[ i ].image.height = height; - this.texture[ i ].image.depth = depth; - - } - - this.dispose(); - - } - - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); - - } - - copy( source ) { - - this.dispose(); - - this.width = source.width; - this.height = source.height; - this.depth = source.depth; - - this.scissor.copy( source.scissor ); - this.scissorTest = source.scissorTest; - - this.viewport.copy( source.viewport ); - - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - - if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - - this.texture.length = 0; - - for ( let i = 0, il = source.texture.length; i < il; i ++ ) { - - this.texture[ i ] = source.texture[ i ].clone(); - this.texture[ i ].isRenderTargetTexture = true; - - } - - return this; - - } - -} - class Quaternion { constructor( x = 0, y = 0, z = 0, w = 1 ) { @@ -3802,23 +3721,24 @@ class Quaternion { random() { - // Derived from http://planning.cs.uiuc.edu/node198.html - // Note, this source uses w, x, y, z ordering, - // so we swap the order below. + // sets this quaternion to a uniform random unit quaternnion - const u1 = Math.random(); - const sqrt1u1 = Math.sqrt( 1 - u1 ); - const sqrtu1 = Math.sqrt( u1 ); + // Ken Shoemake + // Uniform random rotations + // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992. - const u2 = 2 * Math.PI * Math.random(); + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); - const u3 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt( 1 - x0 ); + const r2 = Math.sqrt( x0 ); return this.set( - sqrt1u1 * Math.cos( u2 ), - sqrtu1 * Math.sin( u3 ), - sqrtu1 * Math.cos( u3 ), - sqrt1u1 * Math.sin( u2 ), + r1 * Math.sin( theta1 ), + r1 * Math.cos( theta1 ), + r2 * Math.sin( theta2 ), + r2 * Math.cos( theta2 ), ); } @@ -4586,15 +4506,15 @@ class Vector3 { randomDirection() { - // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + // https://mathworld.wolfram.com/SpherePointPicking.html - const u = ( Math.random() - 0.5 ) * 2; - const t = Math.random() * Math.PI * 2; - const f = Math.sqrt( 1 - u ** 2 ); + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt( 1 - u * u ); - this.x = f * Math.cos( t ); - this.y = f * Math.sin( t ); - this.z = u; + this.x = c * Math.cos( theta ); + this.y = u; + this.z = c * Math.sin( theta ); return this; @@ -6620,25 +6540,25 @@ class Matrix4 { position.z = te[ 14 ]; // scale the rotation part - _m1$2.copy( this ); + _m1$4.copy( this ); const invSX = 1 / sx; const invSY = 1 / sy; const invSZ = 1 / sz; - _m1$2.elements[ 0 ] *= invSX; - _m1$2.elements[ 1 ] *= invSX; - _m1$2.elements[ 2 ] *= invSX; + _m1$4.elements[ 0 ] *= invSX; + _m1$4.elements[ 1 ] *= invSX; + _m1$4.elements[ 2 ] *= invSX; - _m1$2.elements[ 4 ] *= invSY; - _m1$2.elements[ 5 ] *= invSY; - _m1$2.elements[ 6 ] *= invSY; + _m1$4.elements[ 4 ] *= invSY; + _m1$4.elements[ 5 ] *= invSY; + _m1$4.elements[ 6 ] *= invSY; - _m1$2.elements[ 8 ] *= invSZ; - _m1$2.elements[ 9 ] *= invSZ; - _m1$2.elements[ 10 ] *= invSZ; + _m1$4.elements[ 8 ] *= invSZ; + _m1$4.elements[ 9 ] *= invSZ; + _m1$4.elements[ 10 ] *= invSZ; - quaternion.setFromRotationMatrix( _m1$2 ); + quaternion.setFromRotationMatrix( _m1$4 ); scale.x = sx; scale.y = sy; @@ -6779,14 +6699,14 @@ class Matrix4 { } const _v1$5 = /*@__PURE__*/ new Vector3(); -const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _m1$4 = /*@__PURE__*/ new Matrix4(); const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); const _x = /*@__PURE__*/ new Vector3(); const _y = /*@__PURE__*/ new Vector3(); const _z = /*@__PURE__*/ new Vector3(); -const _matrix$1 = /*@__PURE__*/ new Matrix4(); +const _matrix$2 = /*@__PURE__*/ new Matrix4(); const _quaternion$3 = /*@__PURE__*/ new Quaternion(); class Euler { @@ -7021,9 +6941,9 @@ class Euler { setFromQuaternion( q, order, update ) { - _matrix$1.makeRotationFromQuaternion( q ); + _matrix$2.makeRotationFromQuaternion( q ); - return this.setFromRotationMatrix( _matrix$1, order, update ); + return this.setFromRotationMatrix( _matrix$2, order, update ); } @@ -7158,8 +7078,8 @@ let _object3DId = 0; const _v1$4 = /*@__PURE__*/ new Vector3(); const _q1 = /*@__PURE__*/ new Quaternion(); -const _m1$1 = /*@__PURE__*/ new Matrix4(); -const _target = /*@__PURE__*/ new Vector3(); +const _m1$3 = /*@__PURE__*/ new Matrix4(); +const _target$1 = /*@__PURE__*/ new Vector3(); const _position$3 = /*@__PURE__*/ new Vector3(); const _scale$2 = /*@__PURE__*/ new Vector3(); @@ -7172,6 +7092,9 @@ const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); const _addedEvent = { type: 'added' }; const _removedEvent = { type: 'removed' }; +const _childaddedEvent = { type: 'childadded', child: null }; +const _childremovedEvent = { type: 'childremoved', child: null }; + class Object3D extends EventDispatcher { constructor() { @@ -7408,7 +7331,7 @@ class Object3D extends EventDispatcher { this.updateWorldMatrix( true, false ); - return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() ); } @@ -7418,11 +7341,11 @@ class Object3D extends EventDispatcher { if ( x.isVector3 ) { - _target.copy( x ); + _target$1.copy( x ); } else { - _target.set( x, y, z ); + _target$1.set( x, y, z ); } @@ -7434,20 +7357,20 @@ class Object3D extends EventDispatcher { if ( this.isCamera || this.isLight ) { - _m1$1.lookAt( _position$3, _target, this.up ); + _m1$3.lookAt( _position$3, _target$1, this.up ); } else { - _m1$1.lookAt( _target, _position$3, this.up ); + _m1$3.lookAt( _target$1, _position$3, this.up ); } - this.quaternion.setFromRotationMatrix( _m1$1 ); + this.quaternion.setFromRotationMatrix( _m1$3 ); if ( parent ) { - _m1$1.extractRotation( parent.matrixWorld ); - _q1.setFromRotationMatrix( _m1$1 ); + _m1$3.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$3 ); this.quaternion.premultiply( _q1.invert() ); } @@ -7488,6 +7411,10 @@ class Object3D extends EventDispatcher { object.dispatchEvent( _addedEvent ); + _childaddedEvent.child = object; + this.dispatchEvent( _childaddedEvent ); + _childaddedEvent.child = null; + } else { console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); @@ -7521,6 +7448,10 @@ class Object3D extends EventDispatcher { object.dispatchEvent( _removedEvent ); + _childremovedEvent.child = object; + this.dispatchEvent( _childremovedEvent ); + _childremovedEvent.child = null; + } return this; @@ -7555,17 +7486,17 @@ class Object3D extends EventDispatcher { this.updateWorldMatrix( true, false ); - _m1$1.copy( this.matrixWorld ).invert(); + _m1$3.copy( this.matrixWorld ).invert(); if ( object.parent !== null ) { object.parent.updateWorldMatrix( true, false ); - _m1$1.multiply( object.parent.matrixWorld ); + _m1$3.multiply( object.parent.matrixWorld ); } - object.applyMatrix4( _m1$1 ); + object.applyMatrix4( _m1$3 ); this.add( object ); @@ -8155,7 +8086,7 @@ Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; const _v0$1 = /*@__PURE__*/ new Vector3(); const _v1$3 = /*@__PURE__*/ new Vector3(); const _v2$2 = /*@__PURE__*/ new Vector3(); -const _v3$1 = /*@__PURE__*/ new Vector3(); +const _v3$2 = /*@__PURE__*/ new Vector3(); const _vab = /*@__PURE__*/ new Vector3(); const _vac = /*@__PURE__*/ new Vector3(); @@ -8227,19 +8158,19 @@ class Triangle { static containsPoint( point, a, b, c ) { // if the triangle is degenerate then we can't contain a point - if ( this.getBarycoord( point, a, b, c, _v3$1 ) === null ) { + if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) { return false; } - return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); + return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 ); } static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) { - if ( this.getBarycoord( point, p1, p2, p3, _v3$1 ) === null ) { + if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) { target.x = 0; target.y = 0; @@ -8250,9 +8181,9 @@ class Triangle { } target.setScalar( 0 ); - target.addScaledVector( v1, _v3$1.x ); - target.addScaledVector( v2, _v3$1.y ); - target.addScaledVector( v3, _v3$1.z ); + target.addScaledVector( v1, _v3$2.x ); + target.addScaledVector( v2, _v3$2.y ); + target.addScaledVector( v3, _v3$2.z ); return target; @@ -9265,7 +9196,7 @@ class Material extends EventDispatcher { if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); - if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; @@ -9375,6 +9306,7 @@ class Material extends EventDispatcher { } + if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray(); if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; @@ -9619,6 +9551,7 @@ class MeshBasicMaterial extends Material { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -9653,6 +9586,7 @@ class MeshBasicMaterial extends Material { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -9880,7 +9814,7 @@ class BufferAttribute { get updateRange() { - console.warn( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 + warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 return this._updateRange; } @@ -10457,19 +10391,9 @@ class Float32BufferAttribute extends BufferAttribute { } -class Float64BufferAttribute extends BufferAttribute { - - constructor( array, itemSize, normalized ) { - - super( new Float64Array( array ), itemSize, normalized ); - - } - -} - -let _id$2 = 0; +let _id$2$1 = 0; -const _m1 = /*@__PURE__*/ new Matrix4(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); const _obj = /*@__PURE__*/ new Object3D(); const _offset = /*@__PURE__*/ new Vector3(); const _box$2 = /*@__PURE__*/ new Box3(); @@ -10484,7 +10408,7 @@ class BufferGeometry extends EventDispatcher { this.isBufferGeometry = true; - Object.defineProperty( this, 'id', { value: _id$2 ++ } ); + Object.defineProperty( this, 'id', { value: _id$2$1 ++ } ); this.uuid = generateUUID(); @@ -10635,9 +10559,9 @@ class BufferGeometry extends EventDispatcher { applyQuaternion( q ) { - _m1.makeRotationFromQuaternion( q ); + _m1$2.makeRotationFromQuaternion( q ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10647,9 +10571,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world x-axis - _m1.makeRotationX( angle ); + _m1$2.makeRotationX( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10659,9 +10583,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world y-axis - _m1.makeRotationY( angle ); + _m1$2.makeRotationY( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10671,9 +10595,9 @@ class BufferGeometry extends EventDispatcher { // rotate geometry around world z-axis - _m1.makeRotationZ( angle ); + _m1$2.makeRotationZ( angle ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10683,9 +10607,9 @@ class BufferGeometry extends EventDispatcher { // translate geometry - _m1.makeTranslation( x, y, z ); + _m1$2.makeTranslation( x, y, z ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10695,9 +10619,9 @@ class BufferGeometry extends EventDispatcher { // scale geometry - _m1.makeScale( x, y, z ); + _m1$2.makeScale( x, y, z ); - this.applyMatrix4( _m1 ); + this.applyMatrix4( _m1$2 ); return this; @@ -10757,7 +10681,7 @@ class BufferGeometry extends EventDispatcher { if ( position && position.isGLBufferAttribute ) { - console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this ); this.boundingBox.set( new Vector3( - Infinity, - Infinity, - Infinity ), @@ -10827,7 +10751,7 @@ class BufferGeometry extends EventDispatcher { if ( position && position.isGLBufferAttribute ) { - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this ); this.boundingSphere.set( new Vector3(), Infinity ); @@ -10944,24 +10868,21 @@ class BufferGeometry extends EventDispatcher { } - const indices = index.array; - const positions = attributes.position.array; - const normals = attributes.normal.array; - const uvs = attributes.uv.array; - - const nVertices = positions.length / 3; + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; if ( this.hasAttribute( 'tangent' ) === false ) { - this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) ); } - const tangents = this.getAttribute( 'tangent' ).array; + const tangentAttribute = this.getAttribute( 'tangent' ); const tan1 = [], tan2 = []; - for ( let i = 0; i < nVertices; i ++ ) { + for ( let i = 0; i < positionAttribute.count; i ++ ) { tan1[ i ] = new Vector3(); tan2[ i ] = new Vector3(); @@ -10981,13 +10902,13 @@ class BufferGeometry extends EventDispatcher { function handleTriangle( a, b, c ) { - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + vA.fromBufferAttribute( positionAttribute, a ); + vB.fromBufferAttribute( positionAttribute, b ); + vC.fromBufferAttribute( positionAttribute, c ); - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + uvA.fromBufferAttribute( uvAttribute, a ); + uvB.fromBufferAttribute( uvAttribute, b ); + uvC.fromBufferAttribute( uvAttribute, c ); vB.sub( vA ); vC.sub( vA ); @@ -11020,7 +10941,7 @@ class BufferGeometry extends EventDispatcher { groups = [ { start: 0, - count: indices.length + count: index.count } ]; } @@ -11035,9 +10956,9 @@ class BufferGeometry extends EventDispatcher { for ( let j = start, jl = start + count; j < jl; j += 3 ) { handleTriangle( - indices[ j + 0 ], - indices[ j + 1 ], - indices[ j + 2 ] + index.getX( j + 0 ), + index.getX( j + 1 ), + index.getX( j + 2 ) ); } @@ -11049,7 +10970,7 @@ class BufferGeometry extends EventDispatcher { function handleVertex( v ) { - n.fromArray( normals, v * 3 ); + n.fromBufferAttribute( normalAttribute, v ); n2.copy( n ); const t = tan1[ v ]; @@ -11065,10 +10986,7 @@ class BufferGeometry extends EventDispatcher { const test = tmp2.dot( tan2[ v ] ); const w = ( test < 0.0 ) ? - 1.0 : 1.0; - tangents[ v * 4 ] = tmp.x; - tangents[ v * 4 + 1 ] = tmp.y; - tangents[ v * 4 + 2 ] = tmp.z; - tangents[ v * 4 + 3 ] = w; + tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w ); } @@ -11081,9 +10999,9 @@ class BufferGeometry extends EventDispatcher { for ( let j = start, jl = start + count; j < jl; j += 3 ) { - handleVertex( indices[ j + 0 ] ); - handleVertex( indices[ j + 1 ] ); - handleVertex( indices[ j + 2 ] ); + handleVertex( index.getX( j + 0 ) ); + handleVertex( index.getX( j + 1 ) ); + handleVertex( index.getX( j + 2 ) ); } @@ -11912,7 +11830,6 @@ function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, n _uvC$1.fromBufferAttribute( uv1, c ); intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); - intersection.uv2 = intersection.uv1; // @deprecated, r152 } @@ -12263,7 +12180,8 @@ class ShaderMaterial extends Material { fragDepth: false, // set to use fragment depth values drawBuffers: false, // set to use draw buffers shaderTextureLOD: false, // set to use shader texture LOD - clipCullDistance: false // set to use vertex shader clipping + clipCullDistance: false, // set to use vertex shader clipping + multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID }; // When rendered geometry doesn't include these attributes but the material does, @@ -12475,6 +12393,11 @@ class Camera extends Object3D { } +const _v3$1 = /*@__PURE__*/ new Vector3(); +const _minTarget = /*@__PURE__*/ new Vector2(); +const _maxTarget = /*@__PURE__*/ new Vector2(); + + class PerspectiveCamera extends Camera { constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { @@ -12573,6 +12496,34 @@ class PerspectiveCamera extends Camera { } + /** + * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. + * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle. + */ + getViewBounds( distance, minTarget, maxTarget ) { + + _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + } + + /** + * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. + * Copies the result into the target Vector2, where x is width and y is height. + */ + getViewSize( distance, target ) { + + this.getViewBounds( distance, _minTarget, _maxTarget ); + + return target.subVectors( _maxTarget, _minTarget ); + + } + /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. @@ -12912,14 +12863,6 @@ class WebGLCubeRenderTarget extends WebGLRenderTarget { const image = { width: size, height: size, depth: 1 }; const images = [ image, image, image, image, image, image ]; - if ( options.encoding !== undefined ) { - - // @deprecated, r152 - warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' ); - options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; - - } - this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace ); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) @@ -13565,7 +13508,7 @@ function WebGLAttributes( gl, capabilities ) { function updateBuffer( buffer, attribute, bufferType ) { const array = attribute.array; - const updateRange = attribute._updateRange; // deprecated + const updateRange = attribute._updateRange; // @deprecated, r159 const updateRanges = attribute.updateRanges; gl.bindBuffer( bufferType, buffer ); @@ -13600,7 +13543,7 @@ function WebGLAttributes( gl, capabilities ) { } - // deprecated + // @deprecated, r159 if ( updateRange.count !== - 1 ) { if ( isWebGL2 ) { @@ -13806,7 +13749,7 @@ var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alp var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; -var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif"; var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; @@ -13828,7 +13771,7 @@ var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; -var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif"; var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; @@ -13862,9 +13805,9 @@ var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\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}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}"; -var 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, 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"; +var 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"; -var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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"; +var 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"; var 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"; @@ -13892,7 +13835,7 @@ var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertM var 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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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"; -var 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, 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, 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"; +var 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"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; @@ -13932,11 +13875,13 @@ var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_META var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; +var 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"; + var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\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"; var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; -var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; @@ -13998,7 +13943,7 @@ var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D spe var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; -var 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 OptimizedCineonToneMapping( 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 CustomToneMapping( vec3 color ) { return color; }"; +var 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 OptimizedCineonToneMapping( 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\tfloat startCompression = 0.8 - 0.04;\n\tfloat 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(1, 1, 1), g);\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; var 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.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"; @@ -14018,67 +13963,67 @@ const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\n const vertex$g = "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}"; -const fragment$g = "#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;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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}"; +const fragment$g = "#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}"; const vertex$f = "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}"; const fragment$f = "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}"; -const vertex$e = "#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#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}"; +const vertex$e = "#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}"; -const fragment$e = "#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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#endif\n}"; +const fragment$e = "#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#endif\n}"; -const vertex$d = "#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#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}"; +const vertex$d = "#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}"; -const fragment$d = "#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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}"; +const fragment$d = "#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}"; const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; const fragment$c = "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}"; -const vertex$b = "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}"; +const vertex$b = "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}"; -const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$b = "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}"; -const vertex$a = "#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#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}"; +const vertex$a = "#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}"; -const fragment$a = "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\t#include \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\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}"; +const fragment$a = "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}"; -const vertex$9 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$9 = "#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}"; -const fragment$9 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$9 = "#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}"; -const vertex$8 = "#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\tvViewPosition = - mvPosition.xyz;\n}"; +const vertex$8 = "#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}"; -const fragment$8 = "#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\t#include \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\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}"; +const fragment$8 = "#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}"; -const vertex$7 = "#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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; +const vertex$7 = "#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}"; -const fragment$7 = "#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\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; +const fragment$7 = "#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}"; -const vertex$6 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$6 = "#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}"; -const fragment$6 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$6 = "#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}"; -const vertex$5 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; +const vertex$5 = "#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}"; -const fragment$5 = "#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_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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$5 = "#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_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}"; -const vertex$4 = "#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\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; +const vertex$4 = "#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}"; -const fragment$4 = "#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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$4 = "#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}"; -const vertex$3 = "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\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}"; +const vertex$3 = "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}"; -const fragment$3 = "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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$3 = "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}"; -const vertex$2 = "#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}"; +const vertex$2 = "#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}"; const fragment$2 = "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}"; const vertex$1 = "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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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}"; -const fragment$1 = "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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"; +const fragment$1 = "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}"; const ShaderChunk = { alphahash_fragment: alphahash_fragment, @@ -14148,6 +14093,7 @@ const ShaderChunk = { map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphinstance_vertex: morphinstance_vertex, morphcolor_vertex: morphcolor_vertex, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, @@ -14256,6 +14202,7 @@ const UniformsLib = { envmap: { envMap: { value: null }, + envMapRotation: { value: /*@__PURE__*/ new Matrix3() }, flipEnvMap: { value: - 1 }, reflectivity: { value: 1.0 }, // basic, lambert, phong ior: { value: 1.5 }, // physical @@ -14676,7 +14623,8 @@ const ShaderLib = { envMap: { value: null }, flipEnvMap: { value: - 1 }, backgroundBlurriness: { value: 0 }, - backgroundIntensity: { value: 1 } + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /*@__PURE__*/ new Matrix3() } }, vertexShader: ShaderChunk.backgroundCube_vert, @@ -14800,6 +14748,8 @@ ShaderLib.physical = { }; const _rgb = { r: 0, b: 0, g: 0 }; +const _e1$1 = /*@__PURE__*/ new Euler(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { @@ -14896,10 +14846,24 @@ function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, } + _e1$1.copy( scene.backgroundRotation ); + + // accommodate left-handed frame + _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1; + + if ( background.isCubeTexture && background.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1$1.y *= - 1; + _e1$1.z *= - 1; + + } + boxMesh.material.uniforms.envMap.value = background; boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) ); boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; if ( currentBackground !== background || @@ -16066,7 +16030,7 @@ function WebGLCubeMaps( renderer ) { if ( image && image.height > 0 ) { - const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + const renderTarget = new WebGLCubeRenderTarget( image.height ); renderTarget.fromEquirectangularTexture( renderer, texture ); cubemaps.set( texture, renderTarget ); @@ -16364,6 +16328,7 @@ class PMREMGenerator { * Generates a PMREM from an equirectangular texture, which can be either LDR * or HDR. The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. + * The smallest supported equirectangular image size is 64 x 32. */ fromEquirectangular( equirectangular, renderTarget = null ) { @@ -16375,6 +16340,7 @@ class PMREMGenerator { * Generates a PMREM from an cubemap texture, which can be either LDR * or HDR. The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. + * The smallest supported cube size is 16 x 16. */ fromCubemap( cubemap, renderTarget = null ) { @@ -17882,24 +17848,31 @@ function WebGLMorphtargets( gl, capabilities, textures ) { } // + if ( object.isInstancedMesh === true && object.morphTexture !== null ) { - let morphInfluencesSum = 0; + program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures ); - for ( let i = 0; i < objectInfluences.length; i ++ ) { + } else { - morphInfluencesSum += objectInfluences[ i ]; + let morphInfluencesSum = 0; - } + for ( let i = 0; i < objectInfluences.length; i ++ ) { - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); - program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + } program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); - } else { // When object doesn't have morph target influences defined, we treat it as a 0-length array @@ -19448,6 +19421,10 @@ function getToneMappingFunction( functionName, toneMapping ) { toneMappingName = 'AgX'; break; + case NeutralToneMapping: + toneMappingName = 'Neutral'; + break; + case CustomToneMapping: toneMappingName = 'Custom'; break; @@ -19465,7 +19442,7 @@ function getToneMappingFunction( functionName, toneMapping ) { function generateExtensions( parameters ) { const chunks = [ - ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.alphaToCoverage || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' @@ -19478,7 +19455,8 @@ function generateExtensions( parameters ) { function generateVertexExtensions( parameters ) { const chunks = [ - parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '' + parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '', + parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '', ]; return chunks.filter( filterEmptyLine ).join( '\n' ); @@ -19870,6 +19848,7 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.batching ? '#define USE_BATCHING' : '', parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', @@ -20001,6 +19980,12 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { '#endif', + '#ifdef USE_INSTANCING_MORPH', + + ' uniform sampler2D morphTexture;', + + '#endif', + 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', @@ -20089,6 +20074,7 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', @@ -20290,6 +20276,8 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { console.error( 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Material Name: ' + self.name + '\n' + + 'Material Type: ' + self.type + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors @@ -20426,7 +20414,7 @@ function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { } -let _id$1 = 0; +let _id$1$1 = 0; class WebGLShaderCache { @@ -20540,7 +20528,7 @@ class WebGLShaderStage { constructor( code ) { - this.id = _id$1 ++; + this.id = _id$1$1 ++; this.code = code; this.usedTimes = 0; @@ -20553,6 +20541,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities const _programLayers = new Layers(); const _customShaders = new WebGLShaderCache(); + const _activeChannels = new Set(); const programs = []; const IS_WEBGL2 = capabilities.isWebGL2; @@ -20581,6 +20570,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities function getChannel( value ) { + _activeChannels.add( value ); + if ( value === 0 ) return 'uv'; return `uv${ value }`; @@ -20701,10 +20692,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities const HAS_EXTENSIONS = !! material.extensions; - const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1; - const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2; - const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3; - let toneMapping = NoToneMapping; if ( material.toneMapped ) { @@ -20740,9 +20727,11 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities batching: IS_BATCHEDMESH, instancing: IS_INSTANCEDMESH, instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ), + alphaToCoverage: !! material.alphaToCoverage, map: HAS_MAP, matcap: HAS_MATCAP, @@ -20788,7 +20777,7 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities gradientMap: HAS_GRADIENTMAP, - opaque: material.transparent === false && material.blending === NormalBlending, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, alphaMap: HAS_ALPHAMAP, alphaTest: HAS_ALPHATEST, @@ -20835,9 +20824,6 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ), vertexColors: material.vertexColors, vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, - vertexUv1s: HAS_ATTRIBUTE_UV1, - vertexUv2s: HAS_ATTRIBUTE_UV2, - vertexUv3s: HAS_ATTRIBUTE_UV3, pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ), @@ -20899,7 +20885,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true, extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true, extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true, - extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ), rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ), rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ), @@ -20910,6 +20897,14 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities }; + // the usage of getChannel() determines the active texture channels for this shader + + parameters.vertexUv1s = _activeChannels.has( 1 ); + parameters.vertexUv2s = _activeChannels.has( 2 ); + parameters.vertexUv3s = _activeChannels.has( 3 ); + + _activeChannels.clear(); + return parameters; } @@ -21019,38 +21014,40 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 2 ); if ( parameters.instancingColor ) _programLayers.enable( 3 ); - if ( parameters.matcap ) + if ( parameters.instancingMorph ) _programLayers.enable( 4 ); - if ( parameters.envMap ) + if ( parameters.matcap ) _programLayers.enable( 5 ); - if ( parameters.normalMapObjectSpace ) + if ( parameters.envMap ) _programLayers.enable( 6 ); - if ( parameters.normalMapTangentSpace ) + if ( parameters.normalMapObjectSpace ) _programLayers.enable( 7 ); - if ( parameters.clearcoat ) + if ( parameters.normalMapTangentSpace ) _programLayers.enable( 8 ); - if ( parameters.iridescence ) + if ( parameters.clearcoat ) _programLayers.enable( 9 ); - if ( parameters.alphaTest ) + if ( parameters.iridescence ) _programLayers.enable( 10 ); - if ( parameters.vertexColors ) + if ( parameters.alphaTest ) _programLayers.enable( 11 ); - if ( parameters.vertexAlphas ) + if ( parameters.vertexColors ) _programLayers.enable( 12 ); - if ( parameters.vertexUv1s ) + if ( parameters.vertexAlphas ) _programLayers.enable( 13 ); - if ( parameters.vertexUv2s ) + if ( parameters.vertexUv1s ) _programLayers.enable( 14 ); - if ( parameters.vertexUv3s ) + if ( parameters.vertexUv2s ) _programLayers.enable( 15 ); - if ( parameters.vertexTangents ) + if ( parameters.vertexUv3s ) _programLayers.enable( 16 ); - if ( parameters.anisotropy ) + if ( parameters.vertexTangents ) _programLayers.enable( 17 ); - if ( parameters.alphaHash ) + if ( parameters.anisotropy ) _programLayers.enable( 18 ); - if ( parameters.batching ) + if ( parameters.alphaHash ) _programLayers.enable( 19 ); + if ( parameters.batching ) + _programLayers.enable( 20 ); array.push( _programLayers.mask ); _programLayers.disableAll(); @@ -21095,6 +21092,8 @@ function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities _programLayers.enable( 18 ); if ( parameters.decodeVideoTexture ) _programLayers.enable( 19 ); + if ( parameters.alphaToCoverage ) + _programLayers.enable( 20 ); array.push( _programLayers.mask ); @@ -23153,33 +23152,19 @@ function WebGLState$1( gl, extensions, capabilities ) { } - if ( renderTarget.isWebGLMultipleRenderTargets ) { + const textures = renderTarget.textures; - const textures = renderTarget.texture; - - if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - - for ( let i = 0, il = textures.length; i < il; i ++ ) { - - drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; - - } + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - drawBuffers.length = textures.length; + for ( let i = 0, il = textures.length; i < il; i ++ ) { - needsUpdate = true; + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; } - } else { - - if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { - - drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0; - - needsUpdate = true; + drawBuffers.length = textures.length; - } + needsUpdate = true; } @@ -23201,10 +23186,14 @@ function WebGLState$1( gl, extensions, capabilities ) { gl.drawBuffers( drawBuffers ); - } else { + } else if ( extensions.has( 'WEBGL_draw_buffers' ) === true ) { extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + } else { + + throw new Error( 'THREE.WebGLState: Usage of gl.drawBuffers() require WebGL2 or WEBGL_draw_buffers extension' ); + } } @@ -23991,6 +23980,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + const _imageDimensions = new Vector2(); const _videoTextures = new WeakMap(); let _canvas; @@ -24028,11 +24018,13 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, let scale = 1; + const dimensions = getDimensions( image ); + // handle case if texture exceeds max size - if ( image.width > maxSize || image.height > maxSize ) { + if ( dimensions.width > maxSize || dimensions.height > maxSize ) { - scale = maxSize / Math.max( image.width, image.height ); + scale = maxSize / Math.max( dimensions.width, dimensions.height ); } @@ -24044,12 +24036,13 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) || + ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) { const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; - const width = floor( scale * image.width ); - const height = floor( scale * image.height ); + const width = floor( scale * dimensions.width ); + const height = floor( scale * dimensions.height ); if ( _canvas === undefined ) _canvas = createCanvas( width, height ); @@ -24063,7 +24056,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, width, height ); - console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' ); return canvas; @@ -24071,7 +24064,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( 'data' in image ) { - console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' ); } @@ -24087,7 +24080,9 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, function isPowerOfTwo$1( image ) { - return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + const dimensions = getDimensions( image ); + + return isPowerOfTwo( dimensions.width ) && isPowerOfTwo( dimensions.height ); } @@ -24154,6 +24149,17 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } + if ( glFormat === _gl.RG_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I; + if ( glType === _gl.INT ) internalFormat = _gl.RG32I; + + } + if ( glFormat === _gl.RGBA ) { const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace ); @@ -24301,18 +24307,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, function deallocateRenderTarget( renderTarget ) { - const texture = renderTarget.texture; - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); - - if ( textureProperties.__webglTexture !== undefined ) { - - _gl.deleteTexture( textureProperties.__webglTexture ); - - info.memory.textures --; - - } if ( renderTarget.depthTexture ) { @@ -24367,27 +24362,24 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - for ( let i = 0, il = texture.length; i < il; i ++ ) { - - const attachmentProperties = properties.get( texture[ i ] ); + const textures = renderTarget.textures; - if ( attachmentProperties.__webglTexture ) { + for ( let i = 0, il = textures.length; i < il; i ++ ) { - _gl.deleteTexture( attachmentProperties.__webglTexture ); + const attachmentProperties = properties.get( textures[ i ] ); - info.memory.textures --; + if ( attachmentProperties.__webglTexture ) { - } + _gl.deleteTexture( attachmentProperties.__webglTexture ); - properties.remove( texture[ i ] ); + info.memory.textures --; } + properties.remove( textures[ i ] ); + } - properties.remove( texture ); properties.remove( renderTarget ); } @@ -24607,8 +24599,6 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 @@ -24616,6 +24606,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); properties.get( texture ).__currentAnisotropy = texture.anisotropy; @@ -24749,6 +24740,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format ); const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; const levels = getMipLevels( texture, image, supportsMips ); if ( texture.isDepthTexture ) { @@ -24861,7 +24853,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -24883,7 +24879,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } } else { @@ -24913,7 +24913,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + if ( dataReady ) { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } } else { @@ -24931,7 +24935,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } } else { @@ -24961,7 +24969,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } } else { @@ -24979,7 +24991,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -25003,7 +25019,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } } else { @@ -25021,7 +25041,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } } else { @@ -25066,7 +25090,9 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage && allocateMemory ) { - state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + const dimensions = getDimensions( mipmaps[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); } @@ -25076,7 +25102,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } } else { @@ -25094,11 +25124,17 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( allocateMemory ) { - state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + const dimensions = getDimensions( image ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); } - state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } } else { @@ -25179,6 +25215,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; let levels = getMipLevels( texture, image, supportsMips ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); @@ -25207,7 +25244,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } } else { @@ -25225,7 +25266,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } } else { @@ -25251,7 +25296,9 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( mipmaps.length > 0 ) levels ++; - state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + const dimensions = getDimensions( cubeImage[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height ); } @@ -25261,7 +25308,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } } else { @@ -25276,7 +25327,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } } else { @@ -25290,7 +25345,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } } else { @@ -25304,7 +25363,11 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( useTexStorage ) { - state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } } else { @@ -25451,7 +25514,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } else { - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; for ( let i = 0; i < textures.length; i ++ ) { @@ -25615,7 +25678,13 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + const textures = renderTarget.textures; + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + if ( ! isMultipleRenderTargets ) { if ( textureProperties.__webglTexture === undefined ) { @@ -25628,10 +25697,6 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - // Setup framebuffer if ( isCube ) { @@ -25680,8 +25745,6 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( capabilities.drawBuffers ) { - const textures = renderTarget.texture; - for ( let i = 0, il = textures.length; i < il; i ++ ) { const attachmentProperties = properties.get( textures[ i ] ); @@ -25706,8 +25769,6 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - const textures = isMultipleRenderTargets ? texture : [ texture ]; - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); renderTargetProperties.__webglColorRenderbuffer = []; @@ -25780,8 +25841,6 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } else if ( isMultipleRenderTargets ) { - const textures = renderTarget.texture; - for ( let i = 0, il = textures.length; i < il; i ++ ) { const attachment = textures[ i ]; @@ -25860,7 +25919,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; for ( let i = 0, il = textures.length; i < il; i ++ ) { @@ -25885,14 +25944,14 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const textures = renderTarget.textures; const width = renderTarget.width; const height = renderTarget.height; let mask = _gl.COLOR_BUFFER_BIT; const invalidationArray = []; const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; const renderTargetProperties = properties.get( renderTarget ); - const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); // If MRT we need to remove FBO attachments if ( isMultipleRenderTargets ) { @@ -26076,6 +26135,31 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } + function getDimensions( image ) { + + if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) { + + // if intrinsic data are not available, fallback to width/height + + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + + } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) { + + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + + } else { + + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + + } + + return _imageDimensions; + + } + // this.allocateTextureUnit = allocateTextureUnit; @@ -26739,6 +26823,105 @@ class WebXRController { } +const _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + +const _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + +class WebXRDepthSensing { + + constructor() { + + this.texture = null; + this.mesh = null; + + this.depthNear = 0; + this.depthFar = 0; + + } + + init( renderer, depthData, renderState ) { + + if ( this.texture === null ) { + + const texture = new Texture(); + + const texProps = renderer.properties.get( texture ); + texProps.__webglTexture = depthData.texture; + + if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) { + + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + + } + + this.texture = texture; + + } + + } + + render( renderer, cameraXR ) { + + if ( this.texture !== null ) { + + if ( this.mesh === null ) { + + const viewport = cameraXR.cameras[ 0 ].viewport; + const material = new ShaderMaterial( { + extensions: { fragDepth: true }, + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + } ); + + this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material ); + + } + + renderer.render( this.mesh, cameraXR ); + + } + + } + + reset() { + + this.texture = null; + this.mesh = null; + + } + +} + class WebXRManager extends EventDispatcher { constructor( renderer, gl ) { @@ -26762,7 +26945,10 @@ class WebXRManager extends EventDispatcher { let glProjLayer = null; let glBaseLayer = null; let xrFrame = null; + + const depthSensing = new WebXRDepthSensing(); const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; let newRenderTarget = null; @@ -26892,6 +27078,8 @@ class WebXRManager extends EventDispatcher { _currentDepthNear = null; _currentDepthFar = null; + depthSensing.reset(); + // restore framebuffer/rendering state renderer.setRenderTarget( initialRenderTarget ); @@ -27250,6 +27438,13 @@ class WebXRManager extends EventDispatcher { if ( session === null ) return; + if ( depthSensing.texture !== null ) { + + camera.near = depthSensing.depthNear; + camera.far = depthSensing.depthFar; + + } + cameraXR.near = cameraR.near = cameraL.near = camera.near; cameraXR.far = cameraR.far = cameraL.far = camera.far; @@ -27265,6 +27460,15 @@ class WebXRManager extends EventDispatcher { _currentDepthNear = cameraXR.near; _currentDepthFar = cameraXR.far; + cameraL.near = _currentDepthNear; + cameraL.far = _currentDepthFar; + cameraR.near = _currentDepthNear; + cameraR.far = _currentDepthFar; + + cameraL.updateProjectionMatrix(); + cameraR.updateProjectionMatrix(); + camera.updateProjectionMatrix(); + } const parent = camera.parent; @@ -27366,6 +27570,12 @@ class WebXRManager extends EventDispatcher { }; + this.hasDepthSensing = function () { + + return depthSensing.texture !== null; + + }; + // Animation Loop let onAnimationFrameCallback = null; @@ -27458,6 +27668,22 @@ class WebXRManager extends EventDispatcher { } + // + + const enabledFeatures = session.enabledFeatures; + + if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) { + + const depthData = glBinding.getDepthInformation( views[ 0 ] ); + + if ( depthData && depthData.isValid && depthData.texture ) { + + depthSensing.init( renderer, depthData, session.renderState ); + + } + + } + } // @@ -27475,6 +27701,8 @@ class WebXRManager extends EventDispatcher { } + depthSensing.render( renderer, cameraXR ); + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); if ( frame.detectedPlanes ) { @@ -27503,6 +27731,9 @@ class WebXRManager extends EventDispatcher { } +const _e1 = /*@__PURE__*/ new Euler(); +const _m1 = /*@__PURE__*/ new Matrix4(); + function WebGLMaterials( renderer, properties ) { function refreshTransformUniform( map, uniform ) { @@ -27711,12 +27942,30 @@ function WebGLMaterials( renderer, properties ) { } - const envMap = properties.get( material ).envMap; + const materialProperties = properties.get( material ); + + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; if ( envMap ) { uniforms.envMap.value = envMap; + _e1.copy( envMapRotation ); + + // accommodate left-handed frame + _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1; + + if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1.y *= - 1; + _e1.z *= - 1; + + } + + uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) ); + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; uniforms.reflectivity.value = material.reflectivity; @@ -28884,7 +29133,7 @@ class WebGLRenderer { } - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() ); }; @@ -28906,7 +29155,7 @@ class WebGLRenderer { } - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() ); }; @@ -29602,7 +29851,11 @@ class WebGLRenderer { // - background.render( currentRenderList, scene ); + if ( xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false ) { + + background.render( currentRenderList, scene ); + + } // render scene @@ -30003,6 +30256,7 @@ class WebGLRenderer { materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; materialProperties.fog = scene.fog; materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation; if ( programs === undefined ) { @@ -30115,6 +30369,7 @@ class WebGLRenderer { materialProperties.batching = parameters.batching; materialProperties.instancing = parameters.instancing; materialProperties.instancingColor = parameters.instancingColor; + materialProperties.instancingMorph = parameters.instancingMorph; materialProperties.skinning = parameters.skinning; materialProperties.morphTargets = parameters.morphTargets; materialProperties.morphNormals = parameters.morphNormals; @@ -30225,6 +30480,14 @@ class WebGLRenderer { needsProgramChange = true; + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) { + + needsProgramChange = true; + } else if ( materialProperties.envMap !== envMap ) { needsProgramChange = true; @@ -30553,20 +30816,16 @@ class WebGLRenderer { const renderTargetProperties = properties.get( renderTarget ); renderTargetProperties.__hasExternalTextures = true; - if ( renderTargetProperties.__hasExternalTextures ) { - - renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - - if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - // The multisample_render_to_texture extension doesn't work properly if there - // are midframe flushes and an external depth buffer. Disable use of the extension. - if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { - console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); - renderTargetProperties.__useRenderToTexture = false; + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - } + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; } @@ -30826,8 +31085,8 @@ class WebGLRenderer { } - const width = sourceBox.max.x - sourceBox.min.x + 1; - const height = sourceBox.max.y - sourceBox.min.y + 1; + const width = Math.round( sourceBox.max.x - sourceBox.min.x ); + const height = Math.round( sourceBox.max.y - sourceBox.min.y ); const depth = sourceBox.max.z - sourceBox.min.z + 1; const glFormat = utils.convert( dstTexture.format ); const glType = utils.convert( dstTexture.type ); @@ -30874,9 +31133,8 @@ class WebGLRenderer { } else { - if ( srcTexture.isCompressedArrayTexture ) { + if ( dstTexture.isCompressedArrayTexture ) { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); } else { @@ -30965,20 +31223,6 @@ class WebGLRenderer { } - get outputEncoding() { // @deprecated, r152 - - console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); - return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - - set outputEncoding( encoding ) { // @deprecated, r152 - - console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' ); - this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; - - } - get useLegacyLights() { // @deprecated, r155 console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' ); @@ -31082,6 +31326,8 @@ class Scene extends Object3D { this.backgroundBlurriness = 0; this.backgroundIntensity = 1; + this.backgroundRotation = new Euler(); + this.environmentRotation = new Euler(); this.overrideMaterial = null; @@ -31103,6 +31349,8 @@ class Scene extends Object3D { this.backgroundBlurriness = source.backgroundBlurriness; this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy( source.backgroundRotation ); + this.environmentRotation.copy( source.environmentRotation ); if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); @@ -31120,6 +31368,9 @@ class Scene extends Object3D { if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + data.object.backgroundRotation = this.backgroundRotation.toArray(); + data.object.environmentRotation = this.environmentRotation.toArray(); + return data; } @@ -31156,7 +31407,7 @@ class InterleavedBuffer { get updateRange() { - console.warn( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 + warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159 return this._updateRange; } @@ -31371,6 +31622,26 @@ class InterleavedBufferAttribute { } + getComponent( index, component ) { + + let value = this.array[ index * this.data.stride + this.offset + component ]; + + if ( this.normalized ) value = denormalize( value, this.array ); + + return value; + + } + + setComponent( index, component, value ) { + + if ( this.normalized ) value = normalize$1( value, this.array ); + + this.data.array[ index * this.data.stride + this.offset + component ] = value; + + return this; + + } + setX( index, x ) { if ( this.normalized ) x = normalize$1( x, this.array ); @@ -32643,6 +32914,7 @@ class InstancedMesh extends Mesh { this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); this.instanceColor = null; + this.morphTexture = null; this.count = count; @@ -32748,6 +33020,24 @@ class InstancedMesh extends Mesh { } + getMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const array = this.morphTexture.source.data.data; + + const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum + + const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + objectInfluences[ i ] = array[ dataIndex + i ]; + + } + + } + raycast( raycaster, intersects ) { const matrixWorld = this.matrixWorld; @@ -32818,6 +33108,38 @@ class InstancedMesh extends Mesh { } + setMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const len = objectInfluences.length + 1; // morphBaseInfluence + all influences + + if ( this.morphTexture === null ) { + + this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType ); + + } + + const array = this.morphTexture.source.data.data; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + const dataIndex = len * index; + + array[ dataIndex ] = morphBaseInfluence; + + array.set( objectInfluences, dataIndex + 1 ); + + } + updateMorphTargets() { } @@ -32888,7 +33210,7 @@ class MultiDrawRenderList { } const ID_ATTR_NAME = 'batchId'; -const _matrix = /*@__PURE__*/ new Matrix4(); +const _matrix$1 = /*@__PURE__*/ new Matrix4(); const _invMatrixWorld = /*@__PURE__*/ new Matrix4(); const _identityMatrix = /*@__PURE__*/ new Matrix4(); const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4(); @@ -33111,8 +33433,8 @@ class BatchedMesh extends Mesh { if ( active[ i ] === false ) continue; - this.getMatrixAt( i, _matrix ); - this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix$1 ); boundingBox.union( _box$1 ); } @@ -33136,8 +33458,8 @@ class BatchedMesh extends Mesh { if ( active[ i ] === false ) continue; - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); boundingSphere.union( _sphere$2 ); } @@ -33727,7 +34049,7 @@ class BatchedMesh extends Mesh { .multiply( this.matrixWorld ); _frustum$1.setFromProjectionMatrix( _projScreenMatrix$2, - renderer.isWebGPURenderer ? WebGPUCoordinateSystem : WebGLCoordinateSystem + renderer.coordinateSystem ); } @@ -33744,8 +34066,8 @@ class BatchedMesh extends Mesh { if ( visibility[ i ] && active[ i ] ) { // get the bounds in world space - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); // determine whether the batched geometry is within the frustum let culled = false; @@ -33802,8 +34124,8 @@ class BatchedMesh extends Mesh { if ( perObjectFrustumCulled ) { // get the bounds in world space - this.getMatrixAt( i, _matrix ); - this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix ); + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 ); culled = ! _frustum$1.intersectsSphere( _sphere$2 ); } @@ -34932,9 +35254,9 @@ class EllipseCurve extends Curve { } - getPoint( t, optionalTarget ) { + getPoint( t, optionalTarget = new Vector2() ) { - const point = optionalTarget || new Vector2(); + const point = optionalTarget; const twoPi = Math.PI * 2; let deltaAngle = this.aEndAngle - this.aStartAngle; @@ -37394,7 +37716,7 @@ class DodecahedronGeometry extends PolyhedronGeometry { const _v0 = /*@__PURE__*/ new Vector3(); const _v1$1 = /*@__PURE__*/ new Vector3(); -const _normal = /*@__PURE__*/ new Vector3(); +const _normal$2 = /*@__PURE__*/ new Vector3(); const _triangle = /*@__PURE__*/ new Triangle(); class EdgesGeometry extends BufferGeometry { @@ -37446,7 +37768,7 @@ class EdgesGeometry extends BufferGeometry { a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); - _triangle.getNormal( _normal ); + _triangle.getNormal( _normal$2 ); // create hashes for the edge from the vertices hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; @@ -37477,7 +37799,7 @@ class EdgesGeometry extends BufferGeometry { // if we found a sibling edge add it into the vertex array if // it meets the angle threshold and delete the edge from the map. - if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + if ( _normal$2.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { vertices.push( v0.x, v0.y, v0.z ); vertices.push( v1.x, v1.y, v1.z ); @@ -37493,7 +37815,7 @@ class EdgesGeometry extends BufferGeometry { index0: indexArr[ j ], index1: indexArr[ jNext ], - normal: _normal.clone(), + normal: _normal$2.clone(), }; @@ -37699,7 +38021,7 @@ function linkedList( data, start, end, dim, clockwise ) { } - if ( last && equals( last, last.next ) ) { + if ( last && equals$1( last, last.next ) ) { removeNode( last ); last = last.next; @@ -37722,7 +38044,7 @@ function filterPoints( start, end ) { again = false; - if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { removeNode( p ); p = end = p.prev; @@ -37907,7 +38229,7 @@ function cureLocalIntersections( start, triangles, dim ) { const a = p.prev, b = p.next.next; - if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { triangles.push( a.i / dim | 0 ); triangles.push( p.i / dim | 0 ); @@ -38230,7 +38552,7 @@ function isValidDiagonal( a, b ) { return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case } @@ -38242,7 +38564,7 @@ function area( p, q, r ) { } // check if two points are equal -function equals( p1, p2 ) { +function equals$1( p1, p2 ) { return p1.x === p2.x && p1.y === p2.y; @@ -40591,6 +40913,7 @@ class MeshStandardMaterial extends Material { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.envMapIntensity = 1.0; this.wireframe = false; @@ -40646,6 +40969,7 @@ class MeshStandardMaterial extends Material { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.envMapIntensity = source.envMapIntensity; this.wireframe = source.wireframe; @@ -40923,6 +41247,7 @@ class MeshPhongMaterial extends Material { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -40976,6 +41301,7 @@ class MeshPhongMaterial extends Material { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -41187,6 +41513,7 @@ class MeshLambertMaterial extends Material { this.alphaMap = null; this.envMap = null; + this.envMapRotation = new Euler(); this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -41238,6 +41565,7 @@ class MeshLambertMaterial extends Material { this.alphaMap = source.alphaMap; this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; @@ -44080,10 +44408,6 @@ class DataTextureLoader extends Loader { texture.colorSpace = texData.colorSpace; - } else if ( texData.encoding !== undefined ) { // @deprecated, r152 - - texture.encoding = texData.encoding; - } if ( texData.flipY !== undefined ) { @@ -45319,6 +45643,7 @@ class MaterialLoader extends Loader { if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation ); if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; @@ -46299,7 +46624,6 @@ class ObjectLoader extends Loader { if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat; if ( data.type !== undefined ) texture.type = data.type; if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace; - if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152 if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); @@ -46438,6 +46762,8 @@ class ObjectLoader extends Loader { if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation ); + if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation ); break; @@ -50748,7 +51074,7 @@ class Uniform$1 { } -let _id$3 = 0; +let _id$4 = 0; class UniformsGroup$1 extends EventDispatcher { @@ -50758,7 +51084,7 @@ class UniformsGroup$1 extends EventDispatcher { this.isUniformsGroup = true; - Object.defineProperty( this, 'id', { value: _id$3 ++ } ); + Object.defineProperty( this, 'id', { value: _id$4 ++ } ); this.name = ''; @@ -50946,6 +51272,8 @@ class GLBufferAttribute { } +const _matrix = /*@__PURE__*/ new Matrix4(); + class Raycaster { constructor( origin, direction, near = 0, far = Infinity ) { @@ -50998,9 +51326,20 @@ class Raycaster { } + setFromXRController( controller ) { + + _matrix.identity().extractRotation( controller.matrixWorld ); + + this.ray.origin.setFromMatrixPosition( controller.matrixWorld ); + this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix ); + + return this; + + } + intersectObject( object, recursive = true, intersects = [] ) { - intersectObject( object, this, intersects, recursive ); + intersect( object, this, intersects, recursive ); intersects.sort( ascSort ); @@ -51012,7 +51351,7 @@ class Raycaster { for ( let i = 0, l = objects.length; i < l; i ++ ) { - intersectObject( objects[ i ], this, intersects, recursive ); + intersect( objects[ i ], this, intersects, recursive ); } @@ -51030,7 +51369,7 @@ function ascSort( a, b ) { } -function intersectObject( object, raycaster, intersects, recursive ) { +function intersect( object, raycaster, intersects, recursive ) { if ( object.layers.test( raycaster.layers ) ) { @@ -51044,7 +51383,7 @@ function intersectObject( object, raycaster, intersects, recursive ) { for ( let i = 0, l = children.length; i < l; i ++ ) { - intersectObject( children[ i ], raycaster, intersects, true ); + intersect( children[ i ], raycaster, intersects, true ); } @@ -51518,7 +51857,6 @@ class SpotLightHelper extends Object3D { this.light = light; - this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; this.color = color; @@ -51570,6 +51908,24 @@ class SpotLightHelper extends Object3D { this.light.updateWorldMatrix( true, false ); this.light.target.updateWorldMatrix( true, false ); + // update the local matrix based on the parent and light target transforms + if ( this.parent ) { + + this.parent.updateWorldMatrix( true ); + + this.matrix + .copy( this.parent.matrixWorld ) + .invert() + .multiply( this.light.matrixWorld ); + + } else { + + this.matrix.copy( this.light.matrixWorld ); + + } + + this.matrixWorld.copy( this.light.matrixWorld ); + const coneLength = this.light.distance ? this.light.distance : 1000; const coneWidth = coneLength * Math.tan( this.light.angle ); @@ -53010,6 +53366,26 @@ class ShapePath { } +class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162 + + constructor( width = 1, height = 1, count = 1, options = {} ) { + + console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' ); + + super( width, height, { ...options, count } ); + + this.isWebGLMultipleRenderTargets = true; + + } + + get texture() { + + return this.textures; + + } + +} + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { @@ -53032,23 +53408,20 @@ if ( typeof window !== 'undefined' ) { } -if ( window.GPUShaderStage === undefined ) { +if ( self.GPUShaderStage === undefined ) { - window.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; + self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; } -let isAvailable = false; - -if ( navigator.gpu !== undefined ) { +// statics - const adapter = await navigator.gpu.requestAdapter(); +let isAvailable = navigator.gpu !== undefined; - if ( adapter !== null ) { - isAvailable = true; +if ( typeof window !== 'undefined' && isAvailable ) { - } + isAvailable = await navigator.gpu.requestAdapter(); } @@ -53056,6 +53429,12 @@ class WebGPU { static isAvailable() { + return Boolean( isAvailable ); + + } + + static getStaticAdapter() { + return isAvailable; } @@ -53220,6 +53599,168 @@ class ChainMap { } +const _plane = new Plane(); +const _viewNormalMatrix = new Matrix3(); + +let _clippingContextVersion = 0; + +class ClippingContext { + + constructor() { + + this.version = ++ _clippingContextVersion; + + this.globalClippingCount = 0; + + this.localClippingCount = 0; + this.localClippingEnabled = false; + this.localClipIntersection = false; + + this.planes = []; + + this.parentVersion = 0; + + } + + projectPlanes( source, offset ) { + + const l = source.length; + const planes = this.planes; + + for ( let i = 0; i < l; i ++ ) { + + _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, _viewNormalMatrix ); + + const v = planes[ offset + i ]; + const normal = _plane.normal; + + v.x = - normal.x; + v.y = - normal.y; + v.z = - normal.z; + v.w = _plane.constant; + + } + + } + + updateGlobal( renderer, camera ) { + + const rendererClippingPlanes = renderer.clippingPlanes; + this.viewMatrix = camera.matrixWorldInverse; + + _viewNormalMatrix.getNormalMatrix( this.viewMatrix ); + + let update = false; + + if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) { + + const l = rendererClippingPlanes.length; + + if ( l !== this.globalClippingCount ) { + + const planes = []; + + for ( let i = 0; i < l; i ++ ) { + + planes.push( new Vector4() ); + + } + + this.globalClippingCount = l; + this.planes = planes; + + update = true; + + } + + this.projectPlanes( rendererClippingPlanes, 0 ); + + } else if ( this.globalClippingCount !== 0 ) { + + this.globalClippingCount = 0; + this.planes = []; + update = true; + + } + + if ( renderer.localClippingEnabled !== this.localClippingEnabled ) { + + this.localClippingEnabled = renderer.localClippingEnabled; + update = true; + + } + + if ( update ) this.version = _clippingContextVersion ++; + + } + + update( parent, material ) { + + let update = false; + + if ( this !== parent && parent.version !== this.parentVersion ) { + + this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount; + this.localClippingEnabled = parent.localClippingEnabled; + this.planes = Array.from( parent.planes ); + this.parentVersion = parent.version; + this.viewMatrix = parent.viewMatrix; + + + update = true; + + } + + if ( this.localClippingEnabled ) { + + const localClippingPlanes = material.clippingPlanes; + + if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) { + + const l = localClippingPlanes.length; + const planes = this.planes; + const offset = this.globalClippingCount; + + if ( update || l !== this.localClippingCount ) { + + planes.length = offset + l; + + for ( let i = 0; i < l; i ++ ) { + + planes[ offset + i ] = new Vector4(); + + } + + this.localClippingCount = l; + update = true; + + } + + this.projectPlanes( localClippingPlanes, offset ); + + + } else if ( this.localClippingCount !== 0 ) { + + this.localClippingCount = 0; + update = true; + + } + + if ( this.localClipIntersection !== material.clipIntersection ) { + + this.localClipIntersection = material.clipIntersection; + update = true; + + } + + } + + if ( update ) this.version = _clippingContextVersion ++; + + } + +} + let id$4 = 0; class RenderObject { @@ -53246,6 +53787,10 @@ class RenderObject { this.pipeline = null; this.vertexBuffers = null; + this.updateClipping( renderContext.clippingContext ); + + this.clippingContextVersion = this.clippingContext.version; + this.initialNodesCacheKey = this.getNodesCacheKey(); this.initialCacheKey = this.getCacheKey(); @@ -53266,6 +53811,41 @@ class RenderObject { } + updateClipping( parent ) { + + const material = this.material; + + let clippingContext = this.clippingContext; + + if ( Array.isArray( material.clippingPlanes ) ) { + + if ( clippingContext === parent || ! clippingContext ) { + + clippingContext = new ClippingContext(); + this.clippingContext = clippingContext; + + } + + clippingContext.update( parent, material ); + + } else if ( this.clippingContext !== parent ) { + + this.clippingContext = parent; + + } + + } + + clippingNeedsUpdate () { + + if ( this.clippingContext.version === this.clippingContextVersion ) return false; + + this.clippingContextVersion = this.clippingContext.version; + + return true; + + } + getNodeBuilderState() { return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) ); @@ -53353,9 +53933,11 @@ class RenderObject { } + cacheKey += this.clippingContextVersion + ','; + if ( object.skeleton ) { - cacheKey += object.skeleton.uuid + ','; + cacheKey += object.skeleton.bones.length + ','; } @@ -53429,7 +54011,9 @@ class RenderObjects { } else { - if ( renderObject.version !== material.version || renderObject.needsUpdate ) { + renderObject.updateClipping( renderContext.clippingContext ); + + if ( renderObject.version !== material.version || renderObject.needsUpdate || renderObject.clippingNeedsUpdate() ) { if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) { @@ -53852,7 +54436,8 @@ class Info { }; this.compute = { - calls: 0 + calls: 0, + computeCalls: 0 }; this.memory = { @@ -53860,6 +54445,11 @@ class Info { textures: 0 }; + this.timestamp = { + compute: 0, + render: 0 + }; + } update( object, count, instanceCount ) { @@ -53886,6 +54476,20 @@ class Info { } + updateTimestamp( type, time ) { + + this.timestamp[ type ] += time; + + } + + resetCompute() { + + this.compute.computeCalls = 0; + + this.timestamp.compute = 0; + + } + reset() { this.render.drawCalls = 0; @@ -53893,6 +54497,8 @@ class Info { this.render.points = 0; this.render.lines = 0; + this.timestamp.render = 0; + } dispose() { @@ -53904,6 +54510,8 @@ class Info { this.render.calls = 0; this.compute.calls = 0; + this.timestamp.compute = 0; + this.timestamp.render = 0; this.memory.geometries = 0; this.memory.textures = 0; @@ -53950,16 +54558,18 @@ class ComputePipeline extends Pipeline { } -let _id = 0; +let _id$3 = 0; class ProgrammableStage { - constructor( code, type ) { + constructor( code, type, transforms = null, attributes = null ) { - this.id = _id ++; + this.id = _id$3 ++; this.code = code; this.stage = type; + this.transforms = transforms; + this.attributes = attributes; this.usedTimes = 0; @@ -54006,18 +54616,18 @@ class Pipelines extends DataMap { // get shader - const nodeBuilder = this.nodes.getForCompute( computeNode ); + const nodeBuilderState = this.nodes.getForCompute( computeNode ); // programmable stage - let stageCompute = this.programs.compute.get( nodeBuilder.computeShader ); + let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader ); if ( stageCompute === undefined ) { if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram ); - stageCompute = new ProgrammableStage( nodeBuilder.computeShader, 'compute' ); - this.programs.compute.set( nodeBuilder.computeShader, stageCompute ); + stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes ); + this.programs.compute.set( nodeBuilderState.computeShader, stageCompute ); backend.createProgram( stageCompute ); @@ -54053,7 +54663,7 @@ class Pipelines extends DataMap { } - getForRender( renderObject ) { + getForRender( renderObject, promises = null ) { const { backend } = this; @@ -54113,7 +54723,7 @@ class Pipelines extends DataMap { if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline ); - pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey ); + pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ); } else { @@ -54214,7 +54824,7 @@ class Pipelines extends DataMap { } - _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey ) { + _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) { // check for existing pipeline @@ -54230,7 +54840,7 @@ class Pipelines extends DataMap { renderObject.pipeline = pipeline; - this.backend.createRenderPipeline( renderObject ); + this.backend.createRenderPipeline( renderObject, promises ); } @@ -54330,7 +54940,7 @@ class Bindings extends DataMap { const nodeBuilderState = this.nodes.getForCompute( computeNode ); - const bindings = nodeBuilderState.bindings.compute; + const bindings = nodeBuilderState.bindings; data.bindings = bindings; @@ -54471,6 +55081,7 @@ const NodeType = { VECTOR2: 'vec2', VECTOR3: 'vec3', VECTOR4: 'vec4', + MATRIX2: 'mat2', MATRIX3: 'mat3', MATRIX4: 'mat4' }; @@ -54736,7 +55347,7 @@ class Node extends EventDispatcher { } - updateReference() { + setReference( /*state*/ ) { return this; @@ -54844,12 +55455,20 @@ class Node extends EventDispatcher { } - analyze( builder ) { + increaseUsage( builder ) { const nodeData = builder.getDataFromNode( this ); - nodeData.dependenciesCount = nodeData.dependenciesCount === undefined ? 1 : nodeData.dependenciesCount + 1; + nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1; + + return nodeData.usageCount; + + } + + analyze( builder ) { - if ( nodeData.dependenciesCount === 1 ) { + const usageCount = this.increaseUsage( builder ); + + if ( usageCount === 1 ) { // node flow children @@ -54913,6 +55532,8 @@ class Node extends EventDispatcher { if ( buildStage === 'setup' ) { + this.setReference( builder ); + const properties = builder.getNodeProperties( this ); if ( properties.initialized !== true || builder.context.tempRead === false ) { @@ -55168,114 +55789,60 @@ function createNodeFromType( type ) { } -class InputNode extends Node { - - constructor( value, nodeType = null ) { - - super( nodeType ); - - this.isInputNode = true; - - this.value = value; - this.precision = null; - - } - - getNodeType( /*builder*/ ) { - - if ( this.nodeType === null ) { - - return getValueType( this.value ); - - } - - return this.nodeType; - - } - - getInputType( builder ) { - - return this.getNodeType( builder ); - - } +class TempNode extends Node { - setPrecision( precision ) { + constructor( type ) { - this.precision = precision; + super( type ); - return this; + this.isTempNode = true; } - serialize( data ) { - - super.serialize( data ); - - data.value = this.value; - - if ( this.value && this.value.toArray ) data.value = this.value.toArray(); - - data.valueType = getValueType( this.value ); - data.nodeType = this.nodeType; - - if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + hasDependencies( builder ) { - data.precision = this.precision; + return builder.getDataFromNode( this ).usageCount > 1; } - deserialize( data ) { - - super.deserialize( data ); - - this.nodeType = data.nodeType; - this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; - - this.precision = data.precision || null; - - if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + build( builder, output ) { - } + const buildStage = builder.getBuildStage(); - generate( /*builder, output*/ ) { + if ( buildStage === 'generate' ) { - } + const type = builder.getVectorType( this.getNodeType( builder, output ) ); + const nodeData = builder.getDataFromNode( this ); -} + if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { -addNodeClass( 'InputNode', InputNode ); + return builder.format( nodeData.propertyName, type, output ); -class UniformGroupNode extends Node { + } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - constructor( name, shared = false ) { + const snippet = super.build( builder, type ); - super( 'string' ); + const nodeVar = builder.getVarFromNode( this, null, type ); + const propertyName = builder.getPropertyName( nodeVar ); - this.name = name; - this.version = 0; + builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - this.shared = shared; + nodeData.snippet = snippet; + nodeData.propertyName = propertyName; - this.isUniformGroup = true; + return builder.format( nodeData.propertyName, type, output ); - } + } - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + return super.build( builder, output ); } } -const uniformGroup = ( name ) => new UniformGroupNode( name ); -const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); - -const frameGroup = sharedUniformGroup( 'frame' ); -const renderGroup = sharedUniformGroup( 'render' ); -const objectGroup = uniformGroup( 'object' ); - -addNodeClass( 'UniformGroupNode', UniformGroupNode ); +addNodeClass( 'TempNode', TempNode ); class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute @@ -55371,61 +55938,6 @@ class ConvertNode extends Node { addNodeClass( 'ConvertNode', ConvertNode ); -class TempNode extends Node { - - constructor( type ) { - - super( type ); - - this.isTempNode = true; - - } - - hasDependencies( builder ) { - - return builder.getDataFromNode( this ).dependenciesCount > 1; - - } - - build( builder, output ) { - - const buildStage = builder.getBuildStage(); - - if ( buildStage === 'generate' ) { - - const type = builder.getVectorType( this.getNodeType( builder, output ) ); - const nodeData = builder.getDataFromNode( this ); - - if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { - - return builder.format( nodeData.propertyName, type, output ); - - } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - - const snippet = super.build( builder, type ); - - const nodeVar = builder.getVarFromNode( this, null, type ); - const propertyName = builder.getPropertyName( nodeVar ); - - builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - - nodeData.snippet = snippet; - nodeData.propertyName = propertyName; - - return builder.format( nodeData.propertyName, type, output ); - - } - - } - - return super.build( builder, output ); - - } - -} - -addNodeClass( 'TempNode', TempNode ); - class JoinNode extends TempNode { constructor( nodes = [], nodeType = null ) { @@ -55453,7 +55965,7 @@ class JoinNode extends TempNode { const type = this.getNodeType( builder ); const nodes = this.nodes; - const primitiveType = builder.getPrimitiveType( type ); + const primitiveType = builder.getComponentType( type ); const snippetValues = []; @@ -55461,7 +55973,7 @@ class JoinNode extends TempNode { let inputSnippet = input.build( builder ); - const inputPrimitiveType = builder.getPrimitiveType( input.getNodeType( builder ) ); + const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) ); if ( inputPrimitiveType !== primitiveType ) { @@ -55512,15 +56024,15 @@ class SplitNode extends Node { } - getPrimitiveType( builder ) { + getComponentType( builder ) { - return builder.getPrimitiveType( this.node.getNodeType( builder ) ); + return builder.getComponentType( this.node.getNodeType( builder ) ); } getNodeType( builder ) { - return builder.getTypeFromLength( this.components.length, this.getPrimitiveType( builder ) ); + return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) ); } @@ -55541,7 +56053,7 @@ class SplitNode extends Node { // needed expand the input node - type = builder.getTypeFromLength( this.getVectorLength(), this.getPrimitiveType( builder ) ); + type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) ); } @@ -55648,6 +56160,83 @@ class SetNode extends TempNode { addNodeClass( 'SetNode', SetNode ); +class InputNode extends Node { + + constructor( value, nodeType = null ) { + + super( nodeType ); + + this.isInputNode = true; + + this.value = value; + this.precision = null; + + } + + getNodeType( /*builder*/ ) { + + if ( this.nodeType === null ) { + + return getValueType( this.value ); + + } + + return this.nodeType; + + } + + getInputType( builder ) { + + return this.getNodeType( builder ); + + } + + setPrecision( precision ) { + + this.precision = precision; + + return this; + + } + + serialize( data ) { + + super.serialize( data ); + + data.value = this.value; + + if ( this.value && this.value.toArray ) data.value = this.value.toArray(); + + data.valueType = getValueType( this.value ); + data.nodeType = this.nodeType; + + if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + + data.precision = this.precision; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.nodeType = data.nodeType; + this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; + + this.precision = data.precision || null; + + if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + + } + + generate( /*builder, output*/ ) { + + } + +} + +addNodeClass( 'InputNode', InputNode ); + class ConstNode extends InputNode { constructor( value, nodeType = null ) { @@ -56233,6 +56822,11 @@ const ivec4 = new ConvertType( 'ivec4' ); const uvec4 = new ConvertType( 'uvec4' ); const bvec4 = new ConvertType( 'bvec4' ); +const mat2 = new ConvertType( 'mat2' ); +const imat2 = new ConvertType( 'imat2' ); +const umat2 = new ConvertType( 'umat2' ); +const bmat2 = new ConvertType( 'bmat2' ); + const mat3 = new ConvertType( 'mat3' ); const imat3 = new ConvertType( 'imat3' ); const umat3 = new ConvertType( 'umat3' ); @@ -56263,6 +56857,10 @@ addNodeElement( 'vec4', vec4 ); addNodeElement( 'ivec4', ivec4 ); addNodeElement( 'uvec4', uvec4 ); addNodeElement( 'bvec4', bvec4 ); +addNodeElement( 'mat2', mat2 ); +addNodeElement( 'imat2', imat2 ); +addNodeElement( 'umat2', umat2 ); +addNodeElement( 'bmat2', bmat2 ); addNodeElement( 'mat3', mat3 ); addNodeElement( 'imat3', imat3 ); addNodeElement( 'umat3', umat3 ); @@ -56283,159 +56881,118 @@ const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node addNodeElement( 'element', element ); addNodeElement( 'convert', convert ); -class UniformNode extends InputNode { - - constructor( value, nodeType = null ) { - - super( value, nodeType ); - - this.isUniformNode = true; - - this.groupNode = objectGroup; - - } +class AssignNode extends TempNode { - setGroup( group ) { + constructor( targetNode, sourceNode ) { - this.groupNode = group; + super(); - return this; + this.targetNode = targetNode; + this.sourceNode = sourceNode; } - getGroup() { + hasDependencies() { - return this.groupNode; + return false; } - getUniformHash( builder ) { + getNodeType( builder, output ) { - return this.getHash( builder ); + return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; } - generate( builder, output ) { + needsSplitAssign( builder ) { - const type = this.getNodeType( builder ); + const { targetNode } = this; - const hash = this.getUniformHash( builder ); + if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) { - let sharedNode = builder.getNodeFromHash( hash ); + const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) ); + const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components; - if ( sharedNode === undefined ) { - - builder.setHashNode( this, hash ); - - sharedNode = this; + return assignDiferentVector; } - const sharedNodeType = sharedNode.getInputType( builder ); - - const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); - const propertyName = builder.getPropertyName( nodeUniform ); - - if ( builder.context.label !== undefined ) delete builder.context.label; - - return builder.format( propertyName, type, output ); - - } - -} - -const uniform = ( arg1, arg2 ) => { - - const nodeType = getConstNodeType( arg2 || arg1 ); - - // @TODO: get ConstNode from .traverse() in the future - const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; - - return nodeObject( new UniformNode( value, nodeType ) ); - -}; - -addNodeClass( 'UniformNode', UniformNode ); - -class ArrayUniformNode extends UniformNode { - - constructor( nodes = [] ) { - - super(); - - this.isArrayUniformNode = true; - - this.nodes = nodes; + return false; } - getNodeType( builder ) { + generate( builder, output ) { - return this.nodes[ 0 ].getNodeType( builder ); + const { targetNode, sourceNode } = this; - } + const needsSplitAssign = this.needsSplitAssign( builder ); -} + const targetType = targetNode.getNodeType( builder ); -addNodeClass( 'ArrayUniformNode', ArrayUniformNode ); + const target = targetNode.context( { assign: true } ).build( builder ); + const source = sourceNode.build( builder, targetType ); -class AssignNode extends TempNode { + const sourceType = sourceNode.getNodeType( builder ); - constructor( targetNode, sourceNode ) { + const nodeData = builder.getDataFromNode( this ); - super(); + // - this.targetNode = targetNode; - this.sourceNode = sourceNode; + let snippet; - } + if ( nodeData.initialized === true ) { - hasDependencies() { + if ( output !== 'void' ) { - return false; + snippet = target; - } + } - getNodeType( builder, output ) { + } else if ( needsSplitAssign ) { - return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; + const sourceVar = builder.getVarFromNode( this, null, targetType ); + const sourceProperty = builder.getPropertyName( sourceVar ); - } + builder.addLineFlowCode( `${ sourceProperty } = ${ source }` ); - generate( builder, output ) { + const targetRoot = targetNode.node.context( { assign: true } ).build( builder ); - const targetNode = this.targetNode; - const sourceNode = this.sourceNode; + for ( let i = 0; i < targetNode.components.length; i ++ ) { - const targetType = targetNode.getNodeType( builder ); + const component = targetNode.components[ i ]; - const target = targetNode.build( builder ); - const source = sourceNode.build( builder, targetType ); + builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` ); - const snippet = `${ target } = ${ source }`; + } - if ( output === 'void' ) { + if ( output !== 'void' ) { - builder.addLineFlowCode( snippet ); + snippet = target; - return; + } } else { - const sourceType = sourceNode.getNodeType( builder ); + snippet = `${ target } = ${ source }`; - if ( sourceType === 'void' ) { + if ( output === 'void' || sourceType === 'void' ) { builder.addLineFlowCode( snippet ); - return target; + if ( output !== 'void' ) { - } + snippet = target; + + } - return builder.format( snippet, targetType, output ); + } } + nodeData.initialized = true; + + return builder.format( snippet, targetType, output ); + } } @@ -57191,6 +57748,12 @@ class CodeNode extends Node { } + isGlobal() { + + return true; + + } + setIncludes( includes ) { this.includes = includes; @@ -57375,6 +57938,112 @@ const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' ); addNodeClass( 'FunctionNode', FunctionNode ); +class UniformGroupNode extends Node { + + constructor( name, shared = false ) { + + super( 'string' ); + + this.name = name; + this.version = 0; + + this.shared = shared; + + this.isUniformGroup = true; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +const uniformGroup = ( name ) => new UniformGroupNode( name ); +const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); + +const frameGroup = sharedUniformGroup( 'frame' ); +const renderGroup = sharedUniformGroup( 'render' ); +const objectGroup = uniformGroup( 'object' ); + +addNodeClass( 'UniformGroupNode', UniformGroupNode ); + +class UniformNode extends InputNode { + + constructor( value, nodeType = null ) { + + super( value, nodeType ); + + this.isUniformNode = true; + + this.groupNode = objectGroup; + + } + + setGroup( group ) { + + this.groupNode = group; + + return this; + + } + + getGroup() { + + return this.groupNode; + + } + + getUniformHash( builder ) { + + return this.getHash( builder ); + + } + + generate( builder, output ) { + + const type = this.getNodeType( builder ); + + const hash = this.getUniformHash( builder ); + + let sharedNode = builder.getNodeFromHash( hash ); + + if ( sharedNode === undefined ) { + + builder.setHashNode( this, hash ); + + sharedNode = this; + + } + + const sharedNodeType = sharedNode.getInputType( builder ); + + const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); + const propertyName = builder.getPropertyName( nodeUniform ); + + if ( builder.context.label !== undefined ) delete builder.context.label; + + return builder.format( propertyName, type, output ); + + } + +} + +const uniform = ( arg1, arg2 ) => { + + const nodeType = getConstNodeType( arg2 || arg1 ); + + // @TODO: get ConstNode from .traverse() in the future + const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; + + return nodeObject( new UniformNode( value, nodeType ) ); + +}; + +addNodeClass( 'UniformNode', UniformNode ); + class UVNode extends AttributeNode { constructor( index = 0 ) { @@ -57482,7 +58151,7 @@ class OperatorNode extends TempNode { const bNode = this.bNode; const typeA = aNode.getNodeType( builder ); - const typeB = bNode.getNodeType( builder ); + const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( typeA === 'void' || typeB === 'void' ) { @@ -57492,11 +58161,11 @@ class OperatorNode extends TempNode { return typeA; - } else if ( op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { + } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { return builder.getIntegerType( typeA ); - } else if ( op === '==' || op === '&&' || op === '||' || op === '^^' ) { + } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) { return 'bool'; @@ -57553,7 +58222,7 @@ class OperatorNode extends TempNode { if ( type !== 'void' ) { typeA = aNode.getNodeType( builder ); - typeB = bNode.getNodeType( builder ); + typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) { @@ -57599,7 +58268,7 @@ class OperatorNode extends TempNode { } const a = aNode.build( builder, typeA ); - const b = bNode.build( builder, typeB ); + const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null; const outputLength = builder.getTypeLength( output ); const fnOpSnippet = builder.getFunctionOperator( op ); @@ -57622,6 +58291,10 @@ class OperatorNode extends TempNode { return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output ); + } else if ( op === '!' || op === '~' ) { + + return builder.format( `(${op}${a})`, typeA, output ); + } else if ( fnOpSnippet ) { return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output ); @@ -57679,8 +58352,10 @@ const lessThanEqual = nodeProxy( OperatorNode, '<=' ); const greaterThanEqual = nodeProxy( OperatorNode, '>=' ); const and = nodeProxy( OperatorNode, '&&' ); const or = nodeProxy( OperatorNode, '||' ); +const not = nodeProxy( OperatorNode, '!' ); const xor = nodeProxy( OperatorNode, '^^' ); const bitAnd = nodeProxy( OperatorNode, '&' ); +const bitNot = nodeProxy( OperatorNode, '~' ); const bitOr = nodeProxy( OperatorNode, '|' ); const bitXor = nodeProxy( OperatorNode, '^' ); const shiftLeft = nodeProxy( OperatorNode, '<<' ); @@ -57699,8 +58374,10 @@ addNodeElement( 'lessThanEqual', lessThanEqual ); addNodeElement( 'greaterThanEqual', greaterThanEqual ); addNodeElement( 'and', and ); addNodeElement( 'or', or ); +addNodeElement( 'not', not ); addNodeElement( 'xor', xor ); addNodeElement( 'bitAnd', bitAnd ); +addNodeElement( 'bitNot', bitNot ); addNodeElement( 'bitOr', bitOr ); addNodeElement( 'bitXor', bitXor ); addNodeElement( 'shiftLeft', shiftLeft ); @@ -57762,6 +58439,14 @@ class MathNode extends TempNode { return 'vec3'; + } else if ( method === MathNode.ALL ) { + + return 'bool'; + + } else if ( method === MathNode.EQUALS ) { + + return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' ); + } else if ( method === MathNode.MOD ) { return this.aNode.getNodeType( builder ); @@ -57900,6 +58585,10 @@ class MathNode extends TempNode { // 1 input +MathNode.ALL = 'all'; +MathNode.ANY = 'any'; +MathNode.EQUALS = 'equals'; + MathNode.RADIANS = 'radians'; MathNode.DEGREES = 'degrees'; MathNode.EXP = 'exp'; @@ -57956,6 +58645,12 @@ MathNode.FACEFORWARD = 'faceforward'; const EPSILON = float( 1e-6 ); const INFINITY = float( 1e6 ); +const PI = float( Math.PI ); +const PI2 = float( Math.PI * 2 ); + +const all = nodeProxy( MathNode, MathNode.ALL ); +const any = nodeProxy( MathNode, MathNode.ANY ); +const equals = nodeProxy( MathNode, MathNode.EQUALS ); const radians = nodeProxy( MathNode, MathNode.RADIANS ); const degrees = nodeProxy( MathNode, MathNode.DEGREES ); @@ -58005,6 +58700,7 @@ const pow4 = nodeProxy( MathNode, MathNode.POW, 4 ); const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ); const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) ); +const lengthSq = ( a ) => dot( a, a ); const mix = nodeProxy( MathNode, MathNode.MIX ); const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) ); const saturate = ( value ) => clamp( value ); @@ -58015,6 +58711,10 @@ const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD ); const mixElement = ( t, e1, e2 ) => mix( e1, e2, t ); const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x ); +addNodeElement( 'all', all ); +addNodeElement( 'any', any ); +addNodeElement( 'equals', equals ); + addNodeElement( 'radians', radians ); addNodeElement( 'degrees', degrees ); addNodeElement( 'exp', exp ); @@ -58036,6 +58736,7 @@ addNodeElement( 'atan', atan ); addNodeElement( 'abs', abs ); addNodeElement( 'sign', sign ); addNodeElement( 'length', length ); +addNodeElement( 'lengthSq', lengthSq ); addNodeElement( 'negate', negate ); addNodeElement( 'oneMinus', oneMinus ); addNodeElement( 'dFdx', dFdx ); @@ -58289,7 +58990,7 @@ class TextureNode extends UniformNode { } - updateReference( /*frame*/ ) { + setReference( /*state*/ ) { return this.value; @@ -58598,440 +59299,428 @@ addNodeElement( 'texture', texture ); addNodeClass( 'TextureNode', TextureNode ); -class ReferenceNode extends Node { - - constructor( property, uniformType, object = null ) { +class BufferNode extends UniformNode { - super(); + constructor( value, bufferType, bufferCount = 0 ) { - this.property = property; - this.index = null; + super( value, bufferType ); - this.uniformType = uniformType; + this.isBufferNode = true; - this.object = object; - this.reference = null; + this.bufferType = bufferType; + this.bufferCount = bufferCount; - this.node = null; + } - this.updateType = NodeUpdateType.OBJECT; + getInputType( /*builder*/ ) { - this.setNodeType( uniformType ); + return 'buffer'; } - updateReference( frame ) { +} - this.reference = this.object !== null ? this.object : frame.object; +const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - return this.reference; +addNodeClass( 'BufferNode', BufferNode ); - } +class UniformsElementNode extends ArrayElementNode { - setIndex( index ) { + constructor( arrayBuffer, indexNode ) { - this.index = index; + super( arrayBuffer, indexNode ); - return this; + this.isArrayBufferElementNode = true; } - getIndex() { + getNodeType( builder ) { - return this.index; + return this.node.getElementType( builder ); } - setNodeType( uniformType ) { + generate( builder ) { - let node = null; + const snippet = super.generate( builder ); + const type = this.getNodeType(); - if ( uniformType === 'texture' ) { + return builder.format( snippet, 'vec4', type ); - node = texture( null ); + } - } else { +} - node = uniform( uniformType ); +class UniformsNode extends BufferNode { - } + constructor( value, elementType = null ) { - this.node = node; + super( null, 'vec4' ); - } + this.array = value; + this.elementType = elementType; - getNodeType( builder ) { + this._elementType = null; + this._elementLength = 0; - return this.node.getNodeType( builder ); + this.updateType = NodeUpdateType.RENDER; - } + this.isArrayBufferNode = true; - update( /*frame*/ ) { + } - let value = this.reference[ this.property ]; + getElementType() { - if ( this.index !== null ) { + return this.elementType || this._elementType; - value = value[ this.index ]; + } - } + getElementLength() { - this.node.value = value; + return this._elementLength; } - setup( /*builder*/ ) { + update( /*frame*/ ) { - return this.node; + const { array, value } = this; - } + const elementLength = this.getElementLength(); + const elementType = this.getElementType(); -} + if ( elementLength === 1 ) { -const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); -const referenceIndex = ( name, index, type, object ) => nodeObject( new ReferenceNode( name, type, object ).setIndex( index ) ); + for ( let i = 0; i < array.length; i ++ ) { -addNodeClass( 'ReferenceNode', ReferenceNode ); + const index = i * 4; -class MaterialReferenceNode extends ReferenceNode { + value[ index ] = array[ i ]; - constructor( property, inputType, material = null ) { + } - super( property, inputType, material ); + } else if ( elementType === 'color' ) { - this.material = material; + for ( let i = 0; i < array.length; i ++ ) { - //this.updateType = NodeUpdateType.RENDER; + const index = i * 4; + const vector = array[ i ]; - } + value[ index ] = vector.r; + value[ index + 1 ] = vector.g; + value[ index + 2 ] = vector.b || 0; + //value[ index + 3 ] = vector.a || 0; - /*setNodeType( node ) { + } - super.setNodeType( node ); + } else { - this.node.groupNode = renderGroup; + for ( let i = 0; i < array.length; i ++ ) { - }*/ + const index = i * 4; + const vector = array[ i ]; - updateReference( frame ) { + value[ index ] = vector.x; + value[ index + 1 ] = vector.y; + value[ index + 2 ] = vector.z || 0; + value[ index + 3 ] = vector.w || 0; - this.reference = this.material !== null ? this.material : frame.material; + } - return this.reference; + } } setup( builder ) { - const material = this.material !== null ? this.material : builder.material; + const length = this.array.length; - this.node.value = material[ this.property ]; + this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType; + this._elementLength = builder.getTypeLength( this._elementType ); + + this.value = new Float32Array( length * 4 ); + this.bufferCount = length; return super.setup( builder ); } -} + element( indexNode ) { -const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); + return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) ); -addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); - -class Object3DNode extends Node { + } - constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { +} - super(); +const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) ); - this.scope = scope; - this.object3d = object3d; +addNodeClass( 'UniformsNode', UniformsNode ); - this.updateType = NodeUpdateType.OBJECT; +class ReferenceElementNode extends ArrayElementNode { - this._uniformNode = new UniformNode( null ); + constructor( referenceNode, indexNode ) { - } + super( referenceNode, indexNode ); - getNodeType() { + this.referenceNode = referenceNode; - const scope = this.scope; + this.isReferenceElementNode = true; - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - return 'mat4'; + getNodeType() { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + return this.referenceNode.uniformType; - return 'mat3'; + } - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + generate( builder ) { - return 'vec3'; + const snippet = super.generate( builder ); + const arrayType = this.referenceNode.getNodeType(); + const elementType = this.getNodeType(); - } + return builder.format( snippet, arrayType, elementType ); } - update( frame ) { +} - const object = this.object3d; - const uniformNode = this._uniformNode; - const scope = this.scope; +class ReferenceNode extends Node { - if ( scope === Object3DNode.VIEW_MATRIX ) { + constructor( property, uniformType, object = null, count = null ) { - uniformNode.value = object.modelViewMatrix; + super(); - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + this.property = property; + this.uniformType = uniformType; + this.object = object; + this.count = count; - uniformNode.value = object.normalMatrix; + this.properties = property.split( '.' ); + this.reference = null; + this.node = null; - } else if ( scope === Object3DNode.WORLD_MATRIX ) { + this.updateType = NodeUpdateType.OBJECT; - uniformNode.value = object.matrixWorld; + } - } else if ( scope === Object3DNode.POSITION ) { + element( indexNode ) { - uniformNode.value = uniformNode.value || new Vector3(); + return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) ); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } - } else if ( scope === Object3DNode.SCALE ) { + setNodeType( uniformType ) { - uniformNode.value = uniformNode.value || new Vector3(); + let node = null; - uniformNode.value.setFromMatrixScale( object.matrixWorld ); + if ( this.count !== null ) { - } else if ( scope === Object3DNode.DIRECTION ) { + node = buffer( null, uniformType, this.count ); - uniformNode.value = uniformNode.value || new Vector3(); + } else if ( Array.isArray( this.getValueFromReference() ) ) { - object.getWorldDirection( uniformNode.value ); + node = uniforms( null, uniformType ); - } else if ( scope === Object3DNode.VIEW_POSITION ) { + } else if ( uniformType === 'texture' ) { - const camera = frame.camera; + node = texture( null ); - uniformNode.value = uniformNode.value || new Vector3(); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } else { - uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); + node = uniform( null, uniformType ); } + this.node = node; + } - generate( builder ) { + getNodeType( builder ) { - const scope = this.scope; + return this.node.getNodeType( builder ); - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - this._uniformNode.nodeType = 'mat4'; + getValueFromReference( object = this.reference ) { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + const { properties } = this; - this._uniformNode.nodeType = 'mat3'; + let value = object[ properties[ 0 ] ]; - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + for ( let i = 1; i < properties.length; i ++ ) { - this._uniformNode.nodeType = 'vec3'; + value = value[ properties[ i ] ]; } - return this._uniformNode.build( builder ); + return value; } - serialize( data ) { + setReference( state ) { - super.serialize( data ); + this.reference = this.object !== null ? this.object : state.object; - data.scope = this.scope; + return this.reference; } - deserialize( data ) { + setup() { - super.deserialize( data ); + this.updateValue(); - this.scope = data.scope; + return this.node; } -} + update( /*frame*/ ) { -Object3DNode.VIEW_MATRIX = 'viewMatrix'; -Object3DNode.NORMAL_MATRIX = 'normalMatrix'; -Object3DNode.WORLD_MATRIX = 'worldMatrix'; -Object3DNode.POSITION = 'position'; -Object3DNode.SCALE = 'scale'; -Object3DNode.VIEW_POSITION = 'viewPosition'; -Object3DNode.DIRECTION = 'direction'; + this.updateValue(); -const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION ); -const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX ); -const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX ); -const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ); -const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION ); -const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE ); -const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ); + } -addNodeClass( 'Object3DNode', Object3DNode ); + updateValue() { -//const cameraGroup = sharedUniformGroup( 'camera' ); + if ( this.node === null ) this.setNodeType( this.uniformType ); -class CameraNode extends Object3DNode { + const value = this.getValueFromReference(); - constructor( scope = CameraNode.POSITION ) { + if ( Array.isArray( value ) ) { - super( scope ); + this.node.array = value; - this.updateType = NodeUpdateType.RENDER; + } else { - //this._uniformNode.groupNode = cameraGroup; + this.node.value = value; + + } } - getNodeType( builder ) { +} - const scope = this.scope; +const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); +const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) ); - if ( scope === CameraNode.PROJECTION_MATRIX ) { +addNodeClass( 'ReferenceNode', ReferenceNode ); - return 'mat4'; +class MaterialReferenceNode extends ReferenceNode { - } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + constructor( property, inputType, material = null ) { - return 'float'; + super( property, inputType, material ); - } + this.material = material; - return super.getNodeType( builder ); + //this.updateType = NodeUpdateType.RENDER; } - update( frame ) { + /*setNodeType( node ) { - const camera = frame.camera; - const uniformNode = this._uniformNode; - const scope = this.scope; + super.setNodeType( node ); - //cameraGroup.needsUpdate = true; + this.node.groupNode = renderGroup; - if ( scope === CameraNode.VIEW_MATRIX ) { + }*/ - uniformNode.value = camera.matrixWorldInverse; + setReference( state ) { - } else if ( scope === CameraNode.PROJECTION_MATRIX ) { + this.reference = this.material !== null ? this.material : state.material; - uniformNode.value = camera.projectionMatrix; + return this.reference; - } else if ( scope === CameraNode.NEAR ) { + } - uniformNode.value = camera.near; +} - } else if ( scope === CameraNode.FAR ) { +const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); - uniformNode.value = camera.far; +addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); - } else if ( scope === CameraNode.LOG_DEPTH ) { +class Object3DNode extends Node { - uniformNode.value = 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ); + constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { - } else { + super(); - this.object3d = camera; + this.scope = scope; + this.object3d = object3d; - super.update( frame ); + this.updateType = NodeUpdateType.OBJECT; - } + this._uniformNode = new UniformNode( null ); } - generate( builder ) { + getNodeType() { const scope = this.scope; - if ( scope === CameraNode.PROJECTION_MATRIX ) { - - this._uniformNode.nodeType = 'mat4'; - - } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { - this._uniformNode.nodeType = 'float'; + return 'mat4'; - } + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - return super.generate( builder ); + return 'mat3'; - } + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { -} + return 'vec3'; -CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; -CameraNode.NEAR = 'near'; -CameraNode.FAR = 'far'; -CameraNode.LOG_DEPTH = 'logDepth'; + } -const cameraProjectionMatrix = label( nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ), 'projectionMatrix' ); -const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); -const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); -const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); -const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX ); -const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX ); -const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX ); -const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION ); + } -addNodeClass( 'CameraNode', CameraNode ); + update( frame ) { -class ModelNode extends Object3DNode { + const object = this.object3d; + const uniformNode = this._uniformNode; + const scope = this.scope; - constructor( scope = ModelNode.VIEW_MATRIX ) { + if ( scope === Object3DNode.VIEW_MATRIX ) { - super( scope ); + uniformNode.value = object.modelViewMatrix; - } + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - update( frame ) { + uniformNode.value = object.normalMatrix; - this.object3d = frame.object; + } else if ( scope === Object3DNode.WORLD_MATRIX ) { - super.update( frame ); + uniformNode.value = object.matrixWorld; - } + } else if ( scope === Object3DNode.POSITION ) { -} + uniformNode.value = uniformNode.value || new Vector3(); -const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION ); -const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' ); -const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX ); -const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX ); -const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION ); -const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE ); -const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION ); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); -addNodeClass( 'ModelNode', ModelNode ); + } else if ( scope === Object3DNode.SCALE ) { -class NormalNode extends Node { + uniformNode.value = uniformNode.value || new Vector3(); - constructor( scope = NormalNode.LOCAL ) { + uniformNode.value.setFromMatrixScale( object.matrixWorld ); - super( 'vec3' ); + } else if ( scope === Object3DNode.DIRECTION ) { - this.scope = scope; + uniformNode.value = uniformNode.value || new Vector3(); - } + object.getWorldDirection( uniformNode.value ); - isGlobal() { + } else if ( scope === Object3DNode.VIEW_POSITION ) { - return true; + const camera = frame.camera; - } + uniformNode.value = uniformNode.value || new Vector3(); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); - getHash( /*builder*/ ) { + uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); - return `normal-${this.scope}`; + } } @@ -59039,30 +59728,250 @@ class NormalNode extends Node { const scope = this.scope; - let outputNode = null; - - if ( scope === NormalNode.GEOMETRY ) { - - outputNode = attribute( 'normal', 'vec3' ); - - } else if ( scope === NormalNode.LOCAL ) { + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { - outputNode = varying( normalGeometry ); + this._uniformNode.nodeType = 'mat4'; - } else if ( scope === NormalNode.VIEW ) { + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { - const vertexNode = modelNormalMatrix.mul( normalLocal ); - outputNode = normalize( varying( vertexNode ) ); + this._uniformNode.nodeType = 'mat3'; - } else if ( scope === NormalNode.WORLD ) { + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { - // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView ) - const vertexNode = normalView.transformDirection( cameraViewMatrix ); - outputNode = normalize( varying( vertexNode ) ); + this._uniformNode.nodeType = 'vec3'; } - return outputNode.build( builder, this.getNodeType( builder ) ); + return this._uniformNode.build( builder ); + + } + + serialize( data ) { + + super.serialize( data ); + + data.scope = this.scope; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.scope = data.scope; + + } + +} + +Object3DNode.VIEW_MATRIX = 'viewMatrix'; +Object3DNode.NORMAL_MATRIX = 'normalMatrix'; +Object3DNode.WORLD_MATRIX = 'worldMatrix'; +Object3DNode.POSITION = 'position'; +Object3DNode.SCALE = 'scale'; +Object3DNode.VIEW_POSITION = 'viewPosition'; +Object3DNode.DIRECTION = 'direction'; + +const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION ); +const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX ); +const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX ); +const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ); +const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION ); +const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE ); +const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ); + +addNodeClass( 'Object3DNode', Object3DNode ); + +//const cameraGroup = sharedUniformGroup( 'camera' ); + +class CameraNode extends Object3DNode { + + constructor( scope = CameraNode.POSITION ) { + + super( scope ); + + this.updateType = NodeUpdateType.RENDER; + + //this._uniformNode.groupNode = cameraGroup; + + } + + getNodeType( builder ) { + + const scope = this.scope; + + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + return 'mat4'; + + } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + + return 'float'; + + } + + return super.getNodeType( builder ); + + } + + update( frame ) { + + const camera = frame.camera; + const uniformNode = this._uniformNode; + const scope = this.scope; + + //cameraGroup.needsUpdate = true; + + if ( scope === CameraNode.VIEW_MATRIX ) { + + uniformNode.value = camera.matrixWorldInverse; + + } else if ( scope === CameraNode.PROJECTION_MATRIX ) { + + uniformNode.value = camera.projectionMatrix; + + } else if ( scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + uniformNode.value = camera.projectionMatrixInverse; + + } else if ( scope === CameraNode.NEAR ) { + + uniformNode.value = camera.near; + + } else if ( scope === CameraNode.FAR ) { + + uniformNode.value = camera.far; + + } else if ( scope === CameraNode.LOG_DEPTH ) { + + uniformNode.value = 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ); + + } else { + + this.object3d = camera; + + super.update( frame ); + + } + + } + + generate( builder ) { + + const scope = this.scope; + + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + this._uniformNode.nodeType = 'mat4'; + + } else if ( scope === CameraNode.NEAR || scope === CameraNode.FAR || scope === CameraNode.LOG_DEPTH ) { + + this._uniformNode.nodeType = 'float'; + + } + + return super.generate( builder ); + + } + +} + +CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; +CameraNode.PROJECTION_MATRIX_INVERSE = 'projectionMatrixInverse'; +CameraNode.NEAR = 'near'; +CameraNode.FAR = 'far'; +CameraNode.LOG_DEPTH = 'logDepth'; + +const cameraProjectionMatrix = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ); +const cameraProjectionMatrixInverse = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX_INVERSE ); +const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); +const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); +const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); +const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX ); +const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX ); +const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX ); +const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION ); + +addNodeClass( 'CameraNode', CameraNode ); + +class ModelNode extends Object3DNode { + + constructor( scope = ModelNode.VIEW_MATRIX ) { + + super( scope ); + + } + + update( frame ) { + + this.object3d = frame.object; + + super.update( frame ); + + } + +} + +const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION ); +const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' ); +const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX ); +const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX ); +const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION ); +const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE ); +const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION ); + +addNodeClass( 'ModelNode', ModelNode ); + +class NormalNode extends Node { + + constructor( scope = NormalNode.LOCAL ) { + + super( 'vec3' ); + + this.scope = scope; + + } + + isGlobal() { + + return true; + + } + + getHash( /*builder*/ ) { + + return `normal-${this.scope}`; + + } + + generate( builder ) { + + const scope = this.scope; + + let outputNode = null; + + if ( scope === NormalNode.GEOMETRY ) { + + outputNode = attribute( 'normal', 'vec3' ); + + } else if ( scope === NormalNode.LOCAL ) { + + outputNode = varying( normalGeometry ); + + } else if ( scope === NormalNode.VIEW ) { + + const vertexNode = modelNormalMatrix.mul( normalLocal ); + outputNode = normalize( varying( vertexNode ) ); + + } else if ( scope === NormalNode.WORLD ) { + + // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView ) + const vertexNode = normalView.transformDirection( cameraViewMatrix ); + outputNode = normalize( varying( vertexNode ) ); + + } + + return outputNode.build( builder, this.getNodeType( builder ) ); } @@ -59322,11 +60231,11 @@ class MaterialNode extends Node { } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) { - const iridescenceThicknessMaximum = reference( 1, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange ); if ( material.iridescenceThicknessMap ) { - const iridescenceThicknessMinimum = reference( 0, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange ); node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum ); @@ -59595,12 +60504,14 @@ class BufferAttributeNode extends InputNode { const nodeType = this.getNodeType( builder ); - const nodeUniform = builder.getBufferAttributeFromNode( this, nodeType ); - const propertyName = builder.getPropertyName( nodeUniform ); + const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType ); + const propertyName = builder.getPropertyName( nodeAttribute ); let output = null; - if ( builder.shaderStage === 'vertex' ) { + if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) { + + this.name = propertyName; output = propertyName; @@ -59713,31 +60624,6 @@ const instance = nodeProxy( InstanceNode ); addNodeClass( 'InstanceNode', InstanceNode ); -class BufferNode extends UniformNode { - - constructor( value, bufferType, bufferCount = 0 ) { - - super( value, bufferType ); - - this.isBufferNode = true; - - this.bufferType = bufferType; - this.bufferCount = bufferCount; - - } - - getInputType( /*builder*/ ) { - - return 'buffer'; - - } - -} - -const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - -addNodeClass( 'BufferNode', BufferNode ); - class TangentNode extends Node { constructor( scope = TangentNode.LOCAL ) { @@ -59779,13 +60665,19 @@ class TangentNode extends Node { outputNode = attribute( 'tangent', 'vec4' ); + if ( builder.geometry.hasAttribute( 'tangent' ) === false ) { + + builder.geometry.computeTangents(); + + } + } else if ( scope === TangentNode.LOCAL ) { outputNode = varying( tangentGeometry.xyz ); } else if ( scope === TangentNode.VIEW ) { - const vertexNode = modelViewMatrix.mul( tangentLocal ).xyz; + const vertexNode = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz; outputNode = normalize( varying( vertexNode ) ); } else if ( scope === TangentNode.WORLD ) { @@ -59833,11 +60725,12 @@ addNodeClass( 'TangentNode', TangentNode ); class SkinningNode extends Node { - constructor( skinnedMesh ) { + constructor( skinnedMesh, useReference = false ) { super( 'void' ); this.skinnedMesh = skinnedMesh; + this.useReference = useReference; this.updateType = NodeUpdateType.OBJECT; @@ -59846,9 +60739,25 @@ class SkinningNode extends Node { this.skinIndexNode = attribute( 'skinIndex', 'uvec4' ); this.skinWeightNode = attribute( 'skinWeight', 'vec4' ); - this.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); - this.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); - this.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode; + + if ( useReference ) { + + bindMatrixNode = reference( 'bindMatrix', 'mat4' ); + bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' ); + boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length ); + + } else { + + bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); + bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); + boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + + } + + this.bindMatrixNode = bindMatrixNode; + this.bindMatrixInverseNode = bindMatrixInverseNode; + this.boneMatricesNode = boneMatricesNode; } @@ -59910,18 +60819,214 @@ class SkinningNode extends Node { } - update() { + update( frame ) { + + const object = this.useReference ? frame.object : this.skinnedMesh; - this.skinnedMesh.skeleton.update(); + object.skeleton.update(); } } -const skinning = nodeProxy( SkinningNode ); +const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) ); +const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) ); addNodeClass( 'SkinningNode', SkinningNode ); +class LoopNode extends Node { + + constructor( params = [] ) { + + super(); + + this.params = params; + + } + + getVarName( index ) { + + return String.fromCharCode( 'i'.charCodeAt() + index ); + + } + + getProperties( builder ) { + + const properties = builder.getNodeProperties( this ); + + if ( properties.stackNode !== undefined ) return properties; + + // + + const inputs = {}; + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + const param = this.params[ i ]; + + const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); + const type = ( param.isNode !== true && param.type ) || 'int'; + + inputs[ name ] = expression( name, type ); + + } + + properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); + properties.stackNode = builder.removeStack(); + + return properties; + + } + + getNodeType( builder ) { + + const { returnsNode } = this.getProperties( builder ); + + return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; + + } + + setup( builder ) { + + // setup properties + + this.getProperties( builder ); + + } + + generate( builder ) { + + const properties = this.getProperties( builder ); + + const contextData = { tempWrite: false }; + + const params = this.params; + const stackNode = properties.stackNode; + + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { + + const param = params[ i ]; + + let start = null, end = null, name = null, type = null, condition = null, update = null; + + if ( param.isNode ) { + + type = 'int'; + name = this.getVarName( i ); + start = '0'; + end = param.build( builder, type ); + condition = '<'; + + } else { + + type = param.type || 'int'; + name = param.name || this.getVarName( i ); + start = param.start; + end = param.end; + condition = param.condition; + update = param.update; + + if ( typeof start === 'number' ) start = start.toString(); + else if ( start && start.isNode ) start = start.build( builder, type ); + + if ( typeof end === 'number' ) end = end.toString(); + else if ( end && end.isNode ) end = end.build( builder, type ); + + if ( start !== undefined && end === undefined ) { + + start = start + ' - 1'; + end = '0'; + condition = '>='; + + } else if ( end !== undefined && start === undefined ) { + + start = '0'; + condition = '<'; + + } + + if ( condition === undefined ) { + + if ( Number( start ) > Number( end ) ) { + + condition = '>='; + + } else { + + condition = '<'; + + } + + } + + } + + const internalParam = { start, end, condition }; + + // + + const startSnippet = internalParam.start; + const endSnippet = internalParam.end; + + let declarationSnippet = ''; + let conditionalSnippet = ''; + let updateSnippet = ''; + + if ( ! update ) { + + if ( type === 'int' || type === 'uint' ) { + + if ( condition.includes( '<' ) ) update = '++'; + else update = '--'; + + } else { + + if ( condition.includes( '<' ) ) update = '+= 1.'; + else update = '-= 1.'; + + } + + } + + declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; + + conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; + updateSnippet += name + ' ' + update; + + const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; + + builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); + + } + + const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); + + const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; + + builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); + + } + + builder.addFlowTab(); + + return returnsSnippet; + + } + +} + +const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); +const Continue = () => expression( 'continue' ).append(); +const Break = () => expression( 'break' ).append(); + +addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); + +addNodeClass( 'LoopNode', LoopNode ); + const morphTextures = new WeakMap(); const morphVec4 = new Vector4(); @@ -60097,10 +61202,9 @@ class MorphNode extends Node { const width = int( size.width ); - for ( let i = 0; i < morphTargetsCount; i ++ ) { + loop( morphTargetsCount, ( { i } ) => { - const influence = referenceIndex( 'morphTargetInfluences', i, 'float' ); - const depth = int( i ); + const influence = reference( 'morphTargetInfluences', 'float' ).element( i ); if ( hasMorphPosition === true ) { @@ -60109,7 +61213,7 @@ class MorphNode extends Node { influence, stride, width, - depth, + depth: i, offset: int( 0 ) } ) ); @@ -60122,13 +61226,13 @@ class MorphNode extends Node { influence, stride, width, - depth, + depth: i, offset: int( 1 ) } ) ); } - } + } ); } @@ -60150,7 +61254,7 @@ class MorphNode extends Node { } -const morph = nodeProxy( MorphNode ); +const morphReference = nodeProxy( MorphNode ); addNodeClass( 'MorphNode', MorphNode ); @@ -60252,7 +61356,7 @@ class LightingNode extends Node { addNodeClass( 'LightingNode', LightingNode ); -let depthMaterial = null; +let overrideMaterial = null; class AnalyticLightNode extends LightingNode { @@ -60294,7 +61398,13 @@ class AnalyticLightNode extends LightingNode { if ( shadowNode === null ) { - if ( depthMaterial === null ) depthMaterial = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ); + if ( overrideMaterial === null ) { + + overrideMaterial = builder.createNodeMaterial(); + overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); + overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode + + } const shadow = this.light.shadow; const rtt = builder.getRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); @@ -60382,8 +61492,10 @@ class AnalyticLightNode extends LightingNode { */ // + const shadowColor = texture( rtt.texture, shadowCoord ); + this.rtt = rtt; - this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode ) ); + this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) ) ); this.shadowNode = shadowNode; @@ -60409,7 +61521,7 @@ class AnalyticLightNode extends LightingNode { const currentOverrideMaterial = scene.overrideMaterial; - scene.overrideMaterial = depthMaterial; + scene.overrideMaterial = overrideMaterial; rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height ); @@ -60635,7 +61747,7 @@ class LightsNode extends Node { } const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) ); -const lightNodes = nodeProxy( LightsNode ); +const lightsNode = nodeProxy( LightsNode ); function addLightNode( lightClass, lightNodeClass ) { @@ -61013,8 +62125,6 @@ class ViewportNode extends Node { const scope = this.scope; - if ( scope === ViewportNode.COORDINATE ) return; - let output = null; if ( scope === ViewportNode.RESOLUTION ) { @@ -61087,7 +62197,7 @@ const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIG addNodeClass( 'ViewportNode', ViewportNode ); -const _size$1 = new Vector2(); +const _size$2 = new Vector2(); class ViewportTextureNode extends TextureNode { @@ -61113,16 +62223,16 @@ class ViewportTextureNode extends TextureNode { updateBefore( frame ) { const renderer = frame.renderer; - renderer.getDrawingBufferSize( _size$1 ); + renderer.getDrawingBufferSize( _size$2 ); // const framebufferTexture = this.value; - if ( framebufferTexture.image.width !== _size$1.width || framebufferTexture.image.height !== _size$1.height ) { + if ( framebufferTexture.image.width !== _size$2.width || framebufferTexture.image.height !== _size$2.height ) { - framebufferTexture.image.width = _size$1.width; - framebufferTexture.image.height = _size$1.height; + framebufferTexture.image.width = _size$2.width; + framebufferTexture.image.height = _size$2.height; framebufferTexture.needsUpdate = true; } @@ -61163,9 +62273,6 @@ class ViewportDepthTextureNode extends ViewportTextureNode { if ( sharedDepthbuffer === null ) { sharedDepthbuffer = new DepthTexture(); - sharedDepthbuffer.minFilter = NearestMipmapNearestFilter; - sharedDepthbuffer.type = UnsignedIntType; - sharedDepthbuffer.format = DepthFormat; } @@ -61271,6 +62378,162 @@ depthPixel.assign = ( value ) => depthPixelBase( value ); addNodeClass( 'ViewportDepthNode', ViewportDepthNode ); +class ClippingNode extends Node { + + constructor( scope = ClippingNode.DEFAULT ) { + + super(); + + this.scope = scope; + + } + + setup( builder ) { + + super.setup( builder ); + + const clippingContext = builder.clippingContext; + const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext; + + const numClippingPlanes = globalClippingCount + localClippingCount; + const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes; + + if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) { + + return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); + + } else { + + return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); + + } + + } + + setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + const distanceToPlane = property( 'float', 'distanceToPlane' ); + const distanceGradient = property( 'float', 'distanceToGradient' ); + + const clipOpacity = property( 'float', 'clipOpacity' ); + + clipOpacity.assign( 1 ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) ); + + clipOpacity.equal( 0.0 ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const unionClipOpacity = property( 'float', 'unionclipOpacity' ); + + unionClipOpacity.assign( 1 ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() ); + + } ); + + clipOpacity.mulAssign( unionClipOpacity.oneMinus() ); + + } + + diffuseColor.a.mulAssign( clipOpacity ); + + diffuseColor.a.equal( 0.0 ).discard(); + + } )(); + + } + + setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + positionView.dot( plane.xyz ).greaterThan( plane.w ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const clipped = property( 'bool', 'clipped' ); + + clipped.assign( true ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) ); + + } ); + + clipped.discard(); + } + + } )(); + + } + +} + +ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage'; +ClippingNode.DEFAULT = 'default'; + +const clipping = () => nodeObject( new ClippingNode() ); + +const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) ); + +class FrontFacingNode extends Node { + + constructor() { + + super( 'bool' ); + + this.isFrontFacingNode = true; + + } + + generate( builder ) { + + return builder.getFrontFacing(); + + } + +} + +const frontFacing = nodeImmutable( FrontFacingNode ); +const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); + +addNodeClass( 'FrontFacingNode', FrontFacingNode ); + const NodeMaterials = new Map(); class NodeMaterial extends ShaderMaterial { @@ -61304,6 +62567,7 @@ class NodeMaterial extends ShaderMaterial { this.positionNode = null; this.depthNode = null; + this.shadowNode = null; this.outputNode = null; @@ -61340,6 +62604,8 @@ class NodeMaterial extends ShaderMaterial { let resultNode; + const clippingNode = this.setupClipping( builder ); + if ( this.fragmentNode === null ) { if ( this.depthWrite === true ) this.setupDepth( builder ); @@ -61351,6 +62617,8 @@ class NodeMaterial extends ShaderMaterial { const outgoingLightNode = this.setupLighting( builder ); + if ( clippingNode !== null ) builder.stack.add( clippingNode ); + resultNode = this.setupOutput( builder, vec4( outgoingLightNode, diffuseColor.a ) ); // OUTPUT NODE @@ -61373,6 +62641,31 @@ class NodeMaterial extends ShaderMaterial { } + setupClipping( builder ) { + + const { globalClippingCount, localClippingCount } = builder.clippingContext; + + let result = null; + + if ( globalClippingCount || localClippingCount ) { + + if ( this.alphaToCoverage ) { + + // to be added to flow when the color/alpha value has been determined + result = clippingAlpha(); + + } else { + + builder.stack.add( clipping() ); + + } + + } + + return result; + + } + setupDepth( builder ) { const { renderer } = builder; @@ -61408,13 +62701,13 @@ class NodeMaterial extends ShaderMaterial { if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) { - morph( object ).append(); + morphReference( object ).append(); } if ( object.isSkinnedMesh === true ) { - skinning( object ).append(); + skinningReference( object ).append(); } @@ -61486,13 +62779,13 @@ class NodeMaterial extends ShaderMaterial { const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize(); - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } else { const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal; - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } @@ -61540,15 +62833,15 @@ class NodeMaterial extends ShaderMaterial { } - let lightsNode = this.lightsNode || builder.lightsNode; + let lightsN = this.lightsNode || builder.lightsNode; if ( materialLightsNode.length > 0 ) { - lightsNode = lightNodes( [ ...lightsNode.lightNodes, ...materialLightsNode ] ); + lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] ); } - return lightsNode; + return lightsN; } @@ -61747,6 +63040,7 @@ class NodeMaterial extends ShaderMaterial { this.positionNode = source.positionNode; this.depthNode = source.depthNode; + this.shadowNode = source.shadowNode; this.outputNode = source.outputNode; @@ -62106,23 +63400,45 @@ class CondNode extends Node { } - generate( builder ) { + generate( builder, output ) { const type = this.getNodeType( builder ); const context$1 = { tempWrite: false }; + const nodeData = builder.getDataFromNode( this ); + + if ( nodeData.nodeProperty !== undefined ) { + + return nodeData.nodeProperty; + + } + const { ifNode, elseNode } = this; - const needsProperty = ifNode.getNodeType( builder ) !== 'void' || ( elseNode && elseNode.getNodeType( builder ) !== 'void' ); - const nodeProperty = needsProperty ? property( type ).build( builder ) : ''; + const needsOutput = output !== 'void'; + const nodeProperty = needsOutput ? property( type ).build( builder ) : ''; + + nodeData.nodeProperty = nodeProperty; const nodeSnippet = context( this.condNode/*, context*/ ).build( builder, 'bool' ); builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab(); - let ifSnippet = context( this.ifNode, context$1 ).build( builder, type ); + let ifSnippet = context( ifNode, context$1 ).build( builder, type ); + + if ( ifSnippet ) { + + if ( needsOutput ) { - ifSnippet = needsProperty ? nodeProperty + ' = ' + ifSnippet + ';' : ifSnippet; + ifSnippet = nodeProperty + ' = ' + ifSnippet + ';'; + + } else { + + ifSnippet = 'return ' + ifSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' ); @@ -62131,7 +63447,20 @@ class CondNode extends Node { builder.addFlowCode( ' else {\n\n' ).addFlowTab(); let elseSnippet = context( elseNode, context$1 ).build( builder, type ); - elseSnippet = nodeProperty ? nodeProperty + ' = ' + elseSnippet + ';' : elseSnippet; + + if ( elseSnippet ) { + + if ( needsOutput ) { + + elseSnippet = nodeProperty + ' = ' + elseSnippet + ';'; + + } else { + + elseSnippet = 'return ' + elseSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' ); @@ -62141,7 +63470,7 @@ class CondNode extends Node { } - return nodeProperty; + return builder.format( nodeProperty, type, output ); } @@ -62344,6 +63673,8 @@ class NodeBuilder { this.fogNode = null; this.toneMappingNode = null; + this.clippingContext = null; + this.vertexShader = null; this.fragmentShader = null; this.computeShader = null; @@ -62722,7 +64053,7 @@ class NodeBuilder { isReference( type ) { - return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture'; + return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture'; } @@ -62732,12 +64063,6 @@ class NodeBuilder { } - /** @deprecated, r152 */ - getTextureEncodingFromMap( map ) { - return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - getTextureColorSpaceFromMap( map ) { let colorSpace; @@ -62781,7 +64106,7 @@ class NodeBuilder { getVectorType( type ) { if ( type === 'color' ) return 'vec3'; - if ( type === 'texture' ) return 'vec4'; + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) return 'vec4'; return type; @@ -62833,6 +64158,7 @@ class NodeBuilder { if ( vecNum !== null ) return Number( vecNum[ 1 ] ); if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; + if ( /mat2/.test( type ) === true ) return 4; if ( /mat3/.test( type ) === true ) return 9; if ( /mat4/.test( type ) === true ) return 16; @@ -63421,24 +64747,12 @@ class NodeBuilder { } - createNodeMaterial( type ) { + createNodeMaterial( type = 'NodeMaterial' ) { return createNodeMaterialFromType( type ); } - getPrimitiveType( type ) { - - let primitiveType; - - if ( type[ 0 ] === 'i' ) primitiveType = 'int'; - else if ( type[ 0 ] === 'u' ) primitiveType = 'uint'; - else primitiveType = 'float'; - - return primitiveType; - - } - format( snippet, fromType, toType ) { fromType = this.getVectorType( fromType ); @@ -63498,7 +64812,7 @@ class NodeBuilder { // convert a number value to vector type, e.g: // vec3( 1u ) -> vec3( float( 1u ) ) - snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`; + snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; } @@ -63559,7 +64873,7 @@ class NodeFrame { updateBeforeNode( node ) { const updateType = node.getUpdateBeforeType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -63567,9 +64881,11 @@ class NodeFrame { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.updateBefore( this ) !== false ) { - node.updateBefore( this ); + frameMap.set( node, this.frameId ); + + } } @@ -63579,9 +64895,11 @@ class NodeFrame { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.updateBefore( this ) !== false ) { - node.updateBefore( this ); + renderMap.set( node, this.renderId ); + + } } @@ -63596,7 +64914,7 @@ class NodeFrame { updateNode( node ) { const updateType = node.getUpdateType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -63604,9 +64922,11 @@ class NodeFrame { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.update( this ) !== false ) { + + frameMap.set( node, this.frameId ); - node.update( this ); + } } @@ -63616,9 +64936,11 @@ class NodeFrame { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.update( this ) !== false ) { + + renderMap.set( node, this.renderId ); - node.update( this ); + } } @@ -63770,6 +65092,85 @@ addNodeElement( 'hash', hash ); addNodeClass( 'HashNode', HashNode ); +// remapping functions https://iquilezles.org/articles/functions/ +const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); +const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); +const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); +const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); + + +addNodeElement( 'parabola', parabola ); +addNodeElement( 'gain', gain ); +addNodeElement( 'pcurve', pcurve ); +addNodeElement( 'sinc', sinc ); + +// https://github.com/cabbibo/glsl-tri-noise-3d + +const tri = tslFn( ( [ x ] ) => { + + return x.fract().sub( .5 ).abs(); + +} ); + +const tri3 = tslFn( ( [ p ] ) => { + + return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); + +} ); + +const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => { + + const p = vec3( p_immutable ).toVar(); + const z = float( 1.4 ).toVar(); + const rz = float( 0.0 ).toVar(); + const bp = vec3( p ).toVar(); + + loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { + + const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); + p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); + bp.mulAssign( 1.8 ); + z.mulAssign( 1.5 ); + p.mulAssign( 1.2 ); + + const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); + rz.addAssign( t.div( z ) ); + bp.addAssign( 0.14 ); + + } ); + + return rz; + +} ); + +// layouts + +tri.setLayout( { + name: 'tri', + type: 'float', + inputs: [ + { name: 'x', type: 'float' } + ] +} ); + +tri3.setLayout( { + name: 'tri3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); + +triNoise3D.setLayout( { + name: 'triNoise3D', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'spd', type: 'float' }, + { name: 'time', type: 'float' } + ] +} ); + let discardExpression; class DiscardNode extends CondNode { @@ -63882,197 +65283,6 @@ const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( f addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode ); -class LoopNode extends Node { - - constructor( params = [] ) { - - super(); - - this.params = params; - - } - - getVarName( index ) { - - return String.fromCharCode( 'i'.charCodeAt() + index ); - - } - - getProperties( builder ) { - - const properties = builder.getNodeProperties( this ); - - if ( properties.stackNode !== undefined ) return properties; - - // - - const inputs = {}; - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - const param = this.params[ i ]; - - const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); - const type = ( param.isNode !== true && param.type ) || 'int'; - - inputs[ name ] = expression( name, type ); - - } - - properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); - properties.stackNode = builder.removeStack(); - - return properties; - - } - - getNodeType( builder ) { - - const { returnsNode } = this.getProperties( builder ); - - return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; - - } - - setup( builder ) { - - // setup properties - - this.getProperties( builder ); - - } - - generate( builder ) { - - const properties = this.getProperties( builder ); - - const contextData = { tempWrite: false }; - - const params = this.params; - const stackNode = properties.stackNode; - - for ( let i = 0, l = params.length - 1; i < l; i ++ ) { - - const param = params[ i ]; - - let start = null, end = null, name = null, type = null, condition = null, update = null; - - if ( param.isNode ) { - - type = 'int'; - name = this.getVarName( i ); - start = '0'; - end = param.build( builder, type ); - condition = '<'; - - } else { - - type = param.type || 'int'; - name = param.name || this.getVarName( i ); - start = param.start; - end = param.end; - condition = param.condition; - update = param.update; - - if ( typeof start === 'number' ) start = start.toString(); - else if ( start && start.isNode ) start = start.build( builder, type ); - - if ( typeof end === 'number' ) end = end.toString(); - else if ( end && end.isNode ) end = end.build( builder, type ); - - if ( start !== undefined && end === undefined ) { - - start = start + ' - 1'; - end = '0'; - condition = '>='; - - } else if ( end !== undefined && start === undefined ) { - - start = '0'; - condition = '<'; - - } - - if ( condition === undefined ) { - - if ( Number( start ) > Number( end ) ) { - - condition = '>='; - - } else { - - condition = '<'; - - } - - } - - } - - const internalParam = { start, end, condition }; - - // - - const startSnippet = internalParam.start; - const endSnippet = internalParam.end; - - let declarationSnippet = ''; - let conditionalSnippet = ''; - let updateSnippet = ''; - - if ( ! update ) { - - if ( type === 'int' ) { - - if ( condition.includes( '<' ) ) update = '++'; - else update = '--'; - - } else { - - if ( condition.includes( '<' ) ) update = '+= 1'; - else update = '-= 1'; - - } - - } - - declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; - - conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; - updateSnippet += name + ' ' + update; - - const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; - - builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); - - } - - const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); - - const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; - - builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); - - } - - builder.addFlowTab(); - - return returnsSnippet; - - } - -} - -const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); - -addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); - -addNodeClass( 'LoopNode', LoopNode ); - class MatcapUVNode extends TempNode { constructor() { @@ -64364,17 +65574,9 @@ class RotateUVNode extends TempNode { const { uvNode, rotationNode, centerNode } = this; - const cosAngle = rotationNode.cos(); - const sinAngle = rotationNode.sin(); - const vector = uvNode.sub( centerNode ); - const rotatedVector = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( vector )? - vec2( cosAngle, sinAngle ).dot( vector ), - vec2( sinAngle.negate(), cosAngle ).dot( vector ) - ); - - return rotatedVector.add( centerNode ); + return vector.rotate( rotationNode ).add( centerNode ); } @@ -64386,6 +65588,62 @@ addNodeElement( 'rotateUV', rotateUV ); addNodeClass( 'RotateUVNode', RotateUVNode ); +class RotateNode extends TempNode { + + constructor( positionNode, rotationNode ) { + + super(); + + this.positionNode = positionNode; + this.rotationNode = rotationNode; + + } + + getNodeType( builder ) { + + return this.positionNode.getNodeType( builder ); + + } + + setup( builder ) { + + const { rotationNode, positionNode } = this; + + const nodeType = this.getNodeType( builder ); + + if ( nodeType === 'vec2' ) { + + const cosAngle = rotationNode.cos(); + const sinAngle = rotationNode.sin(); + + const rotationMatrix = mat2( + cosAngle, sinAngle, + sinAngle.negate(), cosAngle + ); + + return rotationMatrix.mul( positionNode ); + + } else { + + const rotation = rotationNode; + const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + + return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz; + + } + + } + +} + +const rotate = nodeProxy( RotateNode ); + +addNodeElement( 'rotate', rotate ); + +addNodeClass( 'RotateNode', RotateNode ); + class SpriteSheetUVNode extends Node { constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { @@ -64422,6 +65680,92 @@ const spritesheetUV = nodeProxy( SpriteSheetUVNode ); addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode ); +class StorageArrayElementNode extends ArrayElementNode { + + constructor( storageBufferNode, indexNode ) { + + super( storageBufferNode, indexNode ); + + this.isStorageArrayElementNode = true; + + } + + set storageBufferNode( value ) { + + this.node = value; + + } + + get storageBufferNode() { + + return this.node; + + } + + setup( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + if ( ! this.node.instanceIndex && this.node.bufferObject === true ) { + + builder.setupPBO( this.node ); + + } + + } + + return super.setup( builder ); + + } + + generate( builder, output ) { + + let snippet; + + const isAssignContext = builder.context.assign; + + // + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + const { node } = this; + + if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) { + + snippet = builder.generatePBO( this ); + + } else { + + snippet = node.build( builder ); + + } + + } else { + + snippet = super.generate( builder ); + + } + + if ( isAssignContext !== true ) { + + const type = this.getNodeType( builder ); + + snippet = builder.format( snippet, type, output ); + + } + + return snippet; + + } + +} + +const storageElement = nodeProxy( StorageArrayElementNode ); + +addNodeElement( 'storageElement', storageElement ); + +addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode ); + class TriplanarTexturesNode extends Node { constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { @@ -64476,6 +65820,225 @@ addNodeElement( 'triplanarTexture', triplanarTexture ); addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode ); +const _reflectorPlane = new Plane(); +const _normal = new Vector3(); +const _reflectorWorldPosition = new Vector3(); +const _cameraWorldPosition = new Vector3(); +const _rotationMatrix = new Matrix4(); +const _lookAtPosition = new Vector3( 0, 0, - 1 ); +const clipPlane = new Vector4(); + +const _view = new Vector3(); +const _target = new Vector3(); +const _q = new Vector4(); + +const _size$1 = new Vector2(); + +const _defaultRT = new RenderTarget(); +const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y ); + +let _inReflector = false; + +class ReflectorNode extends TextureNode { + + constructor( parameters = {} ) { + + super( _defaultRT.texture, _defaultUV ); + + const { + target = new Object3D(), + resolution = 1, + generateMipmaps = false, + bounces = true + } = parameters; + + // + + this.target = target; + this.resolution = resolution; + this.generateMipmaps = generateMipmaps; + this.bounces = bounces; + + this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; + + this.virtualCameras = new WeakMap(); + this.renderTargets = new WeakMap(); + + + } + + _updateResolution( renderTarget, renderer ) { + + const resolution = this.resolution; + + renderer.getDrawingBufferSize( _size$1 ); + + renderTarget.setSize( Math.round( _size$1.width * resolution ), Math.round( _size$1.height * resolution ) ); + + } + + setup( builder ) { + + this._updateResolution( _defaultRT, builder.renderer ); + + return super.setup( builder ); + + } + + getTextureNode() { + + return this.textureNode; + + } + + getVirtualCamera( camera ) { + + let virtualCamera = this.virtualCameras.get( camera ); + + if ( virtualCamera === undefined ) { + + virtualCamera = camera.clone(); + + this.virtualCameras.set( camera, virtualCamera ); + + } + + return virtualCamera; + + } + + getRenderTarget( camera ) { + + let renderTarget = this.renderTargets.get( camera ); + + if ( renderTarget === undefined ) { + + renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); + + if ( this.generateMipmaps === true ) { + + renderTarget.texture.minFilter = LinearMipMapLinearFilter; + renderTarget.texture.generateMipmaps = true; + + } + + this.renderTargets.set( camera, renderTarget ); + + } + + return renderTarget; + + } + + updateBefore( frame ) { + + if ( this.bounces === false && _inReflector ) return false; + + _inReflector = true; + + const { scene, camera, renderer, material } = frame; + const { target } = this; + + const virtualCamera = this.getVirtualCamera( camera ); + const renderTarget = this.getRenderTarget( virtualCamera ); + + renderer.getDrawingBufferSize( _size$1 ); + + this._updateResolution( renderTarget, renderer ); + + // + + _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); + _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); + + _rotationMatrix.extractRotation( target.matrixWorld ); + + _normal.set( 0, 0, 1 ); + _normal.applyMatrix4( _rotationMatrix ); + + _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); + + // Avoid rendering when reflector is facing away + + if ( _view.dot( _normal ) > 0 ) return; + + _view.reflect( _normal ).negate(); + _view.add( _reflectorWorldPosition ); + + _rotationMatrix.extractRotation( camera.matrixWorld ); + + _lookAtPosition.set( 0, 0, - 1 ); + _lookAtPosition.applyMatrix4( _rotationMatrix ); + _lookAtPosition.add( _cameraWorldPosition ); + + _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); + _target.reflect( _normal ).negate(); + _target.add( _reflectorWorldPosition ); + + // + + virtualCamera.coordinateSystem = camera.coordinateSystem; + virtualCamera.position.copy( _view ); + virtualCamera.up.set( 0, 1, 0 ); + virtualCamera.up.applyMatrix4( _rotationMatrix ); + virtualCamera.up.reflect( _normal ); + virtualCamera.lookAt( _target ); + + virtualCamera.near = camera.near; + virtualCamera.far = camera.far; + + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); + + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); + _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); + + clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); + + const projectionMatrix = virtualCamera.projectionMatrix; + + _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; + _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; + _q.z = - 1.0; + _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; + + // Calculate the scaled plane vector + clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); + + const clipBias = 0; + + // Replacing the third row of the projection matrix + projectionMatrix.elements[ 2 ] = clipPlane.x; + projectionMatrix.elements[ 6 ] = clipPlane.y; + projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias; + projectionMatrix.elements[ 14 ] = clipPlane.w; + + // + + this.value = renderTarget.texture; + + material.visible = false; + + const currentRenderTarget = renderer.getRenderTarget(); + + renderer.setRenderTarget( renderTarget ); + + renderer.render( scene, virtualCamera ); + + renderer.setRenderTarget( currentRenderTarget ); + + material.visible = true; + + _inReflector = false; + + } + +} + +const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); + class BitangentNode extends Node { constructor( scope = BitangentNode.LOCAL ) { @@ -64556,6 +66119,11 @@ const transformedBitangentWorld = normalize( transformedBitangentView.transformD addNodeClass( 'BitangentNode', BitangentNode ); +const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); + +const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/; +const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) ); + class VertexColorNode extends AttributeNode { constructor( index = 0 ) { @@ -64779,6 +66347,11 @@ class StorageBufferNode extends BufferNode { this.isStorageBufferNode = true; + this.bufferObject = false; + + this._attribute = null; + this._varying = null; + } getInputType( /*builder*/ ) { @@ -64787,9 +66360,46 @@ class StorageBufferNode extends BufferNode { } + element( indexNode ) { + + return storageElement( this, indexNode ); + + } + + setBufferObject( value ) { + + this.bufferObject = value; + + return this; + + } + + generate( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) ) return super.generate( builder ); + + const nodeType = this.getNodeType( builder ); + + if ( this._attribute === null ) { + + this._attribute = bufferAttribute( this.value ); + this._varying = varying( this._attribute ); + + } + + + const output = this._varying.build( builder, nodeType ); + + builder.registerTransform( output, this._attribute ); + + return output; + + } + } const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); +const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); addNodeClass( 'StorageBufferNode', StorageBufferNode ); @@ -64805,15 +66415,68 @@ class TextureStoreNode extends TextureNode { } - getNodeType( /*builder*/ ) { + getInputType( /*builder*/ ) { + + return 'storageTexture'; + + } - return 'void'; + setup( builder ) { + + super.setup( builder ); + + const properties = builder.getNodeProperties( this ); + properties.storeNode = this.storeNode; + + } + + generate( builder, output ) { + + let snippet; + + if ( this.storeNode !== null ) { + + snippet = this.generateStore( builder ); + + } else { + + snippet = super.generate( builder, output ); + + } + + return snippet; + + } + + generateStore( builder ) { + + const properties = builder.getNodeProperties( this ); + + const { uvNode, storeNode } = properties; + + const textureProperty = super.generate( builder, 'property' ); + const uvSnippet = uvNode.build( builder, 'uvec2' ); + const storeSnippet = storeNode.build( builder, 'vec4' ); + + const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); + + builder.addLineFlowCode( snippet ); } } -const textureStore = nodeProxy( TextureStoreNode ); +const textureStoreBase = nodeProxy( TextureStoreNode ); + +const textureStore = ( value, uvNode, storeNode ) => { + + const node = textureStoreBase( value, uvNode, storeNode ); + + if ( storeNode !== null ) node.append(); + + return node; + +}; addNodeClass( 'TextureStoreNode', TextureStoreNode ); @@ -64847,6 +66510,13 @@ const BurnNode = tslFn( ( { base, blend } ) => { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'burnColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const DodgeNode = tslFn( ( { base, blend } ) => { @@ -64855,6 +66525,13 @@ const DodgeNode = tslFn( ( { base, blend } ) => { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'dodgeColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const ScreenNode = tslFn( ( { base, blend } ) => { @@ -64863,14 +66540,29 @@ const ScreenNode = tslFn( ( { base, blend } ) => { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'screenColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const OverlayNode = tslFn( ( { base, blend } ) => { const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() ); + //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) ); return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'overlayColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); class BlendModeNode extends TempNode { @@ -64934,29 +66626,6 @@ addNodeElement( 'screen', screen ); addNodeClass( 'BlendModeNode', BlendModeNode ); -class FrontFacingNode extends Node { - - constructor() { - - super( 'bool' ); - - this.isFrontFacingNode = true; - - } - - generate( builder ) { - - return builder.getFrontFacing(); - - } - -} - -const frontFacing = nodeImmutable( FrontFacingNode ); -const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); - -addNodeClass( 'FrontFacingNode', FrontFacingNode ); - // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf @@ -65126,9 +66795,12 @@ const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE ); const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 ); const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma ); +const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); + addNodeElement( 'saturation', saturation ); addNodeElement( 'vibrance', vibrance ); addNodeElement( 'hue', hue ); +addNodeElement( 'threshold', threshold ); addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode ); @@ -65219,8 +66891,6 @@ class NormalMapNode extends TempNode { const normalMap = nodeProxy( NormalMapNode ); -const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); - addNodeElement( 'normalMap', normalMap ); addNodeClass( 'NormalMapNode', NormalMapNode ); @@ -65323,11 +66993,52 @@ const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => { } ); + + +const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); +const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); + +const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => { + + const x = vec3( x_immutable ).toVar(); + const x2 = vec3( x.mul( x ) ).toVar(); + const x4 = vec3( x2.mul( x2 ) ).toVar(); + + return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); + +} ); + +const AGXToneMappingNode = tslFn( ( { color, exposure } ) => { + + const colortone = vec3( color ).toVar(); + const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); + const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); + const AgxMinEv = float( - 12.47393 ); + const AgxMaxEv = float( 4.026069 ); + colortone.mulAssign( exposure ); + colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); + colortone.assign( AgXInsetMatrix.mul( colortone ) ); + colortone.assign( max$1( colortone, 1e-10 ) ); + colortone.assign( log2( colortone ) ); + colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + colortone.assign( agxDefaultContrastApprox( colortone ) ); + colortone.assign( AgXOutsetMatrix.mul( colortone ) ); + colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); + colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + + return colortone; + +} ); + + const toneMappingLib = { [ LinearToneMapping ]: LinearToneMappingNode, [ ReinhardToneMapping ]: ReinhardToneMappingNode, [ CineonToneMapping ]: OptimizedCineonToneMappingNode, - [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode + [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode, + [ AgXToneMapping ]: AGXToneMappingNode }; class ToneMappingNode extends TempNode { @@ -65384,19 +67095,19 @@ const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingN addNodeClass( 'ToneMappingNode', ToneMappingNode ); -let sharedFramebuffer = null; +let _sharedFramebuffer = null; class ViewportSharedTextureNode extends ViewportTextureNode { constructor( uvNode = viewportTopLeft, levelNode = null ) { - if ( sharedFramebuffer === null ) { + if ( _sharedFramebuffer === null ) { - sharedFramebuffer = new FramebufferTexture(); + _sharedFramebuffer = new FramebufferTexture(); } - super( uvNode, levelNode, sharedFramebuffer ); + super( uvNode, levelNode, _sharedFramebuffer ); } @@ -65408,6 +67119,179 @@ addNodeElement( 'viewportSharedTexture', viewportSharedTexture ); addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode ); +class PassTextureNode extends TextureNode { + + constructor( passNode, texture ) { + + super( texture ); + + this.passNode = passNode; + + this.setUpdateMatrix( false ); + + } + + setup( builder ) { + + this.passNode.build( builder ); + + return super.setup( builder ); + + } + + clone() { + + return new this.constructor( this.passNode, this.value ); + + } + +} + +class PassNode extends TempNode { + + constructor( scope, scene, camera ) { + + super( 'vec4' ); + + this.scope = scope; + this.scene = scene; + this.camera = camera; + + this._pixelRatio = 1; + this._width = 1; + this._height = 1; + + const depthTexture = new DepthTexture(); + depthTexture.isRenderTargetTexture = true; + //depthTexture.type = FloatType; + depthTexture.name = 'PostProcessingDepth'; + + const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); + renderTarget.texture.name = 'PostProcessing'; + renderTarget.depthTexture = depthTexture; + + this.renderTarget = renderTarget; + + this.updateBeforeType = NodeUpdateType.FRAME; + + this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); + this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); + + this._depthNode = null; + this._cameraNear = uniform( 0 ); + this._cameraFar = uniform( 0 ); + + this.isPassNode = true; + + } + + isGlobal() { + + return true; + + } + + getTextureNode() { + + return this._textureNode; + + } + + getTextureDepthNode() { + + return this._depthTextureNode; + + } + + getDepthNode() { + + if ( this._depthNode === null ) { + + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; + + this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + + } + + return this._depthNode; + + } + + setup() { + + return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + + } + + updateBefore( frame ) { + + const { renderer } = frame; + const { scene, camera } = this; + + this._pixelRatio = renderer.getPixelRatio(); + + const size = renderer.getSize( new Vector2() ); + + this.setSize( size.width, size.height ); + + const currentToneMapping = renderer.toneMapping; + const currentToneMappingNode = renderer.toneMappingNode; + const currentRenderTarget = renderer.getRenderTarget(); + + this._cameraNear.value = camera.near; + this._cameraFar.value = camera.far; + + renderer.toneMapping = NoToneMapping; + renderer.toneMappingNode = null; + renderer.setRenderTarget( this.renderTarget ); + + renderer.render( scene, camera ); + + renderer.toneMapping = currentToneMapping; + renderer.toneMappingNode = currentToneMappingNode; + renderer.setRenderTarget( currentRenderTarget ); + + } + + setSize( width, height ) { + + this._width = width; + this._height = height; + + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; + + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + + } + + setPixelRatio( pixelRatio ) { + + this._pixelRatio = pixelRatio; + + this.setSize( this._width, this._height ); + + } + + dispose() { + + this.renderTarget.dispose(); + + } + + +} + +PassNode.COLOR = 'color'; +PassNode.DEPTH = 'depth'; + +const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); +const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); +const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + +addNodeClass( 'PassNode', PassNode ); + // Helper for passes that need to fill the viewport with a single quad. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); @@ -65445,9 +67329,9 @@ class QuadMesh { } - render( renderer ) { + async renderAsync( renderer ) { - renderer.render( this._mesh, _camera ); + await renderer.renderAsync( this._mesh, _camera ); } @@ -65463,6 +67347,12 @@ class QuadMesh { } + get render() { + + return this.renderAsync; + + } + } // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that @@ -65475,7 +67365,7 @@ class GaussianBlurNode extends TempNode { constructor( textureNode, sigma = 2 ) { - super( textureNode ); + super( 'vec4' ); this.textureNode = textureNode; this.sigma = sigma; @@ -65490,6 +67380,8 @@ class GaussianBlurNode extends TempNode { this._verticalRT = new RenderTarget(); this._verticalRT.texture.name = 'GaussianBlurNode.vertical'; + this._textureNode = texturePass( this, this._verticalRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; this.resolution = new Vector2( 1, 1 ); @@ -65522,6 +67414,11 @@ class GaussianBlurNode extends TempNode { this.setSize( map.image.width, map.image.height ); + const textureType = map.type; + + this._horizontalRT.texture.type = textureType; + this._verticalRT.texture.type = textureType; + // horizontal renderer.setRenderTarget( this._horizontalRT ); @@ -65546,6 +67443,12 @@ class GaussianBlurNode extends TempNode { } + getTextureNode() { + + return this._textureNode; + + } + setup( builder ) { const textureNode = this.textureNode; @@ -65594,7 +67497,7 @@ class GaussianBlurNode extends TempNode { // - const material = this._material || ( this._material = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const material = this._material || ( this._material = builder.createNodeMaterial() ); material.fragmentNode = blur(); // @@ -65604,7 +67507,7 @@ class GaussianBlurNode extends TempNode { // - return texture( this._verticalRT.texture ); + return this._textureNode; } @@ -65646,10 +67549,18 @@ class AfterImageNode extends TempNode { this._oldRT = new RenderTarget(); this._oldRT.texture.name = 'AfterImageNode.old'; + this._textureNode = texturePass( this, this._compRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; } + getTextureNode() { + + return this._textureNode; + + } + setSize( width, height ) { this._compRT.setSize( width, height ); @@ -65662,6 +67573,12 @@ class AfterImageNode extends TempNode { const { renderer } = frame; const textureNode = this.textureNode; + const map = textureNode.value; + + const textureType = map.type; + + this._compRT.texture.type = textureType; + this._oldRT.texture.type = textureType; const currentRenderTarget = renderer.getRenderTarget(); const currentTexture = textureNode.value; @@ -65678,7 +67595,6 @@ class AfterImageNode extends TempNode { this._compRT = temp; // set size before swapping fails - const map = currentTexture; this.setSize( map.image.width, map.image.height ); renderer.setRenderTarget( currentRenderTarget ); @@ -65726,7 +67642,7 @@ class AfterImageNode extends TempNode { // - const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() ); materialComposed.fragmentNode = afterImg(); quadMeshComp.material = materialComposed; @@ -65738,7 +67654,7 @@ class AfterImageNode extends TempNode { // - return texture( this._compRT.texture ); + return this._textureNode; } @@ -65748,177 +67664,138 @@ const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( addNodeElement( 'afterImage', afterImage ); -class PassTextureNode extends TextureNode { +const quadMesh = new QuadMesh(); - constructor( passNode, texture ) { +class AnamorphicNode extends TempNode { - super( texture ); + constructor( textureNode, tresholdNode, scaleNode, samples ) { - this.passNode = passNode; + super( 'vec4' ); - this.setUpdateMatrix( false ); + this.textureNode = textureNode; + this.tresholdNode = tresholdNode; + this.scaleNode = scaleNode; + this.colorNode = vec3( 0.1, 0.0, 1.0 ); + this.samples = samples; + this.resolution = new Vector2( 1, 1 ); - } + this._renderTarget = new RenderTarget(); + this._renderTarget.texture.name = 'anamorphic'; - setup( builder ) { + this._invSize = uniform( new Vector2() ); - this.passNode.build( builder ); + this._textureNode = texturePass( this, this._renderTarget.texture ); - return super.setup( builder ); + this.updateBeforeType = NodeUpdateType.RENDER; } - clone() { + getTextureNode() { - return new this.constructor( this.passNode, this.value ); + return this._textureNode; } -} - -class PassNode extends TempNode { - - constructor( scope, scene, camera ) { - - super( 'vec4' ); - - this.scope = scope; - this.scene = scene; - this.camera = camera; - - this._pixelRatio = 1; - this._width = 1; - this._height = 1; - - const depthTexture = new DepthTexture(); - depthTexture.isRenderTargetTexture = true; - depthTexture.type = FloatType; - depthTexture.name = 'PostProcessingDepth'; - - const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); - renderTarget.texture.name = 'PostProcessing'; - renderTarget.depthTexture = depthTexture; - - this.renderTarget = renderTarget; - - this.updateBeforeType = NodeUpdateType.FRAME; - - this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); - this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); - - this._depthNode = null; - this._cameraNear = uniform( 0 ); - this._cameraFar = uniform( 0 ); - - this.isPassNode = true; + setSize( width, height ) { - } + this._invSize.value.set( 1 / width, 1 / height ); - isGlobal() { + width = Math.max( Math.round( width * this.resolution.x ), 1 ); + height = Math.max( Math.round( height * this.resolution.y ), 1 ); - return true; + this._renderTarget.setSize( width, height ); } - getTextureNode() { + updateBefore( frame ) { - return this._textureNode; + const { renderer } = frame; - } + const textureNode = this.textureNode; + const map = textureNode.value; - getTextureDepthNode() { + this._renderTarget.texture.type = map.type; - return this._depthTextureNode; + const currentRenderTarget = renderer.getRenderTarget(); + const currentTexture = textureNode.value; - } + quadMesh.material = this._material; - getDepthNode() { + this.setSize( map.image.width, map.image.height ); - if ( this._depthNode === null ) { + // render - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; + renderer.setRenderTarget( this._renderTarget ); - this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + quadMesh.render( renderer ); - } + // restore - return this._depthNode; + renderer.setRenderTarget( currentRenderTarget ); + textureNode.value = currentTexture; } - setup() { - - return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + setup( builder ) { - } + const textureNode = this.textureNode; - updateBefore( frame ) { + if ( textureNode.isTextureNode !== true ) { - const { renderer } = frame; - const { scene, camera } = this; + return vec4(); - this._pixelRatio = renderer.getPixelRatio(); + } - const size = renderer.getSize( new Vector2() ); + // - this.setSize( size.width, size.height ); + const uvNode = textureNode.uvNode || uv(); - const currentToneMapping = renderer.toneMapping; - const currentToneMappingNode = renderer.toneMappingNode; - const currentRenderTarget = renderer.getRenderTarget(); + const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } ); - this._cameraNear.value = camera.near; - this._cameraFar.value = camera.far; + const anamorph = tslFn( () => { - renderer.toneMapping = NoToneMapping; - renderer.toneMappingNode = null; - renderer.setRenderTarget( this.renderTarget ); + const samples = this.samples; + const halfSamples = Math.floor( samples / 2 ); - renderer.render( scene, camera ); + const total = vec3( 0 ).toVar(); - renderer.toneMapping = currentToneMapping; - renderer.toneMappingNode = currentToneMappingNode; - renderer.setRenderTarget( currentRenderTarget ); + loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => { - } + const softness = float( i ).abs().div( halfSamples ).oneMinus(); - setSize( width, height ) { + const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y ); + const color = sampleTexture( uv ); + const pass = threshold( color, this.tresholdNode ).mul( softness ); - this._width = width; - this._height = height; + total.addAssign( pass ); - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; + } ); - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + return total.mul( this.colorNode ); - } + } ); - setPixelRatio( pixelRatio ) { + // - this._pixelRatio = pixelRatio; + const material = this._material || ( this._material = builder.createNodeMaterial() ); + material.fragmentNode = anamorph(); - this.setSize( this._width, this._height ); + // - } + const properties = builder.getNodeProperties( this ); + properties.textureNode = textureNode; - dispose() { + // - this.renderTarget.dispose(); + return this._textureNode; } - } -PassNode.COLOR = 'color'; -PassNode.DEPTH = 'depth'; +const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ), nodeObject( threshold ), nodeObject( scale ), samples ) ); -const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); -const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); - -addNodeClass( 'PassNode', PassNode ); +addNodeElement( 'anamorphic', anamorphic ); class FunctionCallNode extends TempNode { @@ -66670,7 +68547,7 @@ class FogNode extends Node { mixAssign( outputNode ) { - return this.mix( outputNode, this.colorNode ); + return mix( outputNode, this.colorNode, this ); } @@ -69200,13 +71077,7 @@ class SpriteNodeMaterial extends NodeMaterial { const rotation = float( rotationNode || materialRotation ); - const cosAngle = rotation.cos(); - const sinAngle = rotation.sin(); - - const rotatedPosition = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( alignedPosition )? - vec2( cosAngle, sinAngle.negate() ).dot( alignedPosition ), - vec2( sinAngle, cosAngle ).dot( alignedPosition ) - ); + const rotatedPosition = alignedPosition.rotate( rotation ); mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw ); @@ -71411,6 +73282,8 @@ class RenderContext { this.width = 0; this.height = 0; + this.isRenderContext = true; + } } @@ -71435,19 +73308,8 @@ class RenderContexts { } else { - let format, count; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - format = renderTarget.texture[ 0 ].format; - count = renderTarget.texture.length; - - } else { - - format = renderTarget.texture.format; - count = 1; - - } + const format = renderTarget.texture.format; + const count = renderTarget.count; attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; @@ -71489,10 +73351,11 @@ const _size = new Vector3(); class Textures extends DataMap { - constructor( backend, info ) { + constructor( renderer, backend, info ) { super(); + this.renderer = renderer; this.backend = backend; this.info = info; @@ -71505,19 +73368,8 @@ class Textures extends DataMap { const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); - let texture, textures; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - textures = renderTarget.texture; - texture = renderTarget.texture[ 0 ]; - - } else { - - textures = [ renderTarget.texture ]; - texture = renderTarget.texture; - - } + const texture = renderTarget.texture; + const textures = renderTarget.textures; const size = this.getSize( texture ); @@ -71530,8 +73382,8 @@ class Textures extends DataMap { if ( depthTexture === undefined ) { depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; + depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; + depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; depthTexture.image.width = mipWidth; depthTexture.image.height = mipHeight; @@ -71555,6 +73407,7 @@ class Textures extends DataMap { renderTargetData.depthTexture = depthTexture; renderTargetData.depth = renderTarget.depthBuffer; renderTargetData.stencil = renderTarget.stencilBuffer; + renderTargetData.renderTarget = renderTarget; if ( renderTargetData.sampleCount !== sampleCount ) { @@ -71636,6 +73489,25 @@ class Textures extends DataMap { // + if ( texture.isFramebufferTexture ) { + + const renderer = this.renderer; + const renderTarget = renderer.getRenderTarget(); + + if ( renderTarget ) { + + texture.type = renderTarget.texture.type; + + } else { + + texture.type = UnsignedByteType; + + } + + } + + // + const { width, height, depth } = this.getSize( texture ); options.width = width; @@ -71689,7 +73561,7 @@ class Textures extends DataMap { } - backend.updateTexture( texture, options ); + if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); @@ -71890,7 +73762,7 @@ class Background extends DataMap { const backgroundMeshNode = context( vec4( backgroundNode ), { // @TODO: Add Texture2D support using node context getUV: () => normalWorld, - getTextureLevel: () => backgroundBlurriness + getTextureLevel: ( textureNode ) => backgroundBlurriness.mul( maxMipLevel( textureNode ) ) } ).mul( backgroundIntensity ); let viewProj = modelViewProjection(); @@ -71966,11 +73838,12 @@ class Background extends DataMap { class NodeBuilderState { - constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes ) { + constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, transforms = [] ) { this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; this.computeShader = computeShader; + this.transforms = transforms; this.nodeAttributes = nodeAttributes; this.bindings = bindings; @@ -72116,6 +73989,7 @@ class Nodes extends DataMap { nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene ); nodeBuilder.fogNode = this.getFogNode( renderObject.scene ); nodeBuilder.toneMappingNode = this.getToneMappingNode(); + nodeBuilder.clippingContext = renderObject.clippingContext; nodeBuilder.build(); nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); @@ -72166,7 +74040,7 @@ class Nodes extends DataMap { nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); - computeData.nodeBuilderState = nodeBuilder; + computeData.nodeBuilderState = nodeBuilderState; } @@ -72183,7 +74057,8 @@ class Nodes extends DataMap { nodeBuilder.getAttributesArray(), nodeBuilder.getBindings(), nodeBuilder.updateNodes, - nodeBuilder.updateBeforeNodes + nodeBuilder.updateBeforeNodes, + nodeBuilder.transforms ); } @@ -72526,6 +74401,8 @@ class Renderer { this.depth = true; this.stencil = true; + this.clippingPlanes = []; + this.info = new Info(); // internals @@ -72569,9 +74446,13 @@ class Renderer { this._renderObjectFunction = null; this._currentRenderObjectFunction = null; + this._handleObjectFunction = this._renderObjectDirect; + this._initialized = false; this._initPromise = null; + this._compilationPromises = null; + // backwards compatibility this.shadowMap = { @@ -72619,7 +74500,7 @@ class Renderer { this._attributes = new Attributes( backend ); this._background = new Background( this, this._nodes ); this._geometries = new Geometries( this._attributes, this.info ); - this._textures = new Textures( backend, this.info ); + this._textures = new Textures( this, backend, this.info ); this._pipelines = new Pipelines( backend, this._nodes ); this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); @@ -72644,14 +74525,154 @@ class Renderer { } - async compile( /*scene, camera*/ ) { + async compileAsync( scene, camera, targetScene = null ) { + + if ( this._initialized === false ) await this.init(); + + // preserve render tree + + const nodeFrame = this._nodes.nodeFrame; + + const previousRenderId = nodeFrame.renderId; + const previousRenderContext = this._currentRenderContext; + const previousRenderObjectFunction = this._currentRenderObjectFunction; + const previousCompilationPromises = this._compilationPromises; + + // + + const sceneRef = ( scene.isScene === true ) ? scene : _scene; + + if ( targetScene === null ) targetScene = scene; + + const renderTarget = this._renderTarget; + const renderContext = this._renderContexts.get( targetScene, camera, renderTarget ); + const activeMipmapLevel = this._activeMipmapLevel; + + const compilationPromises = []; + + this._currentRenderContext = renderContext; + this._currentRenderObjectFunction = this.renderObject; + + this._handleObjectFunction = this._createObjectPipeline; + + this._compilationPromises = compilationPromises; + + nodeFrame.renderId ++; + + // + + nodeFrame.update(); + + // + + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; + + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); + + // + + sceneRef.onBeforeRender( this, scene, camera, renderTarget ); + + // + + const renderList = this._renderLists.get( scene, camera ); + renderList.begin(); + + this._projectObject( scene, camera, 0, renderList ); + + // include lights from target scene + if ( targetScene !== scene ) { + + targetScene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + renderList.pushLight( object ); + + } + + } ); + + } + + renderList.finish(); + + // + + if ( renderTarget !== null ) { + + this._textures.updateRenderTarget( renderTarget, activeMipmapLevel ); + + const renderTargetData = this._textures.get( renderTarget ); + + renderContext.textures = renderTargetData.textures; + renderContext.depthTexture = renderTargetData.depthTexture; + + } else { + + renderContext.textures = null; + renderContext.depthTexture = null; + + } + + // + + this._nodes.updateScene( sceneRef ); + + // + + this._background.update( sceneRef, renderList, renderContext ); + + // process render lists + + const opaqueObjects = renderList.opaque; + const transparentObjects = renderList.transparent; + const lightsNode = renderList.lightsNode; + + if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode ); + if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode ); + + // restore render tree + + nodeFrame.renderId = previousRenderId; + + this._currentRenderContext = previousRenderContext; + this._currentRenderObjectFunction = previousRenderObjectFunction; + this._compilationPromises = previousCompilationPromises; + + this._handleObjectFunction = this._renderObjectDirect; + + // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete + + await Promise.all( compilationPromises ); } - async render( scene, camera ) { + async renderAsync( scene, camera ) { if ( this._initialized === false ) await this.init(); + const renderContext = this._renderContext( scene, camera ); + + await this.backend.resolveTimestampAsync( renderContext, 'render' ); + + } + + render( scene, camera ) { + + if ( this._initialized === false ) { + return; + + } + + this._renderContext( scene, camera ); + + } + + _renderContext( scene, camera ) { + // preserve render tree const nodeFrame = this._nodes.nodeFrame; @@ -72732,8 +74753,8 @@ class Renderer { renderContext.scissorValue.width >>= activeMipmapLevel; renderContext.scissorValue.height >>= activeMipmapLevel; - renderContext.depth = this.depth; - renderContext.stencil = this.stencil; + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); // @@ -72770,6 +74791,8 @@ class Renderer { renderContext.width = renderTargetData.width; renderContext.height = renderTargetData.height; renderContext.renderTarget = renderTarget; + renderContext.depth = renderTarget.depthBuffer; + renderContext.stencil = renderTarget.stencilBuffer; } else { @@ -72777,6 +74800,8 @@ class Renderer { renderContext.depthTexture = null; renderContext.width = this.domElement.width; renderContext.height = this.domElement.height; + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; } @@ -72822,6 +74847,10 @@ class Renderer { sceneRef.onAfterRender( this, scene, camera, renderTarget ); + // + + return renderContext; + } getMaxAnisotropy() { @@ -72982,6 +75011,8 @@ class Renderer { this._scissorTest = boolean; + this.backend.setScissorTest( boolean ); + } getViewport( target ) { @@ -73085,19 +75116,45 @@ class Renderer { clearColor() { - this.clear( true, false, false ); + return this.clear( true, false, false ); } clearDepth() { - this.clear( false, true, false ); + return this.clear( false, true, false ); } clearStencil() { - this.clear( false, false, true ); + return this.clear( false, false, true ); + + } + + async clearAsync( color = true, depth = true, stencil = true ) { + + if ( this._initialized === false ) await this.init(); + + this.clear( color, depth, stencil ); + + } + + clearColorAsync() { + + return this.clearAsync( true, false, false ); + + } + + clearDepthAsync() { + + return this.clearAsync( false, true, false ); + + } + + clearStencilAsync() { + + return this.clearAsync( false, false, true ); } @@ -73161,7 +75218,7 @@ class Renderer { } - async compute( computeNodes ) { + async computeAsync( computeNodes ) { if ( this._initialized === false ) await this.init(); @@ -73173,10 +75230,12 @@ class Renderer { this.info.calls ++; this.info.compute.calls ++; + this.info.compute.computeCalls ++; nodeFrame.renderId = this.info.calls; // + if ( this.info.autoReset === true ) this.info.resetCompute(); const backend = this.backend; const pipelines = this._pipelines; @@ -73228,12 +75287,20 @@ class Renderer { backend.finishCompute( computeNodes ); + await this.backend.resolveTimestampAsync( computeNodes, 'compute' ); + // nodeFrame.renderId = previousRenderId; } + hasFeatureAsync( name ) { + + return this.backend.hasFeatureAsync( name ); + + } + hasFeature( name ) { return this.backend.hasFeature( name ); @@ -73407,6 +75474,7 @@ class Renderer { renderObject( object, scene, camera, geometry, material, group, lightsNode ) { let overridePositionNode; + let overrideFragmentNode; // @@ -73428,6 +75496,45 @@ class Renderer { } + if ( overrideMaterial.isShadowNodeMaterial ) { + + overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide; + + if ( material.shadowNode && material.shadowNode.isNode ) { + + overrideFragmentNode = overrideMaterial.fragmentNode; + overrideMaterial.fragmentNode = material.shadowNode; + + } + + if ( this.localClippingEnabled ) { + + if ( material.clipShadows ) { + + if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) { + + overrideMaterial.clippingPlanes = material.clippingPlanes; + overrideMaterial.needsUpdate = true; + + } + + if ( overrideMaterial.clipIntersection !== material.clipIntersection ) { + + overrideMaterial.clipIntersection = material.clipIntersection; + + } + + } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) { + + overrideMaterial.clippingPlanes = null; + overrideMaterial.needsUpdate = true; + + } + + } + + } + material = overrideMaterial; } @@ -73437,16 +75544,16 @@ class Renderer { if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { material.side = BackSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id material.side = FrontSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode ); // use default pass id material.side = DoubleSide; } else { - this._renderObjectDirect( object, material, scene, camera, lightsNode ); + this._handleObjectFunction( object, material, scene, camera, lightsNode ); } @@ -73458,6 +75565,12 @@ class Renderer { } + if ( overrideFragmentNode !== undefined ) { + + scene.overrideMaterial.fragmentNode = overrideFragmentNode; + + } + // object.onAfterRender( this, scene, camera, geometry, material, group ); @@ -73490,6 +75603,36 @@ class Renderer { } + _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) { + + const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId ); + + // + + this._nodes.updateBefore( renderObject ); + + // + + this._nodes.updateForRender( renderObject ); + this._geometries.updateForRender( renderObject ); + this._bindings.updateForRender( renderObject ); + + this._pipelines.getForRender( renderObject, this._compilationPromises ); + + } + + get compute() { + + return this.computeAsync; + + } + + get compile() { + + return this.compileAsync; + + } + } class Binding { @@ -73524,24 +75667,6 @@ function getFloatLength( floatLength ) { } -function getVectorLength( count, vectorLength = 4 ) { - - const strideLength = getStrideLength( vectorLength ); - - const floatLength = strideLength * count; - - return getFloatLength( floatLength ); - -} - -function getStrideLength( vectorLength ) { - - const strideLength = 4; - - return vectorLength + ( ( strideLength - ( vectorLength % strideLength ) ) % strideLength ); - -} - class Buffer extends Binding { constructor( name, buffer = null ) { @@ -73588,6 +75713,26 @@ class UniformBuffer extends Buffer { } +let _id$2 = 0; + +class NodeUniformBuffer extends UniformBuffer { + + constructor( nodeUniform ) { + + super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + +} + class UniformsGroup extends UniformBuffer { constructor( name ) { @@ -73650,6 +75795,8 @@ class UniformsGroup extends UniformBuffer { const uniform = this.uniforms[ i ]; + const { boundary, itemSize } = uniform; + // offset within a single chunk in bytes const chunkOffset = offset % GPU_CHUNK_BYTES; @@ -73657,23 +75804,23 @@ class UniformsGroup extends UniformBuffer { // conformance tests - if ( chunkOffset !== 0 && ( remainingSizeInChunk - uniform.boundary ) < 0 ) { + if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) { // check for chunk overflow offset += ( GPU_CHUNK_BYTES - chunkOffset ); - } else if ( chunkOffset % uniform.boundary !== 0 ) { + } else if ( chunkOffset % boundary !== 0 ) { // check for correct alignment - offset += ( chunkOffset % uniform.boundary ); + offset += ( chunkOffset % boundary ); } uniform.offset = ( offset / this.bytesPerElement ); - offset += ( uniform.itemSize * this.bytesPerElement ); + offset += ( itemSize * this.bytesPerElement ); } @@ -74014,7 +76161,8 @@ class NodeSampledCubeTexture extends NodeSampledTexture { const glslMethods = { [ MathNode.ATAN2 ]: 'atan', - textureDimensions: 'textureSize' + textureDimensions: 'textureSize', + equals: 'equal' }; const precisionLib = { @@ -74024,7 +76172,8 @@ const precisionLib = { }; const supports$1 = { - instance: true + instance: true, + swizzleAssign: true }; const defaultPrecisions = ` @@ -74041,6 +76190,7 @@ class GLSLNodeBuilder extends NodeBuilder { super( object, renderer, new GLSLNodeParser(), scene ); this.uniformGroups = {}; + this.transforms = []; } @@ -74088,6 +76238,130 @@ ${ flowData.code } } + setupPBO( storageBufferNode ) { + + const attribute = storageBufferNode.value; + + if ( attribute.pbo === undefined ) { + + const originalArray = attribute.array; + const numElements = attribute.count * attribute.itemSize; + + const { itemSize } = attribute; + let format = RedFormat; + + if ( itemSize === 2 ) { + + format = RGFormat; + + } else if ( itemSize === 3 ) { + + format = 6407; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization + + } else if ( itemSize === 4 ) { + + format = RGBAFormat; + + } + + const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) ); + let height = Math.ceil( ( numElements / itemSize ) / width ); + if ( width * height * itemSize < numElements ) height ++; // Ensure enough space + + const newSize = width * height * itemSize; + + const newArray = new Float32Array( newSize ); + + newArray.set( originalArray, 0 ); + + attribute.array = newArray; + + const pboTexture = new DataTexture( attribute.array, width, height, format, FloatType ); + pboTexture.needsUpdate = true; + pboTexture.isPBOTexture = true; + + const pbo = new UniformNode( pboTexture ); + pbo.setPrecision( 'high' ); + + attribute.pboNode = pbo; + attribute.pbo = pbo.value; + + this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + + } + + } + + generatePBO( storageArrayElementNode ) { + + const { node, indexNode } = storageArrayElementNode; + const attribute = node.value; + + if ( this.renderer.backend.has( attribute ) ) { + + const attributeData = this.renderer.backend.get( attribute ); + attributeData.pbo = attribute.pbo; + + } + + + const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + const textureName = this.getPropertyName( nodeUniform ); + + indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y + const indexSnippet = indexNode.build( this, 'uint' ); + + const elementNodeData = this.getDataFromNode( storageArrayElementNode ); + + let propertyName = elementNodeData.propertyName; + + if ( propertyName === undefined ) { + + // property element + + const nodeVar = this.getVarFromNode( storageArrayElementNode ); + + propertyName = this.getPropertyName( nodeVar ); + + // property size + + const bufferNodeData = this.getDataFromNode( node ); + + let propertySizeName = bufferNodeData.propertySizeName; + + if ( propertySizeName === undefined ) { + + propertySizeName = propertyName + 'Size'; + + this.getVarFromNode( node, propertySizeName, 'uint' ); + + this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` ); + + bufferNodeData.propertySizeName = propertySizeName; + + } + + // + + const { itemSize } = attribute; + + const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize ); + const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`; + + const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' ); + + // + + this.addLineFlowCode( `${ propertyName } = ${ snippet + channel }` ); + + elementNodeData.propertyName = propertyName; + + } + + return propertyName; + + } + generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) { if ( depthSnippet ) { @@ -74280,7 +76554,7 @@ ${ flowData.code } let snippet = ''; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { const attributes = this.getAttributesArray(); @@ -74347,10 +76621,11 @@ ${ flowData.code } const varyings = this.varyings; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { for ( const varying of varyings ) { + if ( shaderStage === 'compute' ) varying.needsInterpolation = true; const type = varying.type; const flat = type === 'int' || type === 'uint' ? 'flat ' : ''; @@ -74415,13 +76690,38 @@ ${ flowData.code } } - isFlipY() { return true; } + registerTransform( varyingName, attributeNode ) { + + this.transforms.push( { varyingName, attributeNode } ); + + } + + getTransforms( /* shaderStage */ ) { + + const transforms = this.transforms; + + let snippet = ''; + + for ( let i = 0; i < transforms.length; i ++ ) { + + const transform = transforms[ i ]; + + const attributeName = this.getPropertyName( transform.attributeNode ); + + snippet += `${ transform.varyingName } = ${ attributeName };\n\t`; + + } + + return snippet; + + } + _getGLSLUniformStruct( name, vars ) { return ` @@ -74457,6 +76757,9 @@ void main() { // vars ${shaderData.vars} + // transforms + ${shaderData.transforms} + // flow ${shaderData.flow} @@ -74559,6 +76862,7 @@ void main() { stageData.vars = this.getVars( shaderStage ); stageData.structs = this.getStructs( shaderStage ); stageData.codes = this.getCodes( shaderStage ); + stageData.transforms = this.getTransforms( shaderStage ); stageData.flow = flow; } @@ -74568,6 +76872,10 @@ void main() { this.vertexShader = this._getGLSLVertexCode( shadersData.vertex ); this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment ); + } else { + + this.computeShader = this._getGLSLVertexCode( shadersData.compute ); + } } @@ -74595,11 +76903,11 @@ void main() { } else if ( type === 'buffer' ) { - node.name = `NodeBuffer_${node.id}`; - - const buffer = new UniformBuffer( node.name, node.value ); + node.name = `NodeBuffer_${ node.id }`; + uniformNode.name = `buffer${ node.id }`; - uniformNode.name = `buffer${node.id}`; + const buffer = new NodeUniformBuffer( node ); + buffer.name = node.name; this.bindings[ shaderStage ].push( buffer ); @@ -74730,6 +77038,10 @@ class Backend { // utils + resolveTimestampAsync( renderContext, type ) { } + + hasFeatureAsync( name ) { } // return Boolean + hasFeature( name ) { } // return Boolean getInstanceCount( renderObject ) { @@ -74756,6 +77068,8 @@ class Backend { } + setScissorTest( boolean ) { } + getClearColor() { const renderer = this.renderer; @@ -74812,6 +77126,12 @@ class Backend { } + has( object ) { + + return this.data.has( object ); + + } + delete( object ) { this.data.delete( object ); @@ -74820,6 +77140,52 @@ class Backend { } +let _id$1 = 0; + +class DualAttributeData { + + constructor( attributeData, dualBuffer ) { + + this.buffers = [ attributeData.bufferGPU, dualBuffer ]; + this.type = attributeData.type; + this.bufferType = attributeData.bufferType; + this.pbo = attributeData.pbo; + this.byteLength = attributeData.byteLength; + this.bytesPerElement = attributeData.BYTES_PER_ELEMENT; + this.version = attributeData.version; + this.isInteger = attributeData.isInteger; + this.activeBufferIndex = 0; + this.baseId = attributeData.id; + + } + + + get id() { + + return `${ this.baseId }|${ this.activeBufferIndex }`; + + } + + get bufferGPU() { + + return this.buffers[ this.activeBufferIndex ]; + + } + + get transformBuffer() { + + return this.buffers[ this.activeBufferIndex ^ 1 ]; + + } + + switchBuffers() { + + this.activeBufferIndex ^= 1; + + } + +} + class WebGLAttributeUtils { constructor( backend ) { @@ -74843,11 +77209,7 @@ class WebGLAttributeUtils { if ( bufferGPU === undefined ) { - bufferGPU = gl.createBuffer(); - - gl.bindBuffer( bufferType, bufferGPU ); - gl.bufferData( bufferType, array, usage ); - gl.bindBuffer( bufferType, null ); + bufferGPU = this._createBuffer( gl, bufferType, array, usage ); bufferData.bufferGPU = bufferGPU; bufferData.bufferType = bufferType; @@ -74905,13 +77267,27 @@ class WebGLAttributeUtils { } - backend.set( attribute, { + let attributeData = { bufferGPU, + bufferType, type, + byteLength: array.byteLength, bytesPerElement: array.BYTES_PER_ELEMENT, version: attribute.version, - isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType - } ); + pbo: attribute.pbo, + isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType, + id: _id$1 ++ + }; + + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) { + + // create buffer for tranform feedback use + const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage ); + attributeData = new DualAttributeData( attributeData, bufferGPUDual ); + + } + + backend.set( attribute, attributeData ); } @@ -75005,6 +77381,18 @@ class WebGLAttributeUtils { } + _createBuffer( gl, bufferType, array, usage ) { + + const bufferGPU = gl.createBuffer(); + + gl.bindBuffer( bufferType, bufferGPU ); + gl.bufferData( bufferType, array, usage ); + gl.bindBuffer( bufferType, null ); + + return bufferGPU; + + } + } let initialized$1 = false, equationToGL, factorToGL; @@ -75762,6 +78150,7 @@ class WebGLUtils { } if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === gl.RGB ) return gl.RGB; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization if ( p === RGBAFormat ) return gl.RGBA; if ( p === LuminanceFormat ) return gl.LUMINANCE; if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA; @@ -76141,6 +78530,17 @@ class WebGLTextureUtils { } + if ( glFormat === gl.RGB ) { + + if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F; + if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F; + if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8; + if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565; + if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1; + if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4; + + } + if ( glFormat === gl.RGBA ) { if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F; @@ -76178,7 +78578,9 @@ class WebGLTextureUtils { setTextureParameters( textureType, texture ) { - const { gl, extensions } = this; + const { gl, extensions, backend } = this; + + const { currentAnisotropy } = backend.get( texture ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); @@ -76193,7 +78595,7 @@ class WebGLTextureUtils { // follow WebGPU backend mapping for texture filtering - const minFilter = texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; + const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] ); @@ -76206,13 +78608,17 @@ class WebGLTextureUtils { if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - //extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 - if ( texture.anisotropy > 1 /*|| properties.get( texture ).__currentAnisotropy*/ ) ; + if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) ); + backend.get( texture ).currentAnisotropy = texture.anisotropy; + + } } @@ -76290,6 +78696,41 @@ class WebGLTextureUtils { } + copyBufferToTexture( buffer, texture ) { + + const { gl, backend } = this; + + const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture ); + + const { width, height } = texture.source.data; + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer ); + + backend.state.bindTexture( glTextureType, textureGPU ); + + gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false ); + gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false ); + gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 ); + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null ); + + backend.state.unbindTexture(); + // debug + // const framebuffer = gl.createFramebuffer(); + // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer ); + // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 ); + + // const readout = new Float32Array( width * height * 4 ); + + // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ); + // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ); + + // gl.readPixels( 0, 0, width, height, altFormat, altType, readout ); + // gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + // console.log( readout ); + + } + updateTexture( texture, options ) { const { gl } = this; @@ -76479,21 +78920,25 @@ class WebGLTextureUtils { const width = texture.image.width; const height = texture.image.height; - state.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); - if ( texture.isDepthTexture ) { - const fb = gl.createFramebuffer(); + let mask = gl.DEPTH_BUFFER_BIT; + + if ( renderContext.stencil ) { - gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); + mask |= gl.STENCIL_BUFFER_BIT; + + } + + const fb = gl.createFramebuffer(); + state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, textureGPU, 0 ); - gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST ); + gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST ); gl.deleteFramebuffer( fb ); - } else { state.bindTexture( gl.TEXTURE_2D, textureGPU ); @@ -76613,10 +79058,11 @@ class WebGLTextureUtils { if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array; - if ( glType === gl.UNSIGNED_INT ) return Uint32Array; - if ( glType === gl.UNSIGNED_FLOAT ) return Float32Array; + if ( glType === gl.FLOAT ) return Float32Array; + + throw new Error( `Unsupported WebGL type: ${glType}` ); } @@ -76745,7 +79191,12 @@ class WebGLBackend extends Backend { this.state = new WebGLState( this ); this.utils = new WebGLUtils( this ); + this.vaoCache = {}; + this.transformFeedbackCache = {}; + this.discard = false; + this.extensions.get( 'EXT_color_buffer_float' ); + this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' ); this._currentContext = null; } @@ -76782,7 +79233,7 @@ class WebGLBackend extends Backend { this._setFramebuffer( renderContext ); - this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext ); + this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false ); // if ( renderContext.viewport ) { @@ -76795,6 +79246,14 @@ class WebGLBackend extends Backend { } + if ( renderContext.scissor ) { + + const { x, y, width, height } = renderContext.scissorValue; + + gl.scissor( x, y, width, height ); + + } + const occlusionQueryCount = renderContext.occlusionQueryCount; if ( occlusionQueryCount > 0 ) { @@ -76987,7 +79446,23 @@ class WebGLBackend extends Backend { } - clear( color, depth, stencil, descriptor = null ) { + setScissorTest( boolean ) { + + const gl = this.gl; + + if ( boolean ) { + + gl.enable( gl.SCISSOR_TEST ); + + } else { + + gl.disable( gl.SCISSOR_TEST ); + + } + + } + + clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) { const { gl } = this; @@ -77010,7 +79485,7 @@ class WebGLBackend extends Backend { if ( clear !== 0 ) { - const clearColor = descriptor.clearColorValue; + const clearColor = descriptor.clearColorValue || this.getClearColor(); if ( depth ) this.state.setDepthMask( true ); @@ -77021,6 +79496,8 @@ class WebGLBackend extends Backend { } else { + if ( setFrameBuffer ) this._setFramebuffer( descriptor ); + if ( color ) { for ( let i = 0; i < descriptor.textures.length; i ++ ) { @@ -77053,20 +79530,95 @@ class WebGLBackend extends Backend { beginCompute( /*computeGroup*/ ) { + const gl = this.gl; + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + } - compute( /*computeGroup, computeNode, bindings, pipeline*/ ) { + compute( computeGroup, computeNode, bindings, pipeline ) { + + const gl = this.gl; + + if ( ! this.discard ) { + + // required here to handle async behaviour of render.compute() + gl.enable( gl.RASTERIZER_DISCARD ); + this.discard = true; + + } + + const { programGPU, transformBuffers, attributes } = this.get( pipeline ); + + const vaoKey = this._getVaoKey( null, attributes ); + + const vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + this._createVao( null, attributes ); + + } else { + + gl.bindVertexArray( vaoGPU ); + + } + + gl.useProgram( programGPU ); + + this._bindUniforms( bindings ); + + const transformFeedbackGPU = this._getTransformFeedback( transformBuffers ); + + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); + gl.beginTransformFeedback( gl.POINTS ); + + if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) { + + gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count ); + + } else { + + gl.drawArrays( gl.POINTS, 0, computeNode.count ); + + } + + gl.endTransformFeedback(); + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); + + // switch active buffers + + for ( let i = 0; i < transformBuffers.length; i ++ ) { + + const dualAttributeData = transformBuffers[ i ]; + + if ( dualAttributeData.pbo ) { + + this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo ); + + } + + dualAttributeData.switchBuffers(); + + + } } finishCompute( /*computeGroup*/ ) { + const gl = this.gl; + + this.discard = false; + + gl.disable( gl.RASTERIZER_DISCARD ); + } draw( renderObject, info ) { const { pipeline, material, context } = renderObject; - const { programGPU, vaoGPU } = this.get( pipeline ); + const { programGPU } = this.get( pipeline ); const { gl, state } = this; @@ -77074,28 +79626,34 @@ class WebGLBackend extends Backend { // - const bindings = renderObject.getBindings(); + this._bindUniforms( renderObject.getBindings() ); - for ( const binding of bindings ) { + state.setMaterial( material ); - const bindingData = this.get( binding ); - const index = bindingData.index; + gl.useProgram( programGPU ); - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + // - gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); + let vaoGPU = renderObject.staticVao; - } else if ( binding.isSampledTexture ) { + if ( vaoGPU === undefined ) { - state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); + const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() ); + + vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + let staticVao; + + ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) ); + + if ( staticVao ) renderObject.staticVao = vaoGPU; } } - state.setMaterial( material ); - - gl.useProgram( programGPU ); gl.bindVertexArray( vaoGPU ); // @@ -77177,7 +79735,6 @@ class WebGLBackend extends Backend { } - info.update( object, indexCount, 1 ); } else { @@ -77201,8 +79758,6 @@ class WebGLBackend extends Backend { } - - // gl.bindVertexArray( null ); @@ -77283,7 +79838,7 @@ class WebGLBackend extends Backend { const gl = this.gl; const { stage, code } = program; - const shader = stage === 'vertex' ? gl.createShader( gl.VERTEX_SHADER ) : gl.createShader( gl.FRAGMENT_SHADER ); + const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER ); gl.shaderSource( shader, code ); gl.compileShader( shader ); @@ -77298,7 +79853,7 @@ class WebGLBackend extends Backend { } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const gl = this.gl; const pipeline = renderObject.pipeline; @@ -77316,39 +79871,487 @@ class WebGLBackend extends Backend { gl.attachShader( programGPU, vertexShader ); gl.linkProgram( programGPU ); + this.set( pipeline, { + programGPU, + fragmentShader, + vertexShader + } ); + + if ( promises !== null && this.parallel ) { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + const parallel = this.parallel; + const checkStatus = () => { + + if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) { + + this._completeCompile( renderObject, pipeline ); + resolve(); + + } else { + + requestAnimationFrame( checkStatus ); + + } + + }; + + checkStatus(); + + } ); + + promises.push( p ); + + return; + + } + + this._completeCompile( renderObject, pipeline ); + + } + + _completeCompile( renderObject, pipeline ) { + + const gl = this.gl; + const pipelineData = this.get( pipeline ); + const { programGPU, fragmentShader, vertexShader } = pipelineData; + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; gl.useProgram( programGPU ); // Bindings - const bindings = renderObject.getBindings(); + this._setupBindings( renderObject.getBindings(), programGPU ); - for ( const binding of bindings ) { + // - const bindingData = this.get( binding ); - const index = bindingData.index; + this.set( pipeline, { + programGPU + } ); + + } + + createComputePipeline( computePipeline, bindings ) { + + const gl = this.gl; + + // Program + + const fragmentProgram = { + stage: 'fragment', + code: '#version 300 es\nprecision highp float;\nvoid main() {}' + }; + + this.createProgram( fragmentProgram ); + + const { computeProgram } = computePipeline; + + const programGPU = gl.createProgram(); + + const fragmentShader = this.get( fragmentProgram ).shaderGPU; + const vertexShader = this.get( computeProgram ).shaderGPU; + + const transforms = computeProgram.transforms; + + const transformVaryingNames = []; + const transformAttributeNodes = []; + + for ( let i = 0; i < transforms.length; i ++ ) { + + const transform = transforms[ i ]; + + transformVaryingNames.push( transform.varyingName ); + transformAttributeNodes.push( transform.attributeNode ); + + } + + gl.attachShader( programGPU, fragmentShader ); + gl.attachShader( programGPU, vertexShader ); + + gl.transformFeedbackVaryings( + programGPU, + transformVaryingNames, + gl.SEPARATE_ATTRIBS, + ); + + gl.linkProgram( programGPU ); + + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; + + gl.useProgram( programGPU ); + + // Bindings + + this.createBindings( bindings ); + + this._setupBindings( bindings, programGPU ); + + const attributeNodes = computeProgram.attributes; + const attributes = []; + const transformBuffers = []; + + for ( let i = 0; i < attributeNodes.length; i ++ ) { + + const attribute = attributeNodes[ i ].node.attribute; + + attributes.push( attribute ); + + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + } + + for ( let i = 0; i < transformAttributeNodes.length; i ++ ) { + + const attribute = transformAttributeNodes[ i ].attribute; + + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + const attributeData = this.get( attribute ); + + transformBuffers.push( attributeData ); + + } + + // + + this.set( computePipeline, { + programGPU, + transformBuffers, + attributes + } ); + + } + + createBindings( bindings ) { + + this.updateBindings( bindings ); + + } + + updateBindings( bindings ) { + + const { gl } = this; + + let groupIndex = 0; + let textureIndex = 0; + + for ( const binding of bindings ) { if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - const location = gl.getUniformBlockIndex( programGPU, binding.name ); - gl.uniformBlockBinding( programGPU, location, index ); + const bufferGPU = gl.createBuffer(); + const data = binding.buffer; + + gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); + gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU ); + + this.set( binding, { + index: groupIndex ++, + bufferGPU + } ); } else if ( binding.isSampledTexture ) { - const location = gl.getUniformLocation( programGPU, binding.name ); - gl.uniform1i( location, index ); + const { textureGPU, glTextureType } = this.get( binding.texture ); + + this.set( binding, { + index: textureIndex ++, + textureGPU, + glTextureType + } ); } } - // VAO + } + + updateBinding( binding ) { + + const gl = this.gl; + + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + + const bindingData = this.get( binding ); + const bufferGPU = bindingData.bufferGPU; + const data = binding.buffer; + + gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); + gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + + } + + } + + // attributes + + createIndexAttribute( attribute ) { + + const gl = this.gl; + + this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + + } + + createAttribute( attribute ) { + + if ( this.has( attribute ) ) return; + + const gl = this.gl; + + this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + + } + + createStorageAttribute( attribute ) { + + //console.warn( 'Abstract class.' ); + + } + + updateAttribute( attribute ) { + + this.attributeUtils.updateAttribute( attribute ); + + } + + destroyAttribute( attribute ) { + + this.attributeUtils.destroyAttribute( attribute ); + + } + + updateSize() { + + //console.warn( 'Abstract class.' ); + + } + + async hasFeatureAsync( name ) { + + return this.hasFeature( name ); + + } + + hasFeature( name ) { + + const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); + + const extensions = this.extensions; + + for ( let i = 0; i < keysMatching.length; i ++ ) { + + + if ( extensions.has( keysMatching[ i ] ) ) return true; + + } + + return false; + + } + + + getMaxAnisotropy() { + + return this.capabilities.getMaxAnisotropy(); + + } + + copyFramebufferToTexture( texture, renderContext ) { + + this.textureUtils.copyFramebufferToTexture( texture, renderContext ); + + } + + _setFramebuffer( renderContext ) { + + const { gl, state } = this; + + let currentFrameBuffer = null; + + if ( renderContext.textures !== null ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetContextData = this.get( renderTarget ); + const { samples, depthBuffer, stencilBuffer } = renderTarget; + const cubeFace = this.renderer._activeCubeFace; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + + let msaaFb = renderTargetContextData.msaaFrameBuffer; + let depthRenderbuffer = renderTargetContextData.depthRenderbuffer; + + let fb; + + if ( isCube ) { + + if ( renderTargetContextData.cubeFramebuffers === undefined ) { + + renderTargetContextData.cubeFramebuffers = []; + + } + + fb = renderTargetContextData.cubeFramebuffers[ cubeFace ]; + + } else { + + fb = renderTargetContextData.framebuffer; + + } + + if ( fb === undefined ) { + + fb = gl.createFramebuffer(); + + state.bindFramebuffer( gl.FRAMEBUFFER, fb ); + + const textures = renderContext.textures; + + if ( isCube ) { + + renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb; + const { textureGPU } = this.get( textures[ 0 ] ); + + gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 ); + + } else { + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + const textureData = this.get( texture ); + textureData.renderTarget = renderContext.renderTarget; + + const attachment = gl.COLOR_ATTACHMENT0 + i; + + gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 ); + + } + + renderTargetContextData.framebuffer = fb; + + state.drawBuffers( renderContext, fb ); + + } + + if ( renderContext.depthTexture !== null ) { + + const textureData = this.get( renderContext.depthTexture ); + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + + gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 ); + + } + + } + + if ( samples > 0 ) { + + if ( msaaFb === undefined ) { + + const invalidationArray = []; + + msaaFb = gl.createFramebuffer(); + + state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb ); + + const msaaRenderbuffers = []; + + const textures = renderContext.textures; + + for ( let i = 0; i < textures.length; i ++ ) { + + + msaaRenderbuffers[ i ] = gl.createRenderbuffer(); + + gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); + + invalidationArray.push( gl.COLOR_ATTACHMENT0 + i ); + + if ( depthBuffer ) { + + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + invalidationArray.push( depthStyle ); + + } + + const texture = renderContext.textures[ i ]; + const textureData = this.get( texture ); + + gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height ); + gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); + + + } + + renderTargetContextData.msaaFrameBuffer = msaaFb; + renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers; + + if ( depthRenderbuffer === undefined ) { + + depthRenderbuffer = gl.createRenderbuffer(); + this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext ); + + renderTargetContextData.depthRenderbuffer = depthRenderbuffer; + + const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; + invalidationArray.push( depthStyle ); + + } + + renderTargetContextData.invalidationArray = invalidationArray; + + } + + currentFrameBuffer = renderTargetContextData.msaaFrameBuffer; + + } else { + + currentFrameBuffer = fb; + + } + + } + + state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer ); + + } + + + _getVaoKey( index, attributes ) { + + let key = []; + + if ( index !== null ) { + + const indexData = this.get( index ); + + key += ':' + indexData.id; + + } + + for ( let i = 0; i < attributes.length; i ++ ) { + + const attributeData = this.get( attributes[ i ] ); + + key += ':' + attributeData.id; + + } + + return key; + + } + + _createVao( index, attributes ) { + + const { gl } = this; const vaoGPU = gl.createVertexArray(); + let key = ''; - const index = renderObject.getIndex(); - const attributes = renderObject.getAttributes(); + let staticVao = true; gl.bindVertexArray( vaoGPU ); @@ -77358,6 +80361,8 @@ class WebGLBackend extends Backend { gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU ); + key += ':' + indexData.id; + } for ( let i = 0; i < attributes.length; i ++ ) { @@ -77365,9 +80370,13 @@ class WebGLBackend extends Backend { const attribute = attributes[ i ]; const attributeData = this.get( attribute ); + key += ':' + attributeData.id; + gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU ); gl.enableVertexAttribArray( i ); + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false; + let stride, offset; if ( attribute.isInterleavedBufferAttribute === true ) { @@ -77404,304 +80413,101 @@ class WebGLBackend extends Backend { } - gl.bindVertexArray( null ); - - // - - this.set( pipeline, { - programGPU, - vaoGPU - } ); + gl.bindBuffer( gl.ARRAY_BUFFER, null ); - } + this.vaoCache[ key ] = vaoGPU; - createComputePipeline( /*computePipeline, bindings*/ ) { + return { vaoGPU, staticVao }; } - createBindings( bindings ) { - - this.updateBindings( bindings ); - - } - - updateBindings( bindings ) { - - const { gl } = this; - - let groupIndex = 0; - let textureIndex = 0; - - for ( const binding of bindings ) { + _getTransformFeedback( transformBuffers ) { - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + let key = ''; - const bufferGPU = gl.createBuffer(); - const data = binding.buffer; + for ( let i = 0; i < transformBuffers.length; i ++ ) { - gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); - gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); - gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU ); - - this.set( binding, { - index: groupIndex ++, - bufferGPU - } ); - - } else if ( binding.isSampledTexture ) { - - const { textureGPU, glTextureType } = this.get( binding.texture ); - - this.set( binding, { - index: textureIndex ++, - textureGPU, - glTextureType - } ); - - } + key += ':' + transformBuffers[ i ].id; } - } + let transformFeedbackGPU = this.transformFeedbackCache[ key ]; - updateBinding( binding ) { + if ( transformFeedbackGPU !== undefined ) { - const gl = this.gl; - - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - - const bindingData = this.get( binding ); - const bufferGPU = bindingData.bufferGPU; - const data = binding.buffer; - - gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU ); - gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW ); + return transformFeedbackGPU; } - } - - // attributes - - createIndexAttribute( attribute ) { - const gl = this.gl; - this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - - } + transformFeedbackGPU = gl.createTransformFeedback(); - createAttribute( attribute ) { + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); - const gl = this.gl; + for ( let i = 0; i < transformBuffers.length; i ++ ) { - this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); + const attributeData = transformBuffers[ i ]; - } + gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer ); - createStorageAttribute( /*attribute*/ ) { + } - } + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); - updateAttribute( attribute ) { + this.transformFeedbackCache[ key ] = transformFeedbackGPU; - this.attributeUtils.updateAttribute( attribute ); + return transformFeedbackGPU; } - destroyAttribute( attribute ) { - - this.attributeUtils.destroyAttribute( attribute ); - } - - updateSize() { + _setupBindings( bindings, programGPU ) { - //console.warn( 'Abstract class.' ); + const gl = this.gl; - } + for ( const binding of bindings ) { - hasFeature( name ) { + const bindingData = this.get( binding ); + const index = bindingData.index; - const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - const extensions = this.extensions; + const location = gl.getUniformBlockIndex( programGPU, binding.name ); + gl.uniformBlockBinding( programGPU, location, index ); - for ( let i = 0; i < keysMatching.length; i ++ ) { + } else if ( binding.isSampledTexture ) { + const location = gl.getUniformLocation( programGPU, binding.name ); + gl.uniform1i( location, index ); - if ( extensions.has( keysMatching[ i ] ) ) return true; + } } - return false; - } - - getMaxAnisotropy() { - - return this.capabilities.getMaxAnisotropy(); - - } - - copyFramebufferToTexture( texture, renderContext ) { - - this.textureUtils.copyFramebufferToTexture( texture, renderContext ); - - } - - _setFramebuffer( renderContext ) { + _bindUniforms( bindings ) { const { gl, state } = this; - let currentFrameBuffer = null; - - if ( renderContext.textures !== null ) { - - const renderTarget = renderContext.renderTarget; - const renderTargetContextData = this.get( renderTarget ); - const { samples, depthBuffer, stencilBuffer } = renderTarget; - const cubeFace = this.renderer._activeCubeFace; - const isCube = renderTarget.isWebGLCubeRenderTarget === true; - - let msaaFb = renderTargetContextData.msaaFrameBuffer; - let depthRenderbuffer = renderTargetContextData.depthRenderbuffer; - - let fb; - - if ( isCube ) { - - if ( renderTargetContextData.cubeFramebuffers === undefined ) { - - renderTargetContextData.cubeFramebuffers = []; - - } - - fb = renderTargetContextData.cubeFramebuffers[ cubeFace ]; - - } else { - - fb = renderTargetContextData.framebuffer; - - } - - if ( fb === undefined ) { - - fb = gl.createFramebuffer(); - - state.bindFramebuffer( gl.FRAMEBUFFER, fb ); - - const textures = renderContext.textures; - - if ( isCube ) { - - renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb; - const { textureGPU } = this.get( textures[ 0 ] ); - - gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 ); - - } else { - - for ( let i = 0; i < textures.length; i ++ ) { - - const texture = textures[ i ]; - const textureData = this.get( texture ); - textureData.renderTarget = renderContext.renderTarget; - - const attachment = gl.COLOR_ATTACHMENT0 + i; - - gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 ); - - } - - renderTargetContextData.framebuffer = fb; - - state.drawBuffers( renderContext, fb ); - - } - - if ( renderContext.depthTexture !== null ) { - - const textureData = this.get( renderContext.depthTexture ); - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - - gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 ); - - } - - } - - if ( samples > 0 ) { - - if ( msaaFb === undefined ) { - - const invalidationArray = []; - - msaaFb = gl.createFramebuffer(); - - state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb ); - - const msaaRenderbuffers = []; - - const textures = renderContext.textures; - - for ( let i = 0; i < textures.length; i ++ ) { - - - msaaRenderbuffers[ i ] = gl.createRenderbuffer(); - - gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); - - invalidationArray.push( gl.COLOR_ATTACHMENT0 + i ); - - if ( depthBuffer ) { - - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - invalidationArray.push( depthStyle ); - - } - - const texture = renderContext.textures[ i ]; - const textureData = this.get( texture ); - - gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height ); - gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] ); - - - } - - renderTargetContextData.msaaFrameBuffer = msaaFb; - renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers; - - if ( depthRenderbuffer === undefined ) { - - depthRenderbuffer = gl.createRenderbuffer(); - this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext ); - - renderTargetContextData.depthRenderbuffer = depthRenderbuffer; - - const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - invalidationArray.push( depthStyle ); - - } + for ( const binding of bindings ) { - renderTargetContextData.invalidationArray = invalidationArray; + const bindingData = this.get( binding ); + const index = bindingData.index; - } + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { - currentFrameBuffer = renderTargetContextData.msaaFrameBuffer; + gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); - } else { + } else if ( binding.isSampledTexture ) { - currentFrameBuffer = fb; + state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); } } - state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer ); - } } @@ -78033,6 +80839,26 @@ class StorageBuffer extends Buffer { } +let _id = 0; + +class NodeStorageBuffer extends StorageBuffer { + + constructor( nodeUniform ) { + + super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + +} + class WebGPUTexturePassUtils { constructor( device ) { @@ -78623,13 +81449,13 @@ class WebGPUTextureUtils { if ( texture.isDataTexture || texture.isData3DTexture ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, false ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY ); } else if ( texture.isDataArrayTexture ) { for ( let i = 0; i < options.image.depth; i ++ ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, false, i ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i ); } @@ -78670,6 +81496,9 @@ class WebGPUTextureUtils { const format = textureData.textureDescriptorGPU.format; const bytesPerTexel = this._getBytesPerTexel( format ); + let bytesPerRow = width * bytesPerTexel; + bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes + const readBuffer = device.createBuffer( { size: width * height * bytesPerTexel, @@ -78686,7 +81515,7 @@ class WebGPUTextureUtils { }, { buffer: readBuffer, - bytesPerRow: width * bytesPerTexel + bytesPerRow: bytesPerRow }, { width: width, @@ -78975,15 +81804,57 @@ class WebGPUTextureUtils { _getBytesPerTexel( format ) { - if ( format === GPUTextureFormat.R8Unorm ) return 1; - if ( format === GPUTextureFormat.R16Float ) return 2; - if ( format === GPUTextureFormat.RG8Unorm ) return 2; - if ( format === GPUTextureFormat.RG16Float ) return 4; - if ( format === GPUTextureFormat.R32Float ) return 4; - if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4; - if ( format === GPUTextureFormat.RG32Float ) return 8; - if ( format === GPUTextureFormat.RGBA16Float ) return 8; - if ( format === GPUTextureFormat.RGBA32Float ) return 16; + // 8-bit formats + if ( format === GPUTextureFormat.R8Unorm || + format === GPUTextureFormat.R8Snorm || + format === GPUTextureFormat.R8Uint || + format === GPUTextureFormat.R8Sint ) return 1; + + // 16-bit formats + if ( format === GPUTextureFormat.R16Uint || + format === GPUTextureFormat.R16Sint || + format === GPUTextureFormat.R16Float || + format === GPUTextureFormat.RG8Unorm || + format === GPUTextureFormat.RG8Snorm || + format === GPUTextureFormat.RG8Uint || + format === GPUTextureFormat.RG8Sint ) return 2; + + // 32-bit formats + if ( format === GPUTextureFormat.R32Uint || + format === GPUTextureFormat.R32Sint || + format === GPUTextureFormat.R32Float || + format === GPUTextureFormat.RG16Uint || + format === GPUTextureFormat.RG16Sint || + format === GPUTextureFormat.RG16Float || + format === GPUTextureFormat.RGBA8Unorm || + format === GPUTextureFormat.RGBA8UnormSRGB || + format === GPUTextureFormat.RGBA8Snorm || + format === GPUTextureFormat.RGBA8Uint || + format === GPUTextureFormat.RGBA8Sint || + format === GPUTextureFormat.BGRA8Unorm || + format === GPUTextureFormat.BGRA8UnormSRGB || + // Packed 32-bit formats + format === GPUTextureFormat.RGB9E5UFloat || + format === GPUTextureFormat.RGB10A2Unorm || + format === GPUTextureFormat.RG11B10UFloat || + format === GPUTextureFormat.Depth32Float || + format === GPUTextureFormat.Depth24Plus || + format === GPUTextureFormat.Depth24PlusStencil8 || + format === GPUTextureFormat.Depth32FloatStencil8 ) return 4; + + // 64-bit formats + if ( format === GPUTextureFormat.RG32Uint || + format === GPUTextureFormat.RG32Sint || + format === GPUTextureFormat.RG32Float || + format === GPUTextureFormat.RGBA16Uint || + format === GPUTextureFormat.RGBA16Sint || + format === GPUTextureFormat.RGBA16Float ) return 8; + + // 128-bit formats + if ( format === GPUTextureFormat.RGBA32Uint || + format === GPUTextureFormat.RGBA32Sint || + format === GPUTextureFormat.RGBA32Float ) return 16; + } @@ -79009,6 +81880,9 @@ class WebGPUTextureUtils { if ( format === GPUTextureFormat.RG16Sint ) return Int16Array; if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array; if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array; + if ( format === GPUTextureFormat.R16Float ) return Float32Array; + if ( format === GPUTextureFormat.RG16Float ) return Float32Array; + if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array; if ( format === GPUTextureFormat.R32Uint ) return Uint32Array; @@ -79021,6 +81895,17 @@ class WebGPUTextureUtils { if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array; if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array; + if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array; + if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array; + if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array; + if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array; + if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array; + + if ( format === GPUTextureFormat.Depth32Float ) return Float32Array; + if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array; + if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array; + if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array; + } _getDimension( texture ) { @@ -79051,7 +81936,7 @@ function getFormat( texture, device = null ) { let formatGPU; - if ( /*texture.isRenderTargetTexture === true ||*/ texture.isFramebufferTexture === true ) { + if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) { formatGPU = GPUTextureFormat.BGRA8Unorm; @@ -79360,7 +82245,7 @@ class WGSLNodeParser extends NodeParser { } // GPUShaderStage is not defined in browsers not supporting WebGPU -const GPUShaderStage = window.GPUShaderStage; +const GPUShaderStage = self.GPUShaderStage; const gpuShaderStageLib = { 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1, @@ -79369,7 +82254,8 @@ const gpuShaderStageLib = { }; const supports = { - instance: true + instance: true, + storageBuffer: true }; const wgslFnOpLib = { @@ -79398,6 +82284,11 @@ const wgslTypeLib = { uvec4: 'vec4', bvec4: 'vec4', + mat2: 'mat2x2', + imat2: 'mat2x2', + umat2: 'mat2x2', + bmat2: 'mat2x2', + mat3: 'mat3x3', imat3: 'mat3x3', umat3: 'mat3x3', @@ -79416,6 +82307,10 @@ const wgslMethods = { mod_vec2: 'threejs_mod_vec2', mod_vec3: 'threejs_mod_vec3', mod_vec4: 'threejs_mod_vec4', + equals_bool: 'threejs_equals_bool', + equals_bvec2: 'threejs_equals_bvec2', + equals_bvec3: 'threejs_equals_bvec3', + equals_bvec4: 'threejs_equals_bvec4', lessThanEqual: 'threejs_lessThanEqual', greaterThan: 'threejs_greaterThan', inversesqrt: 'inverseSqrt', @@ -79448,6 +82343,10 @@ fn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 { mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ), mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ), mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ), + equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ), + equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }' ), + equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }' ), + equals_bvec4: new CodeNode( 'fn threejs_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: new CodeNode( ` fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 { @@ -79547,6 +82446,12 @@ class WGSLNodeBuilder extends NodeBuilder { } + generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) { + + return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`; + + } + isUnfilterable( texture ) { return texture.isDataTexture === true && texture.type === FloatType; @@ -79618,7 +82523,7 @@ class WGSLNodeBuilder extends NodeBuilder { const name = node.name; const type = node.type; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { return name; @@ -79671,11 +82576,11 @@ class WGSLNodeBuilder extends NodeBuilder { const bindings = this.bindings[ shaderStage ]; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { let texture = null; - if ( type === 'texture' ) { + if ( type === 'texture' || type === 'storageTexture' ) { texture = new NodeSampledTexture( uniformNode.name, uniformNode.node ); @@ -79707,8 +82612,8 @@ class WGSLNodeBuilder extends NodeBuilder { } else if ( type === 'buffer' || type === 'storageBuffer' ) { - const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer; - const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value ); + const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer; + const buffer = new bufferClass( node ); buffer.setVisibility( gpuShaderStageLib[ shaderStage ] ); bindings.push( buffer ); @@ -79735,31 +82640,9 @@ class WGSLNodeBuilder extends NodeBuilder { } - if ( node.isArrayUniformNode === true ) { - - uniformGPU = []; - - for ( const uniformNode of node.nodes ) { - - const uniformNodeGPU = this.getNodeUniform( uniformNode, type ); - - // fit bounds to buffer - uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize ); - uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize ); - - uniformsGroup.addUniform( uniformNodeGPU ); - - uniformGPU.push( uniformNodeGPU ); - - } - - } else { - - uniformGPU = this.getNodeUniform( uniformNode, type ); - - uniformsGroup.addUniform( uniformGPU ); + uniformGPU = this.getNodeUniform( uniformNode, type ); - } + uniformsGroup.addUniform( uniformGPU ); } @@ -80058,7 +82941,7 @@ ${ flowData.code } for ( const uniform of uniforms ) { - if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' ) { + if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) { const texture = uniform.node.value; @@ -80130,17 +83013,7 @@ ${ flowData.code } snippets: [] } ); - if ( Array.isArray( uniform.value ) === true ) { - - const length = uniform.value.length; - - group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` ); - - } else { - - group.snippets.push( `\t${uniform.name} : ${ vectorType}` ); - - } + group.snippets.push( `\t${ uniform.name } : ${ vectorType }` ); } @@ -80555,7 +83428,21 @@ class WebGPUAttributeUtils { const device = backend.device; - const array = bufferAttribute.array; + let array = bufferAttribute.array; + + if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) { + + bufferAttribute.itemSize = 4; + array = new array.constructor( bufferAttribute.count * 4 ); + + for ( let i = 0; i < bufferAttribute.count; i ++ ) { + + array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 ); + + } + + } + const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441 buffer = device.createBuffer( { @@ -81025,7 +83912,7 @@ class WebGPUPipelineUtils { } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const { object, material, geometry, pipeline } = renderObject; const { vertexProgram, fragmentProgram } = pipeline; @@ -81119,7 +84006,7 @@ class WebGPUPipelineUtils { } - pipelineData.pipeline = device.createRenderPipeline( { + const pipelineDescriptor = { vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ), fragment: Object.assign( {}, fragmentModule, { targets } ), primitive: primitiveState, @@ -81139,7 +84026,28 @@ class WebGPUPipelineUtils { layout: device.createPipelineLayout( { bindGroupLayouts: [ bindingsData.layout ] } ) - } ); + }; + + if ( promises === null ) { + + pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor ); + + } else { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => { + + pipelineData.pipeline = pipeline; + resolve(); + + } ); + + } ); + + promises.push( p ); + + } } @@ -81550,16 +84458,6 @@ class WebGPUPipelineUtils { import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js'; //*/ -// statics - -let _staticAdapter = null; - -if ( navigator.gpu !== undefined ) { - - _staticAdapter = await navigator.gpu.requestAdapter(); - -} - // class WebGPUBackend extends Backend { @@ -81587,10 +84485,13 @@ class WebGPUBackend extends Backend { this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits; + this.trackTimestamp = ( parameters.trackTimestamp === true ); + this.adapter = null; this.device = null; this.context = null; this.colorBuffer = null; + this.defaultRenderPassdescriptor = null; this.utils = new WebGPUUtils( this ); this.attributeUtils = new WebGPUAttributeUtils( this ); @@ -81681,60 +84582,88 @@ class WebGPUBackend extends Backend { } - beginRender( renderContext ) { + _getDefaultRenderPassDescriptor() { - const renderContextData = this.get( renderContext ); + let descriptor = this.defaultRenderPassdescriptor; - const device = this.device; - const occlusionQueryCount = renderContext.occlusionQueryCount; + const antialias = this.parameters.antialias; - let occlusionQuerySet; + if ( descriptor === null ) { - if ( occlusionQueryCount > 0 ) { + const renderer = this.renderer; - if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); - if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + descriptor = { + colorAttachments: [ { + view: null + } ], + depthStencilAttachment: { + view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() + } + }; - // Get a reference to the array of objects with queries. The renderContextData property - // can be changed by another render pass before the buffer.mapAsyc() completes. - renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; - renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; - renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + const colorAttachment = descriptor.colorAttachments[ 0 ]; - // + if ( antialias === true ) { - occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + colorAttachment.view = this.colorBuffer.createView(); - renderContextData.occlusionQuerySet = occlusionQuerySet; - renderContextData.occlusionQueryIndex = 0; - renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + } else { - renderContextData.lastOcclusionObject = null; + colorAttachment.resolveTarget = undefined; - } + } - const descriptor = { - colorAttachments: [ { - view: null - } ], - depthStencilAttachment: { - view: null - }, - occlusionQuerySet - }; + this.defaultRenderPassdescriptor = descriptor; + + } const colorAttachment = descriptor.colorAttachments[ 0 ]; - const depthStencilAttachment = descriptor.depthStencilAttachment; - const antialias = this.parameters.antialias; + if ( antialias === true ) { - if ( renderContext.textures !== null ) { + colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - const textures = renderContext.textures; + } else { - descriptor.colorAttachments = []; + colorAttachment.view = this.context.getCurrentTexture().createView(); - const colorAttachments = descriptor.colorAttachments; + } + + return descriptor; + + } + + _getRenderPassDescriptor( renderContext ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetData = this.get( renderTarget ); + + let descriptors = renderTargetData.descriptors; + + if ( descriptors === undefined ) { + + descriptors = []; + + renderTargetData.descriptors = descriptors; + + } + + if ( renderTargetData.width !== renderTarget.width || + renderTargetData.height !== renderTarget.height || + renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel || + renderTargetData.samples !== renderTarget.samples + ) { + + descriptors.length = 0; + + } + + let descriptor = descriptors[ renderContext.activeCubeFace ]; + + if ( descriptor === undefined ) { + + const textures = renderContext.textures; + const colorAttachments = []; for ( let i = 0; i < textures.length; i ++ ) { @@ -81772,32 +84701,78 @@ class WebGPUBackend extends Backend { const depthTextureData = this.get( renderContext.depthTexture ); - depthStencilAttachment.view = depthTextureData.texture.createView(); + const depthStencilAttachment = { + view: depthTextureData.texture.createView(), + }; - if ( renderContext.stencil && renderContext.depthTexture.format === DepthFormat ) { + descriptor = { + colorAttachments, + depthStencilAttachment + }; - renderContext.stencil = false; + descriptors[ renderContext.activeCubeFace ] = descriptor; - } + renderTargetData.width = renderTarget.width; + renderTargetData.height = renderTarget.height; + renderTargetData.samples = renderTarget.samples; + renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel; - } else { + } - if ( antialias === true ) { + return descriptor; - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); + } - } else { + beginRender( renderContext ) { - colorAttachment.view = this.context.getCurrentTexture().createView(); - colorAttachment.resolveTarget = undefined; + const renderContextData = this.get( renderContext ); - } + const device = this.device; + const occlusionQueryCount = renderContext.occlusionQueryCount; - depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ).createView(); + let occlusionQuerySet; + + if ( occlusionQueryCount > 0 ) { + + if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); + if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + + // Get a reference to the array of objects with queries. The renderContextData property + // can be changed by another render pass before the buffer.mapAsyc() completes. + renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; + renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; + renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + + // + + occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + + renderContextData.occlusionQuerySet = occlusionQuerySet; + renderContextData.occlusionQueryIndex = 0; + renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + + renderContextData.lastOcclusionObject = null; } + let descriptor; + + if ( renderContext.textures === null ) { + + descriptor = this._getDefaultRenderPassDescriptor(); + + } else { + + descriptor = this._getRenderPassDescriptor( renderContext ); + + } + + this.initTimestampQuery( renderContext, descriptor ); + + descriptor.occlusionQuerySet = occlusionQuerySet; + + const depthStencilAttachment = descriptor.depthStencilAttachment; + if ( renderContext.textures !== null ) { const colorAttachments = descriptor.colorAttachments; @@ -81821,9 +84796,10 @@ class WebGPUBackend extends Backend { } - } else { + const colorAttachment = descriptor.colorAttachments[ 0 ]; + if ( renderContext.clearColor ) { colorAttachment.clearValue = renderContext.clearColorValue; @@ -81960,8 +84936,11 @@ class WebGPUBackend extends Backend { } + this.prepareTimestampBuffer( renderContext, renderContextData.encoder ); + this.device.queue.submit( [ renderContextData.encoder.finish() ] ); + // if ( renderContext.textures !== null ) { @@ -82012,7 +84991,7 @@ class WebGPUBackend extends Backend { const buffer = currentOcclusionQueryBuffer.getMappedRange(); const results = new BigUint64Array( buffer ); - for ( let i = 0; i < currentOcclusionQueryObjects.length; i++ ) { + for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) { if ( results[ i ] !== 0n ) { @@ -82033,7 +85012,7 @@ class WebGPUBackend extends Backend { updateViewport( renderContext ) { const { currentPass } = this.get( renderContext ); - let { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; + const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth ); @@ -82044,7 +85023,7 @@ class WebGPUBackend extends Backend { const device = this.device; const renderer = this.renderer; - const colorAttachments = []; + let colorAttachments = []; let depthStencilAttachment; let clearValue; @@ -82065,39 +85044,23 @@ class WebGPUBackend extends Backend { supportsDepth = renderer.depth; supportsStencil = renderer.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; + const descriptor = this._getDefaultRenderPassDescriptor(); if ( color ) { - const antialias = this.parameters.antialias; - - const colorAttachment = {}; + colorAttachments = descriptor.colorAttachments; - if ( antialias === true ) { - - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - - } else { - - colorAttachment.view = this.context.getCurrentTexture().createView(); - - } + const colorAttachment = colorAttachments[ 0 ]; colorAttachment.clearValue = clearValue; colorAttachment.loadOp = GPULoadOp.Clear; colorAttachment.storeOp = GPUStoreOp.Store; - colorAttachments.push( colorAttachment ); - } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { - depthStencilAttachment = { - view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() - }; + depthStencilAttachment = descriptor.depthStencilAttachment; } @@ -82106,9 +85069,6 @@ class WebGPUBackend extends Backend { supportsDepth = renderTargetData.depth; supportsStencil = renderTargetData.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; - if ( color ) { for ( const texture of renderTargetData.textures ) { @@ -82142,7 +85102,7 @@ class WebGPUBackend extends Backend { } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { const depthTextureData = this.get( renderTargetData.depthTexture ); @@ -82156,7 +85116,7 @@ class WebGPUBackend extends Backend { // - if ( depthStencilAttachment !== undefined ) { + if ( supportsDepth ) { if ( depth ) { @@ -82171,7 +85131,11 @@ class WebGPUBackend extends Backend { } - // + } + + // + + if ( supportsStencil ) { if ( stencil ) { @@ -82208,8 +85172,14 @@ class WebGPUBackend extends Backend { const groupGPU = this.get( computeGroup ); - groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( {} ); - groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass(); + + const descriptor = {}; + + this.initTimestampQuery( computeGroup, descriptor ); + + groupGPU.cmdEncoderGPU = this.device.createCommandEncoder(); + + groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor ); } @@ -82236,6 +85206,9 @@ class WebGPUBackend extends Backend { const groupData = this.get( computeGroup ); groupData.passEncoderGPU.end(); + + this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU ); + this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] ); } @@ -82312,7 +85285,7 @@ class WebGPUBackend extends Backend { // occlusion queries - handle multiple consecutive draw calls for an object - if ( contextData.occlusionQuerySet !== undefined ) { + if ( contextData.occlusionQuerySet !== undefined ) { const lastObject = contextData.lastOcclusionObject; @@ -82396,7 +85369,8 @@ class WebGPUBackend extends Backend { data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage || data.sampleCount !== sampleCount || data.colorSpace !== colorSpace || data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat || - data.primitiveTopology !== primitiveTopology + data.primitiveTopology !== primitiveTopology || + data.clippingContextVersion !== renderObject.clippingContextVersion ) { data.material = material; data.materialVersion = material.version; @@ -82414,6 +85388,7 @@ class WebGPUBackend extends Backend { data.colorFormat = colorFormat; data.depthStencilFormat = depthStencilFormat; data.primitiveTopology = primitiveTopology; + data.clippingContextVersion = renderObject.clippingContextVersion; needsUpdate = true; @@ -82442,7 +85417,8 @@ class WebGPUBackend extends Backend { material.side, utils.getSampleCount( renderContext ), utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ), - utils.getPrimitiveTopology( object, material ) + utils.getPrimitiveTopology( object, material ), + renderObject.clippingContextVersion ].join(); } @@ -82497,6 +85473,87 @@ class WebGPUBackend extends Backend { } + + initTimestampQuery( renderContext, descriptor ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + if ( ! renderContextData.timeStampQuerySet ) { + + // Create a GPUQuerySet which holds 2 timestamp query results: one for the + // beginning and one for the end of compute pass execution. + const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } ); + + const timestampWrites = { + querySet: timeStampQuerySet, + beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins. + endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends. + }; + Object.assign( descriptor, { + timestampWrites, + } ); + renderContextData.timeStampQuerySet = timeStampQuerySet; + + } + + } + + // timestamp utils + + prepareTimestampBuffer( renderContext, encoder ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + const size = 2 * BigInt64Array.BYTES_PER_ELEMENT; + const resolveBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC, + } ); + + const resultBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + } ); + + encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 ); + encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size ); + + renderContextData.currentTimestampQueryBuffer = resultBuffer; + + } + + async resolveTimestampAsync( renderContext, type = 'render' ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + // handle timestamp query results + + const { currentTimestampQueryBuffer } = renderContextData; + + if ( currentTimestampQueryBuffer ) { + + renderContextData.currentTimestampQueryBuffer = null; + + await currentTimestampQueryBuffer.mapAsync( GPUMapMode.READ ); + + const times = new BigUint64Array( currentTimestampQueryBuffer.getMappedRange() ); + + const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000; + // console.log( `Compute ${type} duration: ${Number( times[ 1 ] - times[ 0 ] ) / 1000000}ms` ); + this.renderer.info.updateTimestamp( type, duration ); + + currentTimestampQueryBuffer.unmap(); + + } + + } + // node builder createNodeBuilder( object, renderer, scene = null ) { @@ -82526,9 +85583,9 @@ class WebGPUBackend extends Backend { // pipelines - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { - this.pipelineUtils.createRenderPipeline( renderObject ); + this.pipelineUtils.createRenderPipeline( renderObject, promises ); } @@ -82595,7 +85652,8 @@ class WebGPUBackend extends Backend { updateSize() { this.colorBuffer = this.textureUtils.getColorBuffer(); - + this.defaultRenderPassdescriptor = null; + } // utils public @@ -82606,9 +85664,9 @@ class WebGPUBackend extends Backend { } - hasFeature( name ) { + async hasFeatureAsync( name ) { - const adapter = this.adapter || _staticAdapter; + const adapter = this.adapter || await WebGPU.getStaticAdapter(); // @@ -82616,6 +85674,18 @@ class WebGPUBackend extends Backend { } + hasFeature( name ) { + + if ( ! this.adapter ) { + + return false; + + } + + return this.adapter.features.has( name ); + + } + copyFramebufferToTexture( texture, renderContext ) { const renderContextData = this.get( renderContext ); @@ -82624,18 +85694,40 @@ class WebGPUBackend extends Backend { let sourceGPU = null; - if ( texture.isFramebufferTexture ) { + if ( renderContext.renderTarget ) { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.get( renderContext.depthTexture ).texture; + + } else { + + sourceGPU = this.get( renderContext.textures[ 0 ] ).texture; + + } + + } else { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); - sourceGPU = this.context.getCurrentTexture(); + } else { - } else if ( texture.isDepthTexture ) { + sourceGPU = this.context.getCurrentTexture(); - sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); + } } const destinationGPU = this.get( texture ).texture; + if ( sourceGPU.format !== destinationGPU.format ) { + + return; + + } + renderContextData.currentPass.end(); encoder.copyTextureToTexture( @@ -82685,7 +85777,11 @@ class WebGPURenderer extends Renderer { let BackendClass; - if ( WebGPU.isAvailable() ) { + if ( parameters.forceWebGL ) { + + BackendClass = WebGLBackend; + + } else if ( WebGPU.isAvailable() ) { BackendClass = WebGPUBackend; @@ -82736,4 +85832,4 @@ class WebGPUGLRenderer extends Renderer { } -export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrayUniformNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BitangentNode, BlendModeNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CameraNode, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CheckerNode, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorAdjustmentNode, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, CondNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, DiscardNode, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HashNode, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightNode, LightProbe, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NormalNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PackingNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionNode, PositionalAudio, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, 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, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RedFormat, RedIntegerFormat, ReferenceNode, ReflectVectorNode, ReinhardToneMapping, RemapNode, RenderTarget, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, RotateUVNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderChunk, ShaderLib, ShaderMaterial, ShaderNode, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, SpecularMIPLevelNode, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageBufferNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentNode, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, TextureBicubicNode, TextureLoader, TextureNode, TextureStoreNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, UVNode, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils$1 as WebGLUtils, WebGPU, WebGPUCoordinateSystem, WebGPUGLRenderer, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, and, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, bitAnd, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createCanvasElement, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, degrees, densityFog, depth, depthPass, depthPixel, depthTexture, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dot, dynamicBufferAttribute, element, equal, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lessThan, lessThanEqual, lightNodes, lightTargetDirection, lightingContext, lights, linearToColorSpace, linearTosRGB, log, log2, loop, lumaCoeffs, luminance, mat3, mat4, matcapUV, materialAlphaTest, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecularColor, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, morph, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parameter, pass, perspectiveDepthToViewZ, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, range, rangeFog, reciprocal, reference, referenceIndex, reflect, reflectVector, refract, remainder, remap, remapClamp, renderGroup, rotateUV, roughness, round, sRGBEncoding, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shader, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, skinning, smoothstep, specularColor, specularMIPLevel, split, spritesheetUV, sqrt, stack, step, storage, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, textureBicubic, textureLoad, textureStore, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat3, umat4, uniform, uniformGroup, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor }; +export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnamorphicNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BitangentNode, BlendModeNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CameraNode, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CheckerNode, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorAdjustmentNode, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, CondNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, DiscardNode, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HashNode, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightNode, LightProbe, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NormalNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PI, PI2, PMREMGenerator, PackingNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionNode, PositionalAudio, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, 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, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RedFormat, RedIntegerFormat, ReferenceNode, ReflectVectorNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderTarget, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, RotateNode, RotateUVNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderChunk, ShaderLib, ShaderMaterial, ShaderNode, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, SpecularMIPLevelNode, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentNode, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, TextureBicubicNode, TextureLoader, TextureNode, TextureStoreNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, UVNode, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UniformsLib, UniformsNode, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils$1 as WebGLUtils, WebGPU, WebGPUCoordinateSystem, WebGPUGLRenderer, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, all, anamorphic, and, any, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bmat2, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createCanvasElement, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, degrees, densityFog, depth, depthPass, depthPixel, depthTexture, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dot, dynamicBufferAttribute, element, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat2, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, lightsNode, linearToColorSpace, linearTosRGB, log, log2, loop, lumaCoeffs, luminance, mat2, mat3, mat4, matcapUV, materialAlphaTest, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecularColor, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, morphReference, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, pcurve, perspectiveDepthToViewZ, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflector, refract, remainder, remap, remapClamp, renderGroup, rotate, rotateUV, roughness, round, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shader, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, smoothstep, specularColor, specularMIPLevel, split, spritesheetUV, sqrt, stack, step, storage, storageObject, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, textureBicubic, textureLoad, textureStore, threshold, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat2, umat3, umat4, uniform, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor }; diff --git a/build/three-webgpu.module.min.js b/build/three-webgpu.module.min.js index 0073b23..b26421e 100644 --- a/build/three-webgpu.module.min.js +++ b/build/three-webgpu.module.min.js @@ -8,4 +8,4 @@ * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ -const e="161dev",t={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},n={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,s=2,a=3,o=0,l=1,c=2,u=3,h=0,d=1,p=2,m=0,f=1,g=2,_=3,v=4,x=5,y=100,b=101,S=102,T=103,M=104,E=200,A=201,w=202,R=203,C=204,N=205,L=206,P=207,I=208,U=209,O=210,D=211,F=212,B=213,V=214,z=0,G=1,k=2,H=3,W=4,X=5,j=6,q=7,Y=0,$=1,Z=2,K=0,J=1,Q=2,ee=3,te=4,ne=5,ie=6,re="attached",se="detached",ae=300,oe=301,le=302,ce=303,ue=304,he=306,de=1e3,pe=1001,me=1002,fe=1003,ge=1004,_e=1004,ve=1005,xe=1005,ye=1006,be=1007,Se=1007,Te=1008,Me=1008,Ee=1009,Ae=1010,we=1011,Re=1012,Ce=1013,Ne=1014,Le=1015,Pe=1016,Ie=1017,Ue=1018,Oe=1020,De=1021,Fe=1023,Be=1024,Ve=1025,ze=1026,Ge=1027,ke=1028,He=1029,We=1030,Xe=1031,je=1033,qe=33776,Ye=33777,$e=33778,Ze=33779,Ke=35840,Je=35841,Qe=35842,et=35843,tt=36196,nt=37492,it=37496,rt=37808,st=37809,at=37810,ot=37811,lt=37812,ct=37813,ut=37814,ht=37815,dt=37816,pt=37817,mt=37818,ft=37819,gt=37820,_t=37821,vt=36492,xt=36494,yt=36495,bt=36283,St=36284,Tt=36285,Mt=36286,Et=2200,At=2201,wt=2202,Rt=2300,Ct=2301,Nt=2302,Lt=2400,Pt=2401,It=2402,Ut=2500,Ot=2501,Dt=0,Ft=1,Bt=2,Vt=3e3,zt=3001,Gt=3200,kt=3201,Ht=0,Wt=1,Xt="",jt="srgb",qt="srgb-linear",Yt="display-p3",$t="display-p3-linear",Zt="linear",Kt="srgb",Jt="rec709",Qt="p3",en=0,tn=7680,nn=7681,rn=7682,sn=7683,an=34055,on=34056,ln=5386,cn=512,un=513,hn=514,dn=515,pn=516,mn=517,fn=518,gn=519,_n=512,vn=513,xn=514,yn=515,bn=516,Sn=517,Tn=518,Mn=519,En=35044,An=35048,wn=35040,Rn=35045,Cn=35049,Nn=35041,Ln=35046,Pn=35050,In=35042,Un="100",On="300 es",Dn=1035,Fn=2e3,Bn=2001;class Vn{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[e]&&-1!==n[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const n=this._listeners[e];if(void 0!==n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const n=t.slice(0);for(let t=0,i=n.length;t>8&255]+zn[e>>16&255]+zn[e>>24&255]+"-"+zn[255&t]+zn[t>>8&255]+"-"+zn[t>>16&15|64]+zn[t>>24&255]+"-"+zn[63&n|128]+zn[n>>8&255]+"-"+zn[n>>16&255]+zn[n>>24&255]+zn[255&i]+zn[i>>8&255]+zn[i>>16&255]+zn[i>>24&255]).toLowerCase()}function Xn(e,t,n){return Math.max(t,Math.min(n,e))}function jn(e,t){return(e%t+t)%t}function qn(e,t,n){return(1-n)*e+n*t}function Yn(e){return 0==(e&e-1)&&0!==e}function $n(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function Zn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function Kn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Jn={DEG2RAD:kn,RAD2DEG:Hn,generateUUID:Wn,clamp:Xn,euclideanModulo:jn,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:qn,damp:function(e,t,n,i){return qn(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(jn(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Gn=e);let t=Gn+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*kn},radToDeg:function(e){return e*Hn},isPowerOfTwo:Yn,ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:$n,setQuaternionFromProperEuler:function(e,t,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((t+i)/2),u=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),m=a((i-t)/2);switch(r){case"XYX":e.set(o*u,l*h,l*d,o*c);break;case"YZY":e.set(l*d,o*u,l*h,o*c);break;case"ZXZ":e.set(l*h,l*d,o*u,o*c);break;case"XZX":e.set(o*u,l*m,l*p,o*c);break;case"YXY":e.set(l*p,o*u,l*m,o*c);break;case"ZYZ":e.set(l*m,l*p,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Kn,denormalize:Zn};class Qn{constructor(e=0,t=0){Qn.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Xn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ei{constructor(e,t,n,i,r,s,a,o,l){ei.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const c=this.elements;return c[0]=e,c[1]=i,c[2]=a,c[3]=t,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],u=n[7],h=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],_=i[1],v=i[4],x=i[7],y=i[2],b=i[5],S=i[8];return r[0]=s*m+a*_+o*y,r[3]=s*f+a*v+o*b,r[6]=s*g+a*x+o*S,r[1]=l*m+c*_+u*y,r[4]=l*f+c*v+u*b,r[7]=l*g+c*x+u*S,r[2]=h*m+d*_+p*y,r[5]=h*f+d*v+p*b,r[8]=h*g+d*x+p*S,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8];return t*s*c-t*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=c*s-a*l,h=a*o-c*r,d=l*r-s*o,p=t*u+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(i*l-c*n)*m,e[2]=(a*n-i*s)*m,e[3]=h*m,e[4]=(c*t-i*o)*m,e[5]=(i*r-a*t)*m,e[6]=d*m,e[7]=(n*o-l*t)*m,e[8]=(s*t-n*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(ti.makeScale(e,t)),this}rotate(e){return this.premultiply(ti.makeRotation(-e)),this}translate(e,t){return this.premultiply(ti.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const ti=new ei;function ni(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}const ii={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function ri(e,t){return new ii[e](t)}function si(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function ai(){const e=si("canvas");return e.style.display="block",e}const oi={};function li(e){e in oi||(oi[e]=!0,console.warn(e))}const ci=(new ei).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),ui=(new ei).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),hi={[qt]:{transfer:Zt,primaries:Jt,toReference:e=>e,fromReference:e=>e},[jt]:{transfer:Kt,primaries:Jt,toReference:e=>e.convertSRGBToLinear(),fromReference:e=>e.convertLinearToSRGB()},[$t]:{transfer:Zt,primaries:Qt,toReference:e=>e.applyMatrix3(ui),fromReference:e=>e.applyMatrix3(ci)},[Yt]:{transfer:Kt,primaries:Qt,toReference:e=>e.convertSRGBToLinear().applyMatrix3(ui),fromReference:e=>e.applyMatrix3(ci).convertLinearToSRGB()}},di=new Set([qt,$t]),pi={enabled:!0,_workingColorSpace:qt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(e){if(!di.has(e))throw new Error(`Unsupported working color space, "${e}".`);this._workingColorSpace=e},convert:function(e,t,n){if(!1===this.enabled||t===n||!t||!n)return e;const i=hi[t].toReference;return(0,hi[n].fromReference)(i(e))},fromWorkingColorSpace:function(e,t){return this.convert(e,this._workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this._workingColorSpace)},getPrimaries:function(e){return hi[e].primaries},getTransfer:function(e){return e===Xt?Zt:hi[e].transfer}};function mi(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function fi(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let gi;class _i{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===gi&&(gi=si("canvas")),gi.width=e.width,gi.height=e.height;const n=gi.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=gi}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=si("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==ae)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case de:e.x=e.x-Math.floor(e.x);break;case pe:e.x=e.x<0?0:1;break;case me:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case de:e.y=e.y-Math.floor(e.y);break;case pe:e.y=e.y<0?0:1;break;case me:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return li("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===jt?zt:Vt}set encoding(e){li("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===zt?jt:Xt}}Si.DEFAULT_IMAGE=null,Si.DEFAULT_MAPPING=ae,Si.DEFAULT_ANISOTROPY=1;class Ti{constructor(e=0,t=0,n=0,i=1){Ti.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const s=.01,a=.1,o=e.elements,l=o[0],c=o[4],u=o[8],h=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-h)o&&e>_?e_?o=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,t*n);e=Math.sin(e*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*e+h*r,l=l*e+d*r,c=c*e+p*r,u=u*e+m*r,e===1-a){const e=1/Math.sqrt(o*o+l*l+c*c+u*u);o*=e,l*=e,c*=e,u*=e}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],u=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+c*u+o*d-l*h,e[t+1]=o*p+c*h+l*u-a*d,e[t+2]=l*p+c*d+a*h-o*u,e[t+3]=c*p-a*u-o*h-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),u=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*c*u+l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u-h*d*p;break;case"YXZ":this._x=h*c*u+l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u+h*d*p;break;case"ZXY":this._x=h*c*u-l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u-h*d*p;break;case"ZYX":this._x=h*c*u-l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u+h*d*p;break;case"YZX":this._x=h*c*u+l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u-h*d*p;break;case"XZY":this._x=h*c*u-l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u+h*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],c=t[6],u=t[10],h=n+a+u;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(c-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>u){const e=2*Math.sqrt(1+n-a-u);this._w=(c-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>u){const e=2*Math.sqrt(1+a-n-u);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+c)/e}else{const e=2*Math.sqrt(1+u-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+c)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Xn(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*e._w+n*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*s+t*this._w,this._x=e*n+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),u=Math.sin((1-t)*c)/l,h=Math.sin(t*c)/l;return this._w=s*u+this._w*h,this._x=n*u+this._x*h,this._y=i*u+this._y*h,this._z=r*u+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=Math.random(),t=Math.sqrt(1-e),n=Math.sqrt(e),i=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(t*Math.cos(i),n*Math.sin(r),n*Math.cos(r),t*Math.sin(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Pi{constructor(e=0,t=0,n=0){Pi.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ui.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ui.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),c=2*(a*t-r*i),u=2*(r*n-s*t);return this.x=t+o*l+s*u-a*c,this.y=n+o*c+a*l-r*u,this.z=i+o*u+r*c-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Ii.copy(this).projectOnVector(e),this.sub(Ii)}reflect(e){return this.sub(Ii.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Xn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=2*(Math.random()-.5),t=Math.random()*Math.PI*2,n=Math.sqrt(1-e**2);return this.x=n*Math.cos(t),this.y=n*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ii=new Pi,Ui=new Li;class Oi{constructor(e=new Pi(1/0,1/0,1/0),t=new Pi(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,Fi),Fi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Xi),ji.subVectors(this.max,Xi),Vi.subVectors(e.a,Xi),zi.subVectors(e.b,Xi),Gi.subVectors(e.c,Xi),ki.subVectors(zi,Vi),Hi.subVectors(Gi,zi),Wi.subVectors(Vi,Gi);let t=[0,-ki.z,ki.y,0,-Hi.z,Hi.y,0,-Wi.z,Wi.y,ki.z,0,-ki.x,Hi.z,0,-Hi.x,Wi.z,0,-Wi.x,-ki.y,ki.x,0,-Hi.y,Hi.x,0,-Wi.y,Wi.x,0];return!!$i(t,Vi,zi,Gi,ji)&&(t=[1,0,0,0,1,0,0,0,1],!!$i(t,Vi,zi,Gi,ji)&&(qi.crossVectors(ki,Hi),t=[qi.x,qi.y,qi.z],$i(t,Vi,zi,Gi,ji)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Fi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Fi).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Di[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Di[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Di[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Di[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Di[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Di[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Di[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Di[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Di)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Di=[new Pi,new Pi,new Pi,new Pi,new Pi,new Pi,new Pi,new Pi],Fi=new Pi,Bi=new Oi,Vi=new Pi,zi=new Pi,Gi=new Pi,ki=new Pi,Hi=new Pi,Wi=new Pi,Xi=new Pi,ji=new Pi,qi=new Pi,Yi=new Pi;function $i(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){Yi.fromArray(e,s);const a=r.x*Math.abs(Yi.x)+r.y*Math.abs(Yi.y)+r.z*Math.abs(Yi.z),o=t.dot(Yi),l=n.dot(Yi),c=i.dot(Yi);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Zi=new Oi,Ki=new Pi,Ji=new Pi;class Qi{constructor(e=new Pi,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):Zi.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Ki.subVectors(e,this.center);const t=Ki.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(Ki,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Ji.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ki.copy(e.center).add(Ji)),this.expandByPoint(Ki.copy(e.center).sub(Ji))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const er=new Pi,tr=new Pi,nr=new Pi,ir=new Pi,rr=new Pi,sr=new Pi,ar=new Pi;class or{constructor(e=new Pi,t=new Pi(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,er)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=er.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(er.copy(this.origin).addScaledVector(this.direction,t),er.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){tr.copy(e).add(t).multiplyScalar(.5),nr.copy(t).sub(e).normalize(),ir.copy(this.origin).sub(tr);const r=.5*e.distanceTo(t),s=-this.direction.dot(nr),a=ir.dot(this.direction),o=-ir.dot(nr),l=ir.lengthSq(),c=Math.abs(1-s*s);let u,h,d,p;if(c>0)if(u=s*o-a,h=s*a-o,p=r*c,u>=0)if(h>=-p)if(h<=p){const e=1/c;u*=e,h*=e,d=u*(u+s*h+2*a)+h*(s*u+h+2*o)+l}else h=r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;else h=-r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;else h<=-p?(u=Math.max(0,-(-s*r+a)),h=u>0?-r:Math.min(Math.max(-r,-o),r),d=-u*u+h*(h+2*o)+l):h<=p?(u=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(u=Math.max(0,-(s*r+a)),h=u>0?r:Math.min(Math.max(-r,-o),r),d=-u*u+h*(h+2*o)+l);else h=s>0?-r:r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(tr).addScaledVector(nr,h),d}intersectSphere(e,t){er.subVectors(e.center,this.origin);const n=er.dot(this.direction),i=er.dot(er)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),c>=0?(r=(e.min.y-h.y)*c,s=(e.max.y-h.y)*c):(r=(e.max.y-h.y)*c,s=(e.min.y-h.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(e.min.z-h.z)*u,o=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,o=(e.min.z-h.z)*u),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,er)}intersectTriangle(e,t,n,i,r){rr.subVectors(t,e),sr.subVectors(n,e),ar.crossVectors(rr,sr);let s,a=this.direction.dot(ar);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}ir.subVectors(this.origin,e);const o=s*this.direction.dot(sr.crossVectors(ir,sr));if(o<0)return null;const l=s*this.direction.dot(rr.cross(ir));if(l<0)return null;if(o+l>a)return null;const c=-s*ir.dot(ar);return c<0?null:this.at(c/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class lr{constructor(e,t,n,i,r,s,a,o,l,c,u,h,d,p,m,f){lr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l,c,u,h,d,p,m,f)}set(e,t,n,i,r,s,a,o,l,c,u,h,d,p,m,f){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=u,g[14]=h,g[3]=d,g[7]=p,g[11]=m,g[15]=f,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 lr).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,i=1/cr.setFromMatrixColumn(e,0).length(),r=1/cr.setFromMatrixColumn(e,1).length(),s=1/cr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=s*c,n=s*u,i=a*c,r=a*u;t[0]=o*c,t[4]=-o*u,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*c,n=o*u,i=l*c,r=l*u;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*u,t[5]=s*c,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*c,n=o*u,i=l*c,r=l*u;t[0]=e-r*a,t[4]=-s*u,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*c,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*c,n=s*u,i=a*c,r=a*u;t[0]=o*c,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*u,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*c,t[4]=r-e*u,t[8]=i*u+n,t[1]=u,t[5]=s*c,t[9]=-a*c,t[2]=-l*c,t[6]=n*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*c,t[4]=-u,t[8]=l*c,t[1]=e*u+r,t[5]=s*c,t[9]=n*u-i,t[2]=i*u-n,t[6]=a*c,t[10]=r*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(hr,e,dr)}lookAt(e,t,n){const i=this.elements;return fr.subVectors(e,t),0===fr.lengthSq()&&(fr.z=1),fr.normalize(),pr.crossVectors(n,fr),0===pr.lengthSq()&&(1===Math.abs(n.z)?fr.x+=1e-4:fr.z+=1e-4,fr.normalize(),pr.crossVectors(n,fr)),pr.normalize(),mr.crossVectors(fr,pr),i[0]=pr.x,i[4]=mr.x,i[8]=fr.x,i[1]=pr.y,i[5]=mr.y,i[9]=fr.y,i[2]=pr.z,i[6]=mr.z,i[10]=fr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],u=n[5],h=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],_=n[3],v=n[7],x=n[11],y=n[15],b=i[0],S=i[4],T=i[8],M=i[12],E=i[1],A=i[5],w=i[9],R=i[13],C=i[2],N=i[6],L=i[10],P=i[14],I=i[3],U=i[7],O=i[11],D=i[15];return r[0]=s*b+a*E+o*C+l*I,r[4]=s*S+a*A+o*N+l*U,r[8]=s*T+a*w+o*L+l*O,r[12]=s*M+a*R+o*P+l*D,r[1]=c*b+u*E+h*C+d*I,r[5]=c*S+u*A+h*N+d*U,r[9]=c*T+u*w+h*L+d*O,r[13]=c*M+u*R+h*P+d*D,r[2]=p*b+m*E+f*C+g*I,r[6]=p*S+m*A+f*N+g*U,r[10]=p*T+m*w+f*L+g*O,r[14]=p*M+m*R+f*P+g*D,r[3]=_*b+v*E+x*C+y*I,r[7]=_*S+v*A+x*N+y*U,r[11]=_*T+v*w+x*L+y*O,r[15]=_*M+v*R+x*P+y*D,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],c=e[2],u=e[6],h=e[10],d=e[14];return e[3]*(+r*o*u-i*l*u-r*a*h+n*l*h+i*a*d-n*o*d)+e[7]*(+t*o*d-t*l*h+r*s*h-i*s*d+i*l*c-r*o*c)+e[11]*(+t*l*u-t*a*d-r*s*u+n*s*d+r*a*c-n*l*c)+e[15]*(-i*a*c-t*o*u+t*a*h+i*s*u-n*s*h+n*o*c)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=e[9],h=e[10],d=e[11],p=e[12],m=e[13],f=e[14],g=e[15],_=u*f*l-m*h*l+m*o*d-a*f*d-u*o*g+a*h*g,v=p*h*l-c*f*l-p*o*d+s*f*d+c*o*g-s*h*g,x=c*m*l-p*u*l+p*a*d-s*m*d-c*a*g+s*u*g,y=p*u*o-c*m*o-p*a*h+s*m*h+c*a*f-s*u*f,b=t*_+n*v+i*x+r*y;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/b;return e[0]=_*S,e[1]=(m*h*r-u*f*r-m*i*d+n*f*d+u*i*g-n*h*g)*S,e[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,e[3]=(u*o*r-a*h*r-u*i*l+n*h*l+a*i*d-n*o*d)*S,e[4]=v*S,e[5]=(c*f*r-p*h*r+p*i*d-t*f*d-c*i*g+t*h*g)*S,e[6]=(p*o*r-s*f*r-p*i*l+t*f*l+s*i*g-t*o*g)*S,e[7]=(s*h*r-c*o*r+c*i*l-t*h*l-s*i*d+t*o*d)*S,e[8]=x*S,e[9]=(p*u*r-c*m*r-p*n*d+t*m*d+c*n*g-t*u*g)*S,e[10]=(s*m*r-p*a*r+p*n*l-t*m*l-s*n*g+t*a*g)*S,e[11]=(c*a*r-s*u*r-c*n*l+t*u*l+s*n*d-t*a*d)*S,e[12]=y*S,e[13]=(c*m*i-p*u*i+p*n*h-t*m*h-c*n*f+t*u*f)*S,e[14]=(p*a*i-s*m*i-p*n*o+t*m*o+s*n*f-t*a*f)*S,e[15]=(s*u*i-c*a*i+c*n*o-t*u*o-s*n*h+t*a*h)*S,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,c=s+s,u=a+a,h=r*l,d=r*c,p=r*u,m=s*c,f=s*u,g=a*u,_=o*l,v=o*c,x=o*u,y=n.x,b=n.y,S=n.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-v)*y,i[3]=0,i[4]=(d-x)*b,i[5]=(1-(h+g))*b,i[6]=(f+_)*b,i[7]=0,i[8]=(p+v)*S,i[9]=(f-_)*S,i[10]=(1-(h+m))*S,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=cr.set(i[0],i[1],i[2]).length();const s=cr.set(i[4],i[5],i[6]).length(),a=cr.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],ur.copy(this);const o=1/r,l=1/s,c=1/a;return ur.elements[0]*=o,ur.elements[1]*=o,ur.elements[2]*=o,ur.elements[4]*=l,ur.elements[5]*=l,ur.elements[6]*=l,ur.elements[8]*=c,ur.elements[9]*=c,ur.elements[10]*=c,t.setFromRotationMatrix(ur),n.x=r,n.y=s,n.z=a,this}makePerspective(e,t,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(t-e),c=2*r/(n-i),u=(t+e)/(t-e),h=(n+i)/(n-i);let d,p;if(a===Fn)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Bn)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=u,o[12]=0,o[1]=0,o[5]=c,o[9]=h,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(e,t,n,i,r,s,a=2e3){const o=this.elements,l=1/(t-e),c=1/(n-i),u=1/(s-r),h=(t+e)*l,d=(n+i)*c;let p,m;if(a===Fn)p=(s+r)*u,m=-2*u;else{if(a!==Bn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*u,m=-1*u}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-h,o[1]=0,o[5]=2*c,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(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const cr=new Pi,ur=new lr,hr=new Pi(0,0,0),dr=new Pi(1,1,1),pr=new Pi,mr=new Pi,fr=new Pi,gr=new lr,_r=new Li;class vr{constructor(e=0,t=0,n=0,i=vr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],u=i[2],h=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Xn(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Xn(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Xn(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Xn(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Xn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Xn(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return gr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(gr,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return _r.setFromEuler(this),this.setFromQuaternion(_r,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}vr.DEFAULT_ORDER="XYZ";class xr{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),u.length>0&&(n.nodes=u)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Ur.subVectors(i,t),Or.subVectors(n,t),Dr.subVectors(e,t);const s=Ur.dot(Ur),a=Ur.dot(Or),o=Ur.dot(Dr),l=Or.dot(Or),c=Or.dot(Dr),u=s*l-a*a;if(0===u)return r.set(0,0,0),null;const h=1/u,d=(l*o-a*c)*h,p=(s*c-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,Fr)&&(Fr.x>=0&&Fr.y>=0&&Fr.x+Fr.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,Fr)?(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,Fr.x),o.addScaledVector(s,Fr.y),o.addScaledVector(a,Fr.z),o)}static isFrontFacing(e,t,n,i){return Ur.subVectors(n,t),Or.subVectors(e,t),Ur.cross(Or).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ur.subVectors(this.c,this.b),Or.subVectors(this.a,this.b),.5*Ur.cross(Or).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return Wr.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;Br.subVectors(i,n),Vr.subVectors(r,n),Gr.subVectors(e,n);const o=Br.dot(Gr),l=Vr.dot(Gr);if(o<=0&&l<=0)return t.copy(n);kr.subVectors(e,i);const c=Br.dot(kr),u=Vr.dot(kr);if(c>=0&&u<=c)return t.copy(i);const h=o*u-c*l;if(h<=0&&o>=0&&c<=0)return s=o/(o-c),t.copy(n).addScaledVector(Br,s);Hr.subVectors(e,r);const d=Br.dot(Hr),p=Vr.dot(Hr);if(p>=0&&d<=p)return t.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(Vr,a);const f=c*p-d*u;if(f<=0&&u-c>=0&&d-p>=0)return zr.subVectors(r,i),a=(u-c)/(u-c+(d-p)),t.copy(i).addScaledVector(zr,a);const g=1/(f+m+h);return s=m*g,a=h*g,t.copy(n).addScaledVector(Br,s).addScaledVector(Vr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Xr={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},jr={h:0,s:0,l:0},qr={h:0,s:0,l:0};function Yr(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class $r{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=jt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,pi.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=pi.workingColorSpace){return this.r=e,this.g=t,this.b=n,pi.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=pi.workingColorSpace){if(e=jn(e,1),t=Xn(t,0,1),n=Xn(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=Yr(r,i,e+1/3),this.g=Yr(r,i,e),this.b=Yr(r,i,e-1/3)}return pi.toWorkingColorSpace(this,i),this}setStyle(e,t=jt){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=jt){const n=Xr[e.toLowerCase()];return void 0!==n?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=mi(e.r),this.g=mi(e.g),this.b=mi(e.b),this}copyLinearToSRGB(e){return this.r=fi(e.r),this.g=fi(e.g),this.b=fi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=jt){return pi.fromWorkingColorSpace(Zr.copy(this),e),65536*Math.round(Xn(255*Zr.r,0,255))+256*Math.round(Xn(255*Zr.g,0,255))+Math.round(Xn(255*Zr.b,0,255))}getHexString(e=jt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=pi.workingColorSpace){pi.fromWorkingColorSpace(Zr.copy(this),t);const n=Zr.r,i=Zr.g,r=Zr.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=c<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),this.side!==h&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==C&&(n.blendSrc=this.blendSrc),this.blendDst!==N&&(n.blendDst=this.blendDst),this.blendEquation!==y&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==gn&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==tn&&(n.stencilFail=this.stencilFail),this.stencilZFail!==tn&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==tn&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class Qr extends Jr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new $r(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.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const es=ts();function ts(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;0==(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function ns(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Xn(e,-65504,65504),es.floatView[0]=e;const t=es.uint32View[0],n=t>>23&511;return es.baseTable[n]+((8388607&t)>>es.shiftTable[n])}function is(e){const t=e>>10;return es.uint32View[0]=es.mantissaTable[es.offsetTable[t]+(1023&e)]+es.exponentTable[t],es.floatView[0]}const rs={toHalfFloat:ns,fromHalfFloat:is},ss=new Pi,as=new Qn;class os{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=En,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=Le,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return console.warn("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;i0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone(t));const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}As.copy(r).invert(),ws.copy(e.ray).applyMatrix4(As),null!==n.boundingBox&&!1===ws.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,ws)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,u=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;rn.far?null:{distance:c,point:ks.clone(),object:e}}(e,t,n,i,Ns,Ls,Ps,Gs);if(u){r&&(Os.fromBufferAttribute(r,o),Ds.fromBufferAttribute(r,l),Fs.fromBufferAttribute(r,c),u.uv=Wr.getInterpolation(Gs,Ns,Ls,Ps,Os,Ds,Fs,new Qn)),s&&(Os.fromBufferAttribute(s,o),Ds.fromBufferAttribute(s,l),Fs.fromBufferAttribute(s,c),u.uv1=Wr.getInterpolation(Gs,Ns,Ls,Ps,Os,Ds,Fs,new Qn),u.uv2=u.uv1),a&&(Bs.fromBufferAttribute(a,o),Vs.fromBufferAttribute(a,l),zs.fromBufferAttribute(a,c),u.normal=Wr.getInterpolation(Gs,Ns,Ls,Ps,Bs,Vs,zs,new Pi),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const e={a:o,b:l,c:c,normal:new Pi,materialIndex:0};Wr.getNormal(Ns,Ls,Ps,e.normal),u.face=e}return u}class Xs extends Es{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],u=[];let h=0,d=0;function p(e,t,n,i,r,s,p,m,f,g,_){const v=s/f,x=p/g,y=s/2,b=p/2,S=m/2,T=f+1,M=g+1;let E=0,A=0;const w=new Pi;for(let s=0;s0?1:-1,c.push(w.x,w.y,w.z),u.push(o/f),u.push(1-s/g),E+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Ks extends Ir{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new lr,this.projectionMatrix=new lr,this.projectionMatrixInverse=new lr,this.coordinateSystem=Fn}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}class Js extends Ks{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*Hn*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*kn*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Hn*Math.atan(Math.tan(.5*kn*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,t,n,i,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*kn*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Qs=-90;class ea extends Ir{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Js(Qs,1,e,t);i.layers=this.layers,this.add(i);const r=new Js(Qs,1,e,t);r.layers=this.layers,this.add(r);const s=new Js(Qs,1,e,t);s.layers=this.layers,this.add(s);const a=new Js(Qs,1,e,t);a.layers=this.layers,this.add(a);const o=new Js(Qs,1,e,t);o.layers=this.layers,this.add(o);const l=new Js(Qs,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===Fn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==Bn)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,s),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,o),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,i),e.render(t,c),e.setRenderTarget(u,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class ta extends Si{constructor(e,t,n,i,r,s,a,o,l,c){super(e=void 0!==e?e:[],t=void 0!==t?t:oe,n,i,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class na extends Ei{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];void 0!==t.encoding&&(li("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),t.colorSpace=t.encoding===zt?jt:Xt),this.texture=new ta(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:ye}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Xs(5,5,5),r=new Zs({name:"CubemapFromEquirect",uniforms:js(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:d,blending:0});r.uniforms.tEquirect.value=t;const s=new Hs(i,r),a=t.minFilter;t.minFilter===Te&&(t.minFilter=ye);return new ea(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,n,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}const ia=new Pi,ra=new Pi,sa=new ei;class aa{constructor(e=new Pi(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=ia.subVectors(n,t).cross(ra.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(ia),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||sa.getNormalMatrix(e),i=this.coplanarPoint(ia).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const oa=new Qi,la=new Pi;class ca{constructor(e=new aa,t=new aa,n=new aa,i=new aa,r=new aa,s=new aa){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3){const n=this.planes,i=e.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],u=i[6],h=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],_=i[13],v=i[14],x=i[15];if(n[0].setComponents(o-r,h-l,f-d,x-g).normalize(),n[1].setComponents(o+r,h+l,f+d,x+g).normalize(),n[2].setComponents(o+s,h+c,f+p,x+_).normalize(),n[3].setComponents(o-s,h-c,f-p,x-_).normalize(),n[4].setComponents(o-a,h-u,f-m,x-v).normalize(),t===Fn)n[5].setComponents(o+a,h+u,f+m,x+v).normalize();else{if(t!==Bn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(a,u,m,v).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),oa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),oa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(oa)}intersectsSprite(e){return oa.center.set(0,0,0),oa.radius=.7071067811865476,oa.applyMatrix4(e.matrixWorld),this.intersectsSphere(oa)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,la.y=i.normal.y>0?e.max.y:e.min.y,la.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(la)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function ua(){let e=null,t=!1,n=null,i=null;function r(t,s){n(t,s),i=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==n&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function ha(e,t){const n=t.isWebGL2,i=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),i.get(e)},remove:function(t){t.isInterleavedBufferAttribute&&(t=t.data);const n=i.get(t);n&&(e.deleteBuffer(n.buffer),i.delete(t))},update:function(t,r){if(t.isGLBufferAttribute){const e=i.get(t);return void((!e||e.version 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\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 )\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 )\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",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}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\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\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:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\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}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\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, 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\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, 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, 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_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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_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\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.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.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.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 ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\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",morphcolor_vertex:"#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\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\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\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.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( 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( 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 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 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 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 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 shadow;\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 shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\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 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 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 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.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.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.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 OptimizedCineonToneMapping( 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 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.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 ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\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;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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#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#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\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\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}",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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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#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\t#include \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\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\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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\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\t#include \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\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#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\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\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\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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\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_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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\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\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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}",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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}"},ma={common:{diffuse:{value:new $r(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ei},alphaMap:{value:null},alphaMapTransform:{value:new ei},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ei}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ei}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ei}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ei},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ei},normalScale:{value:new Qn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ei},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ei}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ei}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ei}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new $r(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{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 $r(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ei},alphaTest:{value:0},uvTransform:{value:new ei}},sprite:{diffuse:{value:new $r(16777215)},opacity:{value:1},center:{value:new Qn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ei},alphaMap:{value:null},alphaMapTransform:{value:new ei},alphaTest:{value:0}}},fa={basic:{uniforms:qs([ma.common,ma.specularmap,ma.envmap,ma.aomap,ma.lightmap,ma.fog]),vertexShader:pa.meshbasic_vert,fragmentShader:pa.meshbasic_frag},lambert:{uniforms:qs([ma.common,ma.specularmap,ma.envmap,ma.aomap,ma.lightmap,ma.emissivemap,ma.bumpmap,ma.normalmap,ma.displacementmap,ma.fog,ma.lights,{emissive:{value:new $r(0)}}]),vertexShader:pa.meshlambert_vert,fragmentShader:pa.meshlambert_frag},phong:{uniforms:qs([ma.common,ma.specularmap,ma.envmap,ma.aomap,ma.lightmap,ma.emissivemap,ma.bumpmap,ma.normalmap,ma.displacementmap,ma.fog,ma.lights,{emissive:{value:new $r(0)},specular:{value:new $r(1118481)},shininess:{value:30}}]),vertexShader:pa.meshphong_vert,fragmentShader:pa.meshphong_frag},standard:{uniforms:qs([ma.common,ma.envmap,ma.aomap,ma.lightmap,ma.emissivemap,ma.bumpmap,ma.normalmap,ma.displacementmap,ma.roughnessmap,ma.metalnessmap,ma.fog,ma.lights,{emissive:{value:new $r(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:pa.meshphysical_vert,fragmentShader:pa.meshphysical_frag},toon:{uniforms:qs([ma.common,ma.aomap,ma.lightmap,ma.emissivemap,ma.bumpmap,ma.normalmap,ma.displacementmap,ma.gradientmap,ma.fog,ma.lights,{emissive:{value:new $r(0)}}]),vertexShader:pa.meshtoon_vert,fragmentShader:pa.meshtoon_frag},matcap:{uniforms:qs([ma.common,ma.bumpmap,ma.normalmap,ma.displacementmap,ma.fog,{matcap:{value:null}}]),vertexShader:pa.meshmatcap_vert,fragmentShader:pa.meshmatcap_frag},points:{uniforms:qs([ma.points,ma.fog]),vertexShader:pa.points_vert,fragmentShader:pa.points_frag},dashed:{uniforms:qs([ma.common,ma.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:pa.linedashed_vert,fragmentShader:pa.linedashed_frag},depth:{uniforms:qs([ma.common,ma.displacementmap]),vertexShader:pa.depth_vert,fragmentShader:pa.depth_frag},normal:{uniforms:qs([ma.common,ma.bumpmap,ma.normalmap,ma.displacementmap,{opacity:{value:1}}]),vertexShader:pa.meshnormal_vert,fragmentShader:pa.meshnormal_frag},sprite:{uniforms:qs([ma.sprite,ma.fog]),vertexShader:pa.sprite_vert,fragmentShader:pa.sprite_frag},background:{uniforms:{uvTransform:{value:new ei},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:pa.background_vert,fragmentShader:pa.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:pa.backgroundCube_vert,fragmentShader:pa.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:pa.cube_vert,fragmentShader:pa.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:pa.equirect_vert,fragmentShader:pa.equirect_frag},distanceRGBA:{uniforms:qs([ma.common,ma.displacementmap,{referencePosition:{value:new Pi},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:pa.distanceRGBA_vert,fragmentShader:pa.distanceRGBA_frag},shadow:{uniforms:qs([ma.lights,ma.fog,{color:{value:new $r(0)},opacity:{value:1}}]),vertexShader:pa.shadow_vert,fragmentShader:pa.shadow_frag}};fa.physical={uniforms:qs([fa.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ei},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ei},clearcoatNormalScale:{value:new Qn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ei},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ei},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ei},sheen:{value:0},sheenColor:{value:new $r(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ei},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ei},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ei},transmissionSamplerSize:{value:new Qn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ei},attenuationDistance:{value:0},attenuationColor:{value:new $r(0)},specularColor:{value:new $r(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ei},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ei},anisotropyVector:{value:new Qn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ei}}]),vertexShader:pa.meshphysical_vert,fragmentShader:pa.meshphysical_frag};const ga={r:0,b:0,g:0};function _a(e,t,n,i,r,s,a){const o=new $r(0);let l,c,u=!0===s?0:1,p=null,m=0,f=null;function g(t,n){t.getRGB(ga,Ys(e)),i.buffers.color.setClear(ga.r,ga.g,ga.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),u=t,g(o,u)},getClearAlpha:function(){return u},setClearAlpha:function(e){u=e,g(o,u)},render:function(s,_){let v=!1,x=!0===_.isScene?_.background:null;if(x&&x.isTexture){x=(_.backgroundBlurriness>0?n:t).get(x)}null===x?g(o,u):x&&x.isColor&&(g(x,1),v=!0);const y=e.xr.getEnvironmentBlendMode();"additive"===y?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===y&&i.buffers.color.setClear(0,0,0,0,a),(e.autoClear||v)&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),x&&(x.isCubeTexture||x.mapping===he)?(void 0===c&&(c=new Hs(new Xs(1,1,1),new Zs({name:"BackgroundCubeMaterial",uniforms:js(fa.backgroundCube.uniforms),vertexShader:fa.backgroundCube.vertexShader,fragmentShader:fa.backgroundCube.fragmentShader,side:d,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),c.material.uniforms.envMap.value=x,c.material.uniforms.flipEnvMap.value=x.isCubeTexture&&!1===x.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,c.material.toneMapped=pi.getTransfer(x.colorSpace)!==Kt,p===x&&m===x.version&&f===e.toneMapping||(c.material.needsUpdate=!0,p=x,m=x.version,f=e.toneMapping),c.layers.enableAll(),s.unshift(c,c.geometry,c.material,0,0,null)):x&&x.isTexture&&(void 0===l&&(l=new Hs(new da(2,2),new Zs({name:"BackgroundMaterial",uniforms:js(fa.background.uniforms),vertexShader:fa.background.vertexShader,fragmentShader:fa.background.fragmentShader,side:h,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=x,l.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,l.material.toneMapped=pi.getTransfer(x.colorSpace)!==Kt,!0===x.matrixAutoUpdate&&x.updateMatrix(),l.material.uniforms.uvTransform.value.copy(x.matrix),p===x&&m===x.version&&f===e.toneMapping||(l.material.needsUpdate=!0,p=x,m=x.version,f=e.toneMapping),l.layers.enableAll(),s.unshift(l,l.geometry,l.material,0,0,null))}}}function va(e,t,n,i){const r=e.getParameter(e.MAX_VERTEX_ATTRIBS),s=i.isWebGL2?null:t.get("OES_vertex_array_object"),a=i.isWebGL2||null!==s,o={},l=p(null);let c=l,u=!1;function h(t){return i.isWebGL2?e.bindVertexArray(t):s.bindVertexArrayOES(t)}function d(t){return i.isWebGL2?e.deleteVertexArray(t):s.deleteVertexArrayOES(t)}function p(e){const t=[],n=[],i=[];for(let e=0;e=0){const n=r[t];let i=s[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;a++}}return c.attributesNum!==a||c.index!==i}(r,x,d,y),b&&function(e,t,n,i){const r={},s=t.attributes;let a=0;const o=n.getAttributes();for(const t in o){if(o[t].location>=0){let n=s[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,a++}}c.attributes=r,c.attributesNum=a,c.index=i}(r,x,d,y)}else{const e=!0===l.wireframe;c.geometry===x.id&&c.program===d.id&&c.wireframe===e||(c.geometry=x.id,c.program=d.id,c.wireframe=e,b=!0)}null!==y&&n.update(y,e.ELEMENT_ARRAY_BUFFER),(b||u)&&(u=!1,function(r,s,a,o){if(!1===i.isWebGL2&&(r.isInstancedMesh||o.isInstancedBufferGeometry)&&null===t.get("ANGLE_instanced_arrays"))return;m();const l=o.attributes,c=a.getAttributes(),u=s.defaultAttributeValues;for(const t in c){const s=c[t];if(s.location>=0){let a=l[t];if(void 0===a&&("instanceMatrix"===t&&r.instanceMatrix&&(a=r.instanceMatrix),"instanceColor"===t&&r.instanceColor&&(a=r.instanceColor)),void 0!==a){const t=a.normalized,l=a.itemSize,c=n.get(a);if(void 0===c)continue;const u=c.buffer,h=c.type,d=c.bytesPerElement,p=!0===i.isWebGL2&&(h===e.INT||h===e.UNSIGNED_INT||a.gpuType===Ce);if(a.isInterleavedBufferAttribute){const n=a.data,i=n.stride,c=a.offset;if(n.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"}const s="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=s||t.has("WEBGL_draw_buffers"),c=!0===n.logarithmicDepthBuffer,u=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),f=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),g=e.getParameter(e.MAX_VARYING_VECTORS),_=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),v=h>0,x=s||t.has("OES_texture_float");return{isWebGL2:s,drawBuffers:l,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:r,precision:a,logarithmicDepthBuffer:c,maxTextures:u,maxVertexTextures:h,maxTextureSize:d,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:f,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:v,floatFragmentTextures:x,floatVertexTextures:v&&x,maxSamples:s?e.getParameter(e.MAX_SAMPLES):0}}function ba(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new aa,o=new ei,l={value:null,needsUpdate:!1};function c(e,n,i,r){const s=null!==e?e.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=m.clippingState||null;l.value=r,r=c(h,o,t,u);for(let e=0;e!==t;++e)r[e]=n[e];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function Sa(e){let t=new WeakMap;function n(e,t){return t===ce?e.mapping=oe:t===ue&&(e.mapping=le),e}function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===ce||s===ue){if(t.has(r)){return n(t.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new na(s.height/2);return a.fromEquirectangularTexture(e,r),t.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){t=new WeakMap}}}class Ta extends Ks{constructor(e=-1,t=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-e,s=n+e,a=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,s=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}const Ma=[.125,.215,.35,.446,.526,.582],Ea=20,Aa=new Ta,wa=new $r;let Ra=null,Ca=0,Na=0;const La=(1+Math.sqrt(5))/2,Pa=1/La,Ia=[new Pi(1,1,1),new Pi(-1,1,1),new Pi(1,1,-1),new Pi(-1,1,-1),new Pi(0,La,Pa),new Pi(0,La,-Pa),new Pi(Pa,0,La),new Pi(-Pa,0,La),new Pi(La,Pa,0),new Pi(-La,Pa,0)];class Ua{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,i=100){Ra=this._renderer.getRenderTarget(),Ca=this._renderer.getActiveCubeFace(),Na=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,n,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Ba(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Fa(),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?o=Ma[a-e+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),c=-l,u=1+l,h=[c,c,u,c,u,u,c,c,u,u,c,u],d=6,p=6,m=3,f=2,g=1,_=new Float32Array(m*p*d),v=new Float32Array(f*p*d),x=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(i,m*p*e),v.set(h,f*p*e);const r=[e,e,e,e,e,e];x.set(r,g*p*e)}const y=new Es;y.setAttribute("position",new os(_,m)),y.setAttribute("uv",new os(v,f)),y.setAttribute("faceIndex",new os(x,g)),t.push(y),r>4&&r--}return{lodPlanes:t,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(Ea),r=new Pi(0,1,0),s=new Zs({name:"SphericalGaussianBlur",defines:{n:Ea,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Va(),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:0,depthTest:!1,depthWrite:!1});return s}(i,e,t)}return i}_compileMaterial(e){const t=new Hs(this._lodPlanes[0],e);this._renderer.compile(t,Aa)}_sceneToCubeUV(e,t,n,i){const r=new Js(90,1,t,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(wa),o.toneMapping=K,o.autoClear=!1;const u=new Qr({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1}),h=new Hs(new Xs,u);let p=!1;const m=e.background;m?m.isColor&&(u.color.copy(m),e.background=null,p=!0):(u.color.copy(wa),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(r.up.set(0,s[t],0),r.lookAt(a[t],0,0)):1===n?(r.up.set(0,0,s[t]),r.lookAt(0,a[t],0)):(r.up.set(0,s[t],0),r.lookAt(0,0,a[t]));const l=this._cubeSize;Da(i,n*l,t>2?l:0,l,l),o.setRenderTarget(i),p&&o.render(h,r),o.render(e,r)}h.geometry.dispose(),h.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=m}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===oe||e.mapping===le;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=Ba()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Fa());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new Hs(this._lodPlanes[0],r);r.uniforms.envMap.value=e;const a=this._cubeSize;Da(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Aa)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;for(let t=1;tEa&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(c,Aa)}}function Oa(e,t,n){const i=new Ei(e,t,n);return i.texture.mapping=he,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Da(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function Fa(){return new Zs({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Va(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Ba(){return new Zs({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Va(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Va(){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 za(e){let t=new WeakMap,n=null;function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===ce||s===ue,o=s===oe||s===le;if(a||o){if(r.isRenderTargetTexture&&!0===r.needsPMREMUpdate){r.needsPMREMUpdate=!1;let i=t.get(r);return null===n&&(n=new Ua(e)),i=a?n.fromEquirectangular(r,i):n.fromCubemap(r,i),t.set(r,i),i.texture}if(t.has(r))return t.get(r).texture;{const s=r.image;if(a&&s&&s.height>0||o&&s&&function(e){let t=0;const n=6;for(let i=0;it.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);const f=new Float32Array(p*m*4*r),g=new Ai(f,p,m,r);g.type=Le,g.needsUpdate=!0;const _=4*d;for(let t=0;t0)return e;const r=t*n;let s=to[r];if(void 0===s&&(s=new Float32Array(r),to[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function oo(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function al(e,t){const n=function(e){const t=pi.getPrimaries(pi.workingColorSpace),n=pi.getPrimaries(e);let i;switch(t===n?i="":t===Qt&&n===Jt?i="LinearDisplayP3ToLinearSRGB":t===Jt&&n===Qt&&(i="LinearSRGBToLinearDisplayP3"),e){case qt:case $t:return[i,"LinearTransferOETF"];case jt:case Yt:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",e),[i,"LinearTransferOETF"]}}(t);return`vec4 ${e}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function ol(e,t){let n;switch(t){case J:n="Linear";break;case Q:n="Reinhard";break;case ee:n="OptimizedCineon";break;case te:n="ACESFilmic";break;case ie:n="AgX";break;case ne:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function ll(e){return""!==e}function cl(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 ul(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const hl=/^[ \t]*#include +<([\w\d./]+)>/gm;function dl(e){return e.replace(hl,ml)}const pl=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function ml(e,t){let n=pa[t];if(void 0===n){const e=pl.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=pa[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return dl(n)}const fl=/#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 gl(e){return e.replace(fl,_l)}function _l(e,t,n,i){let r="";for(let e=parseInt(t);e0&&(y+="\n"),b=[g,"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v].filter(ll).join("\n"),b.length>0&&(b+="\n")):(y=[vl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",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 "+p:"",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&&n.isWebGL2?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+h:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.useLegacyLights?"#define LEGACY_LIGHTS":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","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","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","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(ll).join("\n"),b=[g,vl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.envMap?"#define "+p:"",n.envMap?"#define "+m:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.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.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas?"#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 "+h:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.useLegacyLights?"#define LEGACY_LIGHTS":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==K?"#define TONE_MAPPING":"",n.toneMapping!==K?pa.tonemapping_pars_fragment:"",n.toneMapping!==K?ol("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",pa.colorspace_pars_fragment,al("linearToOutputTexel",n.outputColorSpace),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ll).join("\n")),a=dl(a),a=cl(a,n),a=ul(a,n),o=dl(o),o=cl(o,n),o=ul(o,n),a=gl(a),o=gl(o),n.isWebGL2&&!0!==n.isRawShaderMaterial&&(S="#version 300 es\n",y=[_,"precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+y,b=["precision mediump sampler2DArray;","#define varying in",n.glslVersion===On?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===On?"":"#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"+b);const T=S+y+a,M=S+b+o,E=nl(r,r.VERTEX_SHADER,T),A=nl(r,r.FRAGMENT_SHADER,M);function w(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(x).trim(),i=r.getShaderInfoLog(E).trim(),s=r.getShaderInfoLog(A).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(x,r.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,x,E,A);else{const e=sl(r,E,"vertex"),t=sl(r,A,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(x,r.VALIDATE_STATUS)+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+t)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(t.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:y},fragmentShader:{log:s,prefix:b}})}r.deleteShader(E),r.deleteShader(A),R=new tl(r,x),C=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r0,q=s.clearcoat>0,Y=s.iridescence>0,$=s.sheen>0,Z=s.transmission>0,J=j&&!!s.anisotropyMap,Q=q&&!!s.clearcoatMap,ee=q&&!!s.clearcoatNormalMap,te=q&&!!s.clearcoatRoughnessMap,ne=Y&&!!s.iridescenceMap,ie=Y&&!!s.iridescenceThicknessMap,re=$&&!!s.sheenColorMap,se=$&&!!s.sheenRoughnessMap,ae=!!s.specularMap,oe=!!s.specularColorMap,le=!!s.specularIntensityMap,ce=Z&&!!s.transmissionMap,ue=Z&&!!s.thicknessMap,de=!!s.gradientMap,pe=!!s.alphaMap,me=s.alphaTest>0,fe=!!s.alphaHash,ge=!!s.extensions,_e=!!y.attributes.uv1,ve=!!y.attributes.uv2,xe=!!y.attributes.uv3;let ye=K;return s.toneMapped&&(null!==P&&!0!==P.isXRRenderTarget||(ye=e.toneMapping)),{isWebGL2:u,shaderID:M,shaderType:s.type,shaderName:s.name,vertexShader:w,fragmentShader:R,defines:s.defines,customVertexShaderID:C,customFragmentShaderID:N,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:m,batching:U,instancing:I,instancingColor:I&&null!==v.instanceColor,supportsVertexTextures:p,outputColorSpace:null===P?e.outputColorSpace:!0===P.isXRRenderTarget?P.texture.colorSpace:qt,map:O,matcap:D,envMap:F,envMapMode:F&&S.mapping,envMapCubeUVHeight:T,aoMap:B,lightMap:V,bumpMap:z,normalMap:G,displacementMap:p&&k,emissiveMap:H,normalMapObjectSpace:G&&1===s.normalMapType,normalMapTangentSpace:G&&0===s.normalMapType,metalnessMap:W,roughnessMap:X,anisotropy:j,anisotropyMap:J,clearcoat:q,clearcoatMap:Q,clearcoatNormalMap:ee,clearcoatRoughnessMap:te,iridescence:Y,iridescenceMap:ne,iridescenceThicknessMap:ie,sheen:$,sheenColorMap:re,sheenRoughnessMap:se,specularMap:ae,specularColorMap:oe,specularIntensityMap:le,transmission:Z,transmissionMap:ce,thicknessMap:ue,gradientMap:de,opaque:!1===s.transparent&&1===s.blending,alphaMap:pe,alphaTest:me,alphaHash:fe,combine:s.combine,mapUv:O&&g(s.map.channel),aoMapUv:B&&g(s.aoMap.channel),lightMapUv:V&&g(s.lightMap.channel),bumpMapUv:z&&g(s.bumpMap.channel),normalMapUv:G&&g(s.normalMap.channel),displacementMapUv:k&&g(s.displacementMap.channel),emissiveMapUv:H&&g(s.emissiveMap.channel),metalnessMapUv:W&&g(s.metalnessMap.channel),roughnessMapUv:X&&g(s.roughnessMap.channel),anisotropyMapUv:J&&g(s.anisotropyMap.channel),clearcoatMapUv:Q&&g(s.clearcoatMap.channel),clearcoatNormalMapUv:ee&&g(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:te&&g(s.clearcoatRoughnessMap.channel),iridescenceMapUv:ne&&g(s.iridescenceMap.channel),iridescenceThicknessMapUv:ie&&g(s.iridescenceThicknessMap.channel),sheenColorMapUv:re&&g(s.sheenColorMap.channel),sheenRoughnessMapUv:se&&g(s.sheenRoughnessMap.channel),specularMapUv:ae&&g(s.specularMap.channel),specularColorMapUv:oe&&g(s.specularColorMap.channel),specularIntensityMapUv:le&&g(s.specularIntensityMap.channel),transmissionMapUv:ce&&g(s.transmissionMap.channel),thicknessMapUv:ue&&g(s.thicknessMap.channel),alphaMapUv:pe&&g(s.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(G||j),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!y.attributes.color&&4===y.attributes.color.itemSize,vertexUv1s:_e,vertexUv2s:ve,vertexUv3s:xe,pointsUvs:!0===v.isPoints&&!!y.attributes.uv&&(O||pe),fog:!!x,useFog:!0===s.fog,fogExp2:!!x&&x.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:h,skinning:!0===v.isSkinnedMesh,morphTargets:void 0!==y.morphAttributes.position,morphNormals:void 0!==y.morphAttributes.normal,morphColors:void 0!==y.morphAttributes.color,morphTargetsCount:A,morphTextureStride:L,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&c.length>0,shadowMapType:e.shadowMap.type,toneMapping:ye,useLegacyLights:e._useLegacyLights,decodeVideoTexture:O&&!0===s.map.isVideoTexture&&pi.getTransfer(s.map.colorSpace)===Kt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:s.side===d,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionDerivatives:ge&&!0===s.extensions.derivatives,extensionFragDepth:ge&&!0===s.extensions.fragDepth,extensionDrawBuffers:ge&&!0===s.extensions.drawBuffers,extensionShaderTextureLOD:ge&&!0===s.extensions.shaderTextureLOD,extensionClipCullDistance:ge&&s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),rendererExtensionFragDepth:u||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:u||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:u||i.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()}},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){o.disableAll(),t.isWebGL2&&o.enable(0);t.supportsVertexTextures&&o.enable(1);t.instancing&&o.enable(2);t.instancingColor&&o.enable(3);t.matcap&&o.enable(4);t.envMap&&o.enable(5);t.normalMapObjectSpace&&o.enable(6);t.normalMapTangentSpace&&o.enable(7);t.clearcoat&&o.enable(8);t.iridescence&&o.enable(9);t.alphaTest&&o.enable(10);t.vertexColors&&o.enable(11);t.vertexAlphas&&o.enable(12);t.vertexUv1s&&o.enable(13);t.vertexUv2s&&o.enable(14);t.vertexUv3s&&o.enable(15);t.vertexTangents&&o.enable(16);t.anisotropy&&o.enable(17);t.alphaHash&&o.enable(18);t.batching&&o.enable(19);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.skinning&&o.enable(4);t.morphTargets&&o.enable(5);t.morphNormals&&o.enable(6);t.morphColors&&o.enable(7);t.premultipliedAlpha&&o.enable(8);t.shadowMapEnabled&&o.enable(9);t.useLegacyLights&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.transmission&&o.enable(15);t.sheen&&o.enable(16);t.opaque&&o.enable(17);t.pointsUvs&&o.enable(18);t.decodeVideoTexture&&o.enable(19);e.push(o.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=f[e.type];let n;if(t){const e=fa[t];n=$s.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i;for(let e=0,t=c.length;e0?i.push(u):!0===a.transparent?r.push(u):n.push(u)},unshift:function(e,t,a,o,l,c){const u=s(e,t,a,o,l,c);a.transmission>0?i.unshift(u):!0===a.transparent?r.unshift(u):n.unshift(u)},finish:function(){for(let n=t,i=e.length;n1&&n.sort(e||El),i.length>1&&i.sort(t||Al),r.length>1&&r.sort(t||Al)}}}function Rl(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new wl,e.set(t,[r])):n>=i.length?(r=new wl,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function Cl(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new Pi,color:new $r};break;case"SpotLight":n={position:new Pi,direction:new Pi,color:new $r,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Pi,color:new $r,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Pi,skyColor:new $r,groundColor:new $r};break;case"RectAreaLight":n={color:new $r,position:new Pi,halfWidth:new Pi,halfHeight:new Pi}}return e[t.id]=n,n}}}let Nl=0;function Ll(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Pl(e,t){const n=new Cl,i=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Qn};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Qn,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),r={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++)r.probe.push(new Pi);const s=new Pi,a=new lr,o=new lr;return{setup:function(s,a){let o=0,l=0,c=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let u=0,h=0,d=0,p=0,m=0,f=0,g=0,_=0,v=0,x=0,y=0;s.sort(Ll);const b=!0===a?Math.PI:1;for(let e=0,t=s.length;e0&&(t.isWebGL2?!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=ma.LTC_FLOAT_1,r.rectAreaLTC2=ma.LTC_FLOAT_2):(r.rectAreaLTC1=ma.LTC_HALF_1,r.rectAreaLTC2=ma.LTC_HALF_2):!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=ma.LTC_FLOAT_1,r.rectAreaLTC2=ma.LTC_FLOAT_2):!0===e.has("OES_texture_half_float_linear")?(r.rectAreaLTC1=ma.LTC_HALF_1,r.rectAreaLTC2=ma.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),r.ambient[0]=o,r.ambient[1]=l,r.ambient[2]=c;const S=r.hash;S.directionalLength===u&&S.pointLength===h&&S.spotLength===d&&S.rectAreaLength===p&&S.hemiLength===m&&S.numDirectionalShadows===f&&S.numPointShadows===g&&S.numSpotShadows===_&&S.numSpotMaps===v&&S.numLightProbes===y||(r.directional.length=u,r.spot.length=d,r.rectArea.length=p,r.point.length=h,r.hemi.length=m,r.directionalShadow.length=f,r.directionalShadowMap.length=f,r.pointShadow.length=g,r.pointShadowMap.length=g,r.spotShadow.length=_,r.spotShadowMap.length=_,r.directionalShadowMatrix.length=f,r.pointShadowMatrix.length=g,r.spotLightMatrix.length=_+v-x,r.spotLightMap.length=v,r.numSpotLightShadowsWithMaps=x,r.numLightProbes=y,S.directionalLength=u,S.pointLength=h,S.spotLength=d,S.rectAreaLength=p,S.hemiLength=m,S.numDirectionalShadows=f,S.numPointShadows=g,S.numSpotShadows=_,S.numSpotMaps=v,S.numLightProbes=y,r.version=Nl++)},setupView:function(e,t){let n=0,i=0,l=0,c=0,u=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t=s.length?(a=new Il(e,t),s.push(a)):a=s[r],a},dispose:function(){n=new WeakMap}}}class Ol extends Jr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Dl extends Jr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}function Fl(e,t,n){let i=new ca;const r=new Qn,s=new Qn,a=new Ti,o=new Ol({depthPacking:3201}),c=new Dl,p={},m=n.maxTextureSize,f={[h]:d,[d]:h,2:2},g=new Zs({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Qn},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}"}),_=g.clone();_.defines.HORIZONTAL_PASS=1;const v=new Es;v.setAttribute("position",new os(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new Hs(v,g),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=l;let b=this.type;function S(n,i){const s=t.update(x);g.defines.VSM_SAMPLES!==n.blurSamples&&(g.defines.VSM_SAMPLES=n.blurSamples,_.defines.VSM_SAMPLES=n.blurSamples,g.needsUpdate=!0,_.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Ei(r.x,r.y)),g.uniforms.shadow_pass.value=n.map.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,g,x,null),_.uniforms.shadow_pass.value=n.mapPass.texture,_.uniforms.resolution.value=n.mapSize,_.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,_,x,null)}function T(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?c:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const e=s.uuid,t=n.uuid;let i=p[e];void 0===i&&(i={},p[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",E)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=r===u?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:f[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function M(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&o===u)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let c=0,u=t.length;cm||r.y>m)&&(r.x>m&&(s.x=Math.floor(m/g.x),r.x=s.x*g.x,h.mapSize.x=s.x),r.y>m&&(s.y=Math.floor(m/g.y),r.y=s.y*g.y,h.mapSize.y=s.y)),null===h.map||!0===p||!0===f){const e=this.type!==u?{minFilter:fe,magFilter:fe}:{};null!==h.map&&h.map.dispose(),h.map=new Ei(r.x,r.y,e),h.map.texture.name=c.name+".shadowMap",h.camera.updateProjectionMatrix()}e.setRenderTarget(h.map),e.clear();const _=h.getViewportCount();for(let e=0;e<_;e++){const t=h.getViewport(e);a.set(s.x*t.x,s.y*t.y,s.x*t.z,s.y*t.w),d.viewport(a),h.updateMatrices(c,e),i=h.getFrustum(),M(n,o,h.camera,c,this.type)}!0!==h.isPointLightShadow&&this.type===u&&S(h,o),h.needsUpdate=!1}b=this.type,y.needsUpdate=!1,e.setRenderTarget(l,c,h)}}function Bl(e,t,n){const i=n.isWebGL2;const r=new function(){let t=!1;const n=new Ti;let i=null;const r=new Ti(0,0,0,0);return{setMask:function(n){i===n||t||(e.colorMask(n,n,n,n),i=n)},setLocked:function(e){t=e},setClear:function(t,i,s,a,o){!0===o&&(t*=a,i*=a,s*=a),n.set(t,i,s,a),!1===r.equals(n)&&(e.clearColor(t,i,s,a),r.copy(n))},reset:function(){t=!1,i=null,r.set(-1,0,0,0)}}},s=new function(){let t=!1,n=null,i=null,r=null;return{setTest:function(t){t?ie(e.DEPTH_TEST):re(e.DEPTH_TEST)},setMask:function(i){n===i||t||(e.depthMask(i),n=i)},setFunc:function(t){if(i!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:default:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL)}i=t}},setLocked:function(e){t=e},setClear:function(t){r!==t&&(e.clearDepth(t),r=t)},reset:function(){t=!1,n=null,i=null,r=null}}},a=new function(){let t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(n){t||(n?ie(e.STENCIL_TEST):re(e.STENCIL_TEST))},setMask:function(i){n===i||t||(e.stencilMask(i),n=i)},setFunc:function(t,n,a){i===t&&r===n&&s===a||(e.stencilFunc(t,n,a),i=t,r=n,s=a)},setOp:function(t,n,i){a===t&&o===n&&l===i||(e.stencilOp(t,n,i),a=t,o=n,l=i)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null}}},o=new WeakMap,l=new WeakMap;let c={},u={},h=new WeakMap,p=[],m=null,f=!1,g=null,_=null,v=null,x=null,T=null,M=null,D=null,F=new $r(0,0,0),B=0,V=!1,z=null,G=null,k=null,H=null,W=null;const X=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let j=!1,q=0;const Y=e.getParameter(e.VERSION);-1!==Y.indexOf("WebGL")?(q=parseFloat(/^WebGL (\d)/.exec(Y)[1]),j=q>=1):-1!==Y.indexOf("OpenGL ES")&&(q=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),j=q>=2);let $=null,Z={};const K=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),Q=(new Ti).fromArray(K),ee=(new Ti).fromArray(J);function te(t,n,r,s){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;oi||e.height>i)&&(r=i/Math.max(e.width,e.height)),r<1||!0===t){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const i=t?$n:Math.floor,s=i(r*e.width),a=i(r*e.height);void 0===h&&(h=m(s,a));const o=n?m(s,a):h;o.width=s,o.height=a;return o.getContext("2d").drawImage(e,0,0,s,a),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+e.width+"x"+e.height+") to ("+s+"x"+a+")."),o}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+e.width+"x"+e.height+")."),e}return e}function g(e){return Yn(e.width)&&Yn(e.height)}function _(e,t){return e.generateMipmaps&&t&&e.minFilter!==fe&&e.minFilter!==ye}function v(t){e.generateMipmap(t)}function x(n,i,r,s,a=!1){if(!1===o)return i;if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let l=i;if(i===e.RED&&(r===e.FLOAT&&(l=e.R32F),r===e.HALF_FLOAT&&(l=e.R16F),r===e.UNSIGNED_BYTE&&(l=e.R8)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(l=e.R8UI),r===e.UNSIGNED_SHORT&&(l=e.R16UI),r===e.UNSIGNED_INT&&(l=e.R32UI),r===e.BYTE&&(l=e.R8I),r===e.SHORT&&(l=e.R16I),r===e.INT&&(l=e.R32I)),i===e.RG&&(r===e.FLOAT&&(l=e.RG32F),r===e.HALF_FLOAT&&(l=e.RG16F),r===e.UNSIGNED_BYTE&&(l=e.RG8)),i===e.RGBA){const t=a?Zt:pi.getTransfer(s);r===e.FLOAT&&(l=e.RGBA32F),r===e.HALF_FLOAT&&(l=e.RGBA16F),r===e.UNSIGNED_BYTE&&(l=t===Kt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return l!==e.R16F&&l!==e.R32F&&l!==e.RG16F&&l!==e.RG32F&&l!==e.RGBA16F&&l!==e.RGBA32F||t.get("EXT_color_buffer_float"),l}function y(e,t,n){return!0===_(e,n)||e.isFramebufferTexture&&e.minFilter!==fe&&e.minFilter!==ye?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 b(t){return t===fe||t===ge||t===ve?e.NEAREST:e.LINEAR}function S(e){const t=e.target;t.removeEventListener("dispose",S),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=d.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(r).length&&d.delete(n)}i.remove(e)}(t),t.isVideoTexture&&u.delete(t)}function T(t){const n=t.target;n.removeEventListener("dispose",T),function(t){const n=t.texture,r=i.get(t),s=i.get(n);void 0!==s.__webglTexture&&(e.deleteTexture(s.__webglTexture),a.memory.textures--);t.depthTexture&&t.depthTexture.dispose();if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(r.__webglFramebuffer[t]))for(let n=0;n0&&s.__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 P(s,t,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const w={[de]:e.REPEAT,[pe]:e.CLAMP_TO_EDGE,[me]:e.MIRRORED_REPEAT},R={[fe]:e.NEAREST,[ge]:e.NEAREST_MIPMAP_NEAREST,[ve]:e.NEAREST_MIPMAP_LINEAR,[ye]:e.LINEAR,[be]:e.LINEAR_MIPMAP_NEAREST,[Te]:e.LINEAR_MIPMAP_LINEAR},C={[_n]:e.NEVER,[Mn]:e.ALWAYS,[vn]:e.LESS,[yn]:e.LEQUAL,[xn]:e.EQUAL,[Tn]:e.GEQUAL,[bn]:e.GREATER,[Sn]:e.NOTEQUAL};function N(n,s,a){if(s.type!==Le||!1!==t.has("OES_texture_float_linear")||s.magFilter!==ye&&s.magFilter!==be&&s.magFilter!==ve&&s.magFilter!==Te&&s.minFilter!==ye&&s.minFilter!==be&&s.minFilter!==ve&&s.minFilter!==Te||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),a?(e.texParameteri(n,e.TEXTURE_WRAP_S,w[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,w[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,w[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,R[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,R[s.minFilter])):(e.texParameteri(n,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(n,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,e.CLAMP_TO_EDGE),s.wrapS===pe&&s.wrapT===pe||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),e.texParameteri(n,e.TEXTURE_MAG_FILTER,b(s.magFilter)),e.texParameteri(n,e.TEXTURE_MIN_FILTER,b(s.minFilter)),s.minFilter!==fe&&s.minFilter!==ye&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){const a=t.get("EXT_texture_filter_anisotropic");if(s.magFilter===fe)return;if(s.minFilter!==ve&&s.minFilter!==Te)return;if(s.type===Le&&!1===t.has("OES_texture_float_linear"))return;if(!1===o&&s.type===Pe&&!1===t.has("OES_texture_half_float_linear"))return;(s.anisotropy>1||i.get(s).__currentAnisotropy)&&(e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy)}}function L(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",S));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function P(t,a,l){let c=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(c=e.TEXTURE_3D);const u=L(t,a),h=a.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+l);const d=i.get(h);if(h.version!==d.__version||!0===u){n.activeTexture(e.TEXTURE0+l);const t=pi.getPrimaries(pi.workingColorSpace),i=a.colorSpace===Xt?null:pi.getPrimaries(a.colorSpace),p=a.colorSpace===Xt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,p);const m=function(e){return!o&&(e.wrapS!==pe||e.wrapT!==pe||e.minFilter!==fe&&e.minFilter!==ye)}(a)&&!1===g(a.image);let b=f(a.image,m,!1,r.maxTextureSize);b=B(a,b);const S=g(b)||o,T=s.convert(a.format,a.colorSpace);let M,E=s.convert(a.type),A=x(a.internalFormat,T,E,a.colorSpace,a.isVideoTexture);N(c,a,S);const w=a.mipmaps,R=o&&!0!==a.isVideoTexture&&A!==tt,C=void 0===d.__version||!0===u,L=y(a,b,S);if(a.isDepthTexture)A=e.DEPTH_COMPONENT,o?A=a.type===Le?e.DEPTH_COMPONENT32F:a.type===Ne?e.DEPTH_COMPONENT24:a.type===Oe?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT16:a.type===Le&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),a.format===ze&&A===e.DEPTH_COMPONENT&&a.type!==Re&&a.type!==Ne&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),a.type=Ne,E=s.convert(a.type)),a.format===Ge&&A===e.DEPTH_COMPONENT&&(A=e.DEPTH_STENCIL,a.type!==Oe&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),a.type=Oe,E=s.convert(a.type))),C&&(R?n.texStorage2D(e.TEXTURE_2D,1,A,b.width,b.height):n.texImage2D(e.TEXTURE_2D,0,A,b.width,b.height,0,T,E,null));else if(a.isDataTexture)if(w.length>0&&S){R&&C&&n.texStorage2D(e.TEXTURE_2D,L,A,w[0].width,w[0].height);for(let t=0,i=w.length;t>=1,i>>=1}}else if(w.length>0&&S){R&&C&&n.texStorage2D(e.TEXTURE_2D,L,A,w[0].width,w[0].height);for(let t=0,i=w.length;t>u),i=Math.max(1,r.height>>u);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?n.texImage3D(c,u,p,t,i,r.depth,0,h,d,null):n.texImage2D(c,u,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),F(r)?l.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,o,c,i.get(a).__webglTexture,0,D(r)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,o,c,i.get(a).__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function U(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer&&!n.stencilBuffer){let r=!0===o?e.DEPTH_COMPONENT24:e.DEPTH_COMPONENT16;if(i||F(n)){const t=n.depthTexture;t&&t.isDepthTexture&&(t.type===Le?r=e.DEPTH_COMPONENT32F:t.type===Ne&&(r=e.DEPTH_COMPONENT24));const i=D(n);F(n)?l.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,i,r,n.width,n.height):e.renderbufferStorageMultisample(e.RENDERBUFFER,i,r,n.width,n.height)}else e.renderbufferStorage(e.RENDERBUFFER,r,n.width,n.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)}else if(n.depthBuffer&&n.stencilBuffer){const r=D(n);i&&!1===F(n)?e.renderbufferStorageMultisample(e.RENDERBUFFER,r,e.DEPTH24_STENCIL8,n.width,n.height):F(n)?l.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,r,e.DEPTH24_STENCIL8,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t)}else{const t=!0===n.isWebGLMultipleRenderTargets?n.texture:[n.texture];for(let r=0;r0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function B(e,n){const i=e.colorSpace,r=e.format,s=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||e.format===Dn||i!==qt&&i!==Xt&&(pi.getTransfer(i)===Kt?!1===o?!0===t.has("EXT_sRGB")&&r===Fe?(e.format=Dn,e.minFilter=ye,e.generateMipmaps=!1):n=_i.sRGBToLinear(n):r===Fe&&s===Ee||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",i)),n}this.allocateTextureUnit=function(){const e=E;return e>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),E+=1,e},this.resetTextureUnits=function(){E=0},this.setTexture2D=A,this.setTexture2DArray=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?P(s,t,r):n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r)},this.setTexture3D=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?P(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const l=i.get(t);t.version>0&&l.__version!==t.version?function(t,a,l){if(6!==a.image.length)return;const c=L(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+l);const h=i.get(u);if(u.version!==h.__version||!0===c){n.activeTexture(e.TEXTURE0+l);const t=pi.getPrimaries(pi.workingColorSpace),i=a.colorSpace===Xt?null:pi.getPrimaries(a.colorSpace),d=a.colorSpace===Xt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);const p=a.isCompressedTexture||a.image[0].isCompressedTexture,m=a.image[0]&&a.image[0].isDataTexture,b=[];for(let e=0;e<6;e++)b[e]=p||m?m?a.image[e].image:a.image[e]:f(a.image[e],!1,!0,r.maxCubemapSize),b[e]=B(a,b[e]);const S=b[0],T=g(S)||o,M=s.convert(a.format,a.colorSpace),E=s.convert(a.type),A=x(a.internalFormat,M,E,a.colorSpace),w=o&&!0!==a.isVideoTexture,R=void 0===h.__version||!0===c;let C,L=y(a,S,T);if(N(e.TEXTURE_CUBE_MAP,a,T),p){w&&R&&n.texStorage2D(e.TEXTURE_CUBE_MAP,L,A,S.width,S.height);for(let t=0;t<6;t++){C=b[t].mipmaps;for(let i=0;i0&&L++,n.texStorage2D(e.TEXTURE_CUBE_MAP,L,A,b[0].width,b[0].height));for(let t=0;t<6;t++)if(m){w?n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,b[t].width,b[t].height,M,E,b[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,A,b[t].width,b[t].height,0,M,E,b[t].data);for(let i=0;i0){c.__webglFramebuffer[t]=[];for(let n=0;n0){c.__webglFramebuffer=[];for(let t=0;t0&&!1===F(t)){const i=d?l:[l];c.__webglMultisampledFramebuffer=e.createFramebuffer(),c.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0&&!1===F(t)){const r=t.isWebGLMultipleRenderTargets?t.texture:[t.texture],s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const l=[],u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,h=i.get(t),d=!0===t.isWebGLMultipleRenderTargets;if(d)for(let t=0;to+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Hl)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new kl;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Xl extends Vn{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,u=null,h=null,d=null,p=null;const m=t.getContextAttributes();let f=null,g=null;const _=[],v=[],x=new Qn;let y=null;const b=new Js;b.layers.enable(1),b.viewport=new Ti;const S=new Js;S.layers.enable(2),S.viewport=new Ti;const T=[b,S],M=new Gl;M.layers.enable(1),M.layers.enable(2);let E=null,A=null;function w(e){const t=v.indexOf(e.inputSource);if(-1===t)return;const n=_[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function R(){i.removeEventListener("select",w),i.removeEventListener("selectstart",w),i.removeEventListener("selectend",w),i.removeEventListener("squeeze",w),i.removeEventListener("squeezestart",w),i.removeEventListener("squeezeend",w),i.removeEventListener("end",R),i.removeEventListener("inputsourceschange",C);for(let e=0;e<_.length;e++){const t=v[e];null!==t&&(v[e]=null,_[e].disconnect(t))}E=null,A=null,e.setRenderTarget(f),d=null,h=null,u=null,i=null,g=null,U.stop(),n.isPresenting=!1,e.setPixelRatio(y),e.setSize(x.width,x.height,!1),n.dispatchEvent({type:"sessionend"})}function C(e){for(let t=0;t=0&&(v[i]=null,_[i].disconnect(n))}for(let t=0;t=v.length){v.push(n),i=e;break}if(null===v[e]){v[e]=n,i=e;break}}if(-1===i)break}const r=_[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=_[e];return void 0===t&&(t=new Wl,_[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=_[e];return void 0===t&&(t=new Wl,_[e]=t),t.getGripSpace()},this.getHand=function(e){let t=_[e];return void 0===t&&(t=new Wl,_[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){if(f=e.getRenderTarget(),i.addEventListener("select",w),i.addEventListener("selectstart",w),i.addEventListener("selectend",w),i.addEventListener("squeeze",w),i.addEventListener("squeezestart",w),i.addEventListener("squeezeend",w),i.addEventListener("end",R),i.addEventListener("inputsourceschange",C),!0!==m.xrCompatible&&await t.makeXRCompatible(),y=e.getPixelRatio(),e.getSize(x),void 0===i.renderState.layers||!1===e.capabilities.isWebGL2){const n={antialias:void 0!==i.renderState.layers||m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),g=new Ei(d.framebufferWidth,d.framebufferHeight,{format:Fe,type:Ee,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil})}else{let n=null,s=null,a=null;m.depth&&(a=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=m.stencil?Ge:ze,s=m.stencil?Oe:Ne);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};u=new XRWebGLBinding(i,t),h=u.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),g=new Ei(h.textureWidth,h.textureHeight,{format:Fe,type:Ee,depthTexture:new $a(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0});e.properties.get(g).__ignoreDepthValues=h.ignoreDepthValues}g.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),U.setContext(i),U.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode};const N=new Pi,L=new Pi;function P(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;M.near=S.near=b.near=e.near,M.far=S.far=b.far=e.far,E===M.near&&A===M.far||(i.updateRenderState({depthNear:M.near,depthFar:M.far}),E=M.near,A=M.far);const t=e.parent,n=M.cameras;P(M,t);for(let e=0;e0&&(i.alphaTest.value=r.alphaTest);const s=t.get(r).envMap;if(s&&(i.envMap.value=s,i.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,i.reflectivity.value=r.reflectivity,i.ior.value=r.ior,i.refractionRatio.value=r.refractionRatio),r.lightMap){i.lightMap.value=r.lightMap;const t=!0===e._useLegacyLights?Math.PI:1;i.lightMapIntensity.value=r.lightMapIntensity*t,n(r.lightMap,i.lightMapTransform)}r.aoMap&&(i.aoMap.value=r.aoMap,i.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,i.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,Ys(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(e,r):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r)):r.isMeshStandardMaterial?(i(e,r),function(e,i){e.metalness.value=i.metalness,i.metalnessMap&&(e.metalnessMap.value=i.metalnessMap,n(i.metalnessMap,e.metalnessMapTransform));e.roughness.value=i.roughness,i.roughnessMap&&(e.roughnessMap.value=i.roughnessMap,n(i.roughnessMap,e.roughnessMapTransform));const r=t.get(i).envMap;r&&(e.envMapIntensity.value=i.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===d&&e.clearcoatNormalScale.value.negate()));t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function ql(e,t,n,i){let r={},s={},a=[];const o=n.isWebGL2?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!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 u(t){const n=t.target;n.removeEventListener("dispose",u);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,h){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let e=0,r=t.length;e0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=K;i.toneMapped&&(null!==E&&!0!==E.isXRRenderTarget||(m=b.toneMapping));const f=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==f?f.length:0,_=te.get(i),x=v.state.lights;if(!0===k&&(!0===H||e!==w)){const t=e===w&&i.id===A;de.setState(i,e,t)}let y=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==x.state.version||_.outputColorSpace!==o||r.isBatchedMesh&&!1===_.batching?y=!0:r.isBatchedMesh||!0!==_.batching?r.isInstancedMesh&&!1===_.instancing?y=!0:r.isInstancedMesh||!0!==_.instancing?r.isSkinnedMesh&&!1===_.skinning?y=!0:r.isSkinnedMesh||!0!==_.skinning?r.isInstancedMesh&&!0===_.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===_.instancingColor&&null!==r.instanceColor||_.envMap!==l||!0===i.fog&&_.fog!==s?y=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===de.numPlanes&&_.numIntersection===de.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==u||_.morphTargets!==h||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==m||!0===J.isWebGL2&&_.morphTargetsCount!==g)&&(y=!0):y=!0:y=!0:y=!0:y=!0:(y=!0,_.__version=i.version);let S=_.currentProgram;!0===y&&(S=Ke(i,t,r));let T=!1,M=!1,R=!1;const C=S.getUniforms(),N=_.uniforms;Q.useProgram(S.program)&&(T=!0,M=!0,R=!0);i.id!==A&&(A=i.id,M=!0);if(T||w!==e){C.setValue(be,"projectionMatrix",e.projectionMatrix),C.setValue(be,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(be,q.setFromMatrixPosition(e.matrixWorld)),J.logarithmicDepthBuffer&&C.setValue(be,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(be,"isOrthographic",!0===e.isOrthographicCamera),w!==e&&(w=e,M=!0,R=!0)}if(r.isSkinnedMesh){C.setOptional(be,r,"bindMatrix"),C.setOptional(be,r,"bindMatrixInverse");const e=r.skeleton;e&&(J.floatVertexTextures?(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(be,"boneTexture",e.boneTexture,ne)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}r.isBatchedMesh&&(C.setOptional(be,r,"batchingTexture"),C.setValue(be,"batchingTexture",r._matricesTexture,ne));const L=n.morphAttributes;(void 0!==L.position||void 0!==L.normal||void 0!==L.color&&!0===J.isWebGL2)&&fe.update(r,n,S);(M||_.receiveShadow!==r.receiveShadow)&&(_.receiveShadow=r.receiveShadow,C.setValue(be,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(N.envMap.value=l,N.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);M&&(C.setValue(be,"toneMappingExposure",b.toneMappingExposure),_.needsLights&&(I=R,(P=N).ambientLightColor.needsUpdate=I,P.lightProbe.needsUpdate=I,P.directionalLights.needsUpdate=I,P.directionalLightShadows.needsUpdate=I,P.pointLights.needsUpdate=I,P.pointLightShadows.needsUpdate=I,P.spotLights.needsUpdate=I,P.spotLightShadows.needsUpdate=I,P.rectAreaLights.needsUpdate=I,P.hemisphereLights.needsUpdate=I),s&&!0===i.fog&&ce.refreshFogUniforms(N,s),ce.refreshMaterialUniforms(N,i,O,U,W),tl.upload(be,Je(_),N,ne));var P,I;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(tl.upload(be,Je(_),N,ne),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(be,"center",r.center);if(C.setValue(be,"modelViewMatrix",r.modelViewMatrix),C.setValue(be,"normalMatrix",r.normalMatrix),C.setValue(be,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t{function n(){i.forEach((function(e){te.get(e).currentProgram.isReady()&&i.delete(e)})),0!==i.size?setTimeout(n,10):t(e)}null!==Z.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let ze=null;function Ge(){We.stop()}function ke(){We.start()}const We=new ua;function qe(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)v.pushLight(e),e.castShadow&&v.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||G.intersectsSprite(e)){i&&q.setFromMatrixPosition(e.matrixWorld).applyMatrix4(X);const t=oe.update(e),r=e.material;r.visible&&_.push(e,t,r,n,q.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||G.intersectsObject(e))){const t=oe.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),q.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),q.copy(t.boundingSphere.center)),q.applyMatrix4(e.matrixWorld).applyMatrix4(X)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s0&&function(e,t,n,i){const r=!0===n.isScene?n.overrideMaterial:null;if(null!==r)return;const s=J.isWebGL2;null===W&&(W=new Ei(1,1,{generateMipmaps:!0,type:Z.has("EXT_color_buffer_half_float")?Pe:Ee,minFilter:Te,samples:s?4:0}));b.getDrawingBufferSize(j),s?W.setSize(j.x,j.y):W.setSize($n(j.x),$n(j.y));const a=b.getRenderTarget();b.setRenderTarget(W),b.getClearColor(L),P=b.getClearAlpha(),P<1&&b.setClearColor(16777215,.5);b.clear();const o=b.toneMapping;b.toneMapping=K,$e(e,n,i),ne.updateMultisampleRenderTarget(W),ne.updateRenderTargetMipmap(W);let l=!1;for(let e=0,r=t.length;e0&&$e(r,t,n),s.length>0&&$e(s,t,n),a.length>0&&$e(a,t,n),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function $e(e,t,n){const i=!0===t.isScene?t.overrideMaterial:null;for(let r=0,s=e.length;r0?y[y.length-1]:null,x.pop(),_=x.length>0?x[x.length-1]:null},this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return M},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(e,t,n){te.get(e.texture).__webglTexture=t,te.get(e.depthTexture).__webglTexture=n;const i=te.get(e);i.__hasExternalTextures=!0,i.__hasExternalTextures&&(i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===Z.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(e,t){const n=te.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t},this.setRenderTarget=function(e,t=0,n=0){E=e,T=t,M=n;let i=!0,r=null,s=!1,a=!1;if(e){const o=te.get(e);void 0!==o.__useDefaultFramebuffer?(Q.bindFramebuffer(be.FRAMEBUFFER,null),i=!1):void 0===o.__webglFramebuffer?ne.setupRenderTarget(e):o.__hasExternalTextures&&ne.rebindTextures(e,te.get(e.texture).__webglTexture,te.get(e.depthTexture).__webglTexture);const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=te.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],s=!0):r=J.isWebGL2&&e.samples>0&&!1===ne.useMultisampledRTT(e)?te.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,R.copy(e.viewport),C.copy(e.scissor),N=e.scissorTest}else R.copy(B).multiplyScalar(O).floor(),C.copy(V).multiplyScalar(O).floor(),N=z;if(Q.bindFramebuffer(be.FRAMEBUFFER,r)&&J.drawBuffers&&i&&Q.drawBuffers(e,r),Q.viewport(R),Q.scissor(C),Q.setScissorTest(N),s){const i=te.get(e.texture);be.framebufferTexture2D(be.FRAMEBUFFER,be.COLOR_ATTACHMENT0,be.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(a){const i=te.get(e.texture),r=t||0;be.framebufferTextureLayer(be.FRAMEBUFFER,be.COLOR_ATTACHMENT0,i.__webglTexture,n||0,r)}A=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=te.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Q.bindFramebuffer(be.FRAMEBUFFER,o);try{const a=e.texture,o=a.format,l=a.type;if(o!==Fe&&ve.convert(o)!==be.getParameter(be.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const c=l===Pe&&(Z.has("EXT_color_buffer_half_float")||J.isWebGL2&&Z.has("EXT_color_buffer_float"));if(!(l===Ee||ve.convert(l)===be.getParameter(be.IMPLEMENTATION_COLOR_READ_TYPE)||l===Le&&(J.isWebGL2||Z.has("OES_texture_float")||Z.has("WEBGL_color_buffer_float"))||c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&be.readPixels(t,n,i,r,ve.convert(o),ve.convert(l),s)}finally{const e=null!==E?te.get(E).__webglFramebuffer:null;Q.bindFramebuffer(be.FRAMEBUFFER,e)}}},this.copyFramebufferToTexture=function(e,t,n=0){const i=Math.pow(2,-n),r=Math.floor(t.image.width*i),s=Math.floor(t.image.height*i);ne.setTexture2D(t,0),be.copyTexSubImage2D(be.TEXTURE_2D,n,0,0,e.x,e.y,r,s),Q.unbindTexture()},this.copyTextureToTexture=function(e,t,n,i=0){const r=t.image.width,s=t.image.height,a=ve.convert(n.format),o=ve.convert(n.type);ne.setTexture2D(n,0),be.pixelStorei(be.UNPACK_FLIP_Y_WEBGL,n.flipY),be.pixelStorei(be.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),be.pixelStorei(be.UNPACK_ALIGNMENT,n.unpackAlignment),t.isDataTexture?be.texSubImage2D(be.TEXTURE_2D,i,e.x,e.y,r,s,a,o,t.image.data):t.isCompressedTexture?be.compressedTexSubImage2D(be.TEXTURE_2D,i,e.x,e.y,t.mipmaps[0].width,t.mipmaps[0].height,a,t.mipmaps[0].data):be.texSubImage2D(be.TEXTURE_2D,i,e.x,e.y,a,o,t.image),0===i&&n.generateMipmaps&&be.generateMipmap(be.TEXTURE_2D),Q.unbindTexture()},this.copyTextureToTexture3D=function(e,t,n,i,r=0){if(b.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const s=e.max.x-e.min.x+1,a=e.max.y-e.min.y+1,o=e.max.z-e.min.z+1,l=ve.convert(i.format),c=ve.convert(i.type);let u;if(i.isData3DTexture)ne.setTexture3D(i,0),u=be.TEXTURE_3D;else{if(!i.isDataArrayTexture&&!i.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");ne.setTexture2DArray(i,0),u=be.TEXTURE_2D_ARRAY}be.pixelStorei(be.UNPACK_FLIP_Y_WEBGL,i.flipY),be.pixelStorei(be.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),be.pixelStorei(be.UNPACK_ALIGNMENT,i.unpackAlignment);const h=be.getParameter(be.UNPACK_ROW_LENGTH),d=be.getParameter(be.UNPACK_IMAGE_HEIGHT),p=be.getParameter(be.UNPACK_SKIP_PIXELS),m=be.getParameter(be.UNPACK_SKIP_ROWS),f=be.getParameter(be.UNPACK_SKIP_IMAGES),g=n.isCompressedTexture?n.mipmaps[r]:n.image;be.pixelStorei(be.UNPACK_ROW_LENGTH,g.width),be.pixelStorei(be.UNPACK_IMAGE_HEIGHT,g.height),be.pixelStorei(be.UNPACK_SKIP_PIXELS,e.min.x),be.pixelStorei(be.UNPACK_SKIP_ROWS,e.min.y),be.pixelStorei(be.UNPACK_SKIP_IMAGES,e.min.z),n.isDataTexture||n.isData3DTexture?be.texSubImage3D(u,r,t.x,t.y,t.z,s,a,o,l,c,g.data):n.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),be.compressedTexSubImage3D(u,r,t.x,t.y,t.z,s,a,o,l,g.data)):be.texSubImage3D(u,r,t.x,t.y,t.z,s,a,o,l,c,g),be.pixelStorei(be.UNPACK_ROW_LENGTH,h),be.pixelStorei(be.UNPACK_IMAGE_HEIGHT,d),be.pixelStorei(be.UNPACK_SKIP_PIXELS,p),be.pixelStorei(be.UNPACK_SKIP_ROWS,m),be.pixelStorei(be.UNPACK_SKIP_IMAGES,f),0===r&&i.generateMipmaps&&be.generateMipmap(u),Q.unbindTexture()},this.initTexture=function(e){e.isCubeTexture?ne.setTextureCube(e,0):e.isData3DTexture?ne.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?ne.setTexture2DArray(e,0):ne.setTexture2D(e,0),Q.unbindTexture()},this.resetState=function(){T=0,M=0,E=null,Q.reset(),xe.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Fn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===Yt?"display-p3":"srgb",t.unpackColorSpace=pi.workingColorSpace===$t?"display-p3":"srgb"}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===jt?zt:Vt}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===zt?jt:qt}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class $l extends Yl{}$l.prototype.isWebGL1Renderer=!0;class Zl{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new $r(e),this.density=t}clone(){return new Zl(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Kl{constructor(e,t=1,n=1e3){this.isFog=!0,this.name="",this.color=new $r(e),this.near=t,this.far=n}clone(){return new Kl(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Jl extends Ir{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t}}class Ql{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=En,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Wn()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return console.warn("THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:o,point:rc.clone(),uv:Wr.getInterpolation(rc,uc,hc,dc,pc,mc,fc,new Qn),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function _c(e,t,n,i,r,s){oc.subVectors(e,n).addScalar(.5).multiply(i),void 0!==r?(lc.x=s*oc.x-r*oc.y,lc.y=r*oc.x+s*oc.y):lc.copy(oc),e.copy(t),e.x+=lc.x,e.y+=lc.y,e.applyMatrix4(cc)}const vc=new Pi,xc=new Pi;class yc extends Ir{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,n=t.length;e0){let n,i;for(n=1,i=t.length;n0){vc.setFromMatrixPosition(this.matrixWorld);const n=e.ray.origin.distanceTo(vc);this.getObjectForDistance(n).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){vc.setFromMatrixPosition(e.matrixWorld),xc.setFromMatrixPosition(this.matrixWorld);const n=vc.distanceTo(xc)/e.zoom;let i,r;for(t[0].object.visible=!0,i=1,r=t.length;i=e))break;t[i-1].object.visible=!1,t[i].object.visible=!0}for(this._currentLevel=i-1;i=n.length&&n.push({start:-1,count:-1,z:-1});const r=n[this.index];i.push(r),this.index++,r.start=e.start,r.count=e.count,r.z=t}reset(){this.list.length=0,this.index=0}}const Yc="batchId",$c=new lr,Zc=new lr,Kc=new lr,Jc=new lr,Qc=new ca,eu=new Oi,tu=new Qi,nu=new Pi,iu=new qc,ru=new Hs,su=[];function au(e,t,n=0){const i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let s=0;s65536?new Uint32Array(r):new Uint16Array(r);t.setIndex(new os(e,1))}const s=i>65536?new Uint32Array(n):new Uint16Array(n);t.setAttribute(Yc,new os(s,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(Yc))throw new Error(`BatchedMesh: Geometry cannot use attribute "${Yc}"`);const t=this.geometry;if(Boolean(e.getIndex())!==Boolean(t.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const n in t.attributes){if(n===Yc)continue;if(!e.hasAttribute(n))throw new Error(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=e.getAttribute(n),r=t.getAttribute(n);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Oi);const e=this._geometryCount,t=this.boundingBox,n=this._active;t.makeEmpty();for(let i=0;i=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const s=this._reservedRanges,a=this._drawRanges,o=this._bounds;0!==this._geometryCount&&(r=s[s.length-1]),i.vertexCount=-1===t?e.getAttribute("position").count:t,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const l=e.getIndex(),c=null!==l;if(c&&(i.indexCount=-1===n?l.count:n,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const u=this._visibility,h=this._active,d=this._matricesTexture,p=this._matricesTexture.image.data;u.push(!0),h.push(!0);const m=this._geometryCount;this._geometryCount++,Kc.toArray(p,16*m),d.needsUpdate=!0,s.push(i),a.push({start:c?i.indexStart:i.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Oi,sphereInitialized:!1,sphere:new Qi});const f=this.geometry.getAttribute(Yc);for(let e=0;e=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const n=this.geometry,i=null!==n.getIndex(),r=n.getIndex(),s=t.getIndex(),a=this._reservedRanges[e];if(i&&s.count>a.indexCount||t.attributes.position.count>a.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.vertexCount;for(const e in n.attributes){if(e===Yc)continue;const i=t.getAttribute(e),r=n.getAttribute(e);au(i,r,o);const s=i.itemSize;for(let e=i.count,t=l;e=t.length||!1===t[e]||(t[e]=!1,this._visibilityChanged=!0),this}getBoundingBoxAt(e,t){if(!1===this._active[e])return null;const n=this._bounds[e],i=n.box,r=this.geometry;if(!1===n.boxInitialized){i.makeEmpty();const t=r.index,s=r.attributes.position,a=this._drawRanges[e];for(let e=a.start,n=a.start+a.count;e=this._geometryCount||!1===n[e]||(t.toArray(r,16*e),i.needsUpdate=!0),this}getMatrixAt(e,t){const n=this._active,i=this._matricesTexture.image.data;return e>=this._geometryCount||!1===n[e]?null:t.fromArray(i,16*e)}setVisibleAt(e,t){const n=this._visibility,i=this._active;return e>=this._geometryCount||!1===i[e]||n[e]===t||(n[e]=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._visibility,n=this._active;return!(e>=this._geometryCount||!1===n[e])&&t[e]}raycast(e,t){const n=this._visibility,i=this._active,r=this._drawRanges,s=this._geometryCount,a=this.matrixWorld,o=this.geometry;ru.material=this.material,ru.geometry.index=o.index,ru.geometry.attributes=o.attributes,null===ru.geometry.boundingBox&&(ru.geometry.boundingBox=new Oi),null===ru.geometry.boundingSphere&&(ru.geometry.boundingSphere=new Qi);for(let o=0;o({...e}))),this._reservedRanges=e._reservedRanges.map((e=>({...e}))),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,t,n,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=i.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._active,l=this._visibility,c=this._multiDrawStarts,u=this._multiDrawCounts,h=this._drawRanges,d=this.perObjectFrustumCulled;d&&(Jc.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),Qc.setFromProjectionMatrix(Jc,e.isWebGPURenderer?Bn:Fn));let p=0;if(this.sortObjects){Zc.copy(this.matrixWorld).invert(),nu.setFromMatrixPosition(n.matrixWorld).applyMatrix4(Zc);for(let e=0,t=l.length;eo)continue;h.applyMatrix4(this.matrixWorld);const s=e.ray.origin.distanceTo(h);se.far||t.push({distance:s,point:u.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}else{for(let n=Math.max(0,s.start),i=Math.min(m.count,s.start+s.count)-1;no)continue;h.applyMatrix4(this.matrixWorld);const i=e.ray.origin.distanceTo(h);ie.far||t.push({distance:i,point:u.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;er.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:t,face:null,object:a})}}class Au extends Si{constructor(e,t,n,i,r,s,a,o,l){super(e,t,n,i,r,s,a,o,l),this.isVideoTexture=!0,this.minFilter=void 0!==s?s:ye,this.magFilter=void 0!==r?r:ye,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){c.needsUpdate=!0,e.requestVideoFrameCallback(t)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class wu extends Si{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fe,this.minFilter=fe,this.generateMipmaps=!1,this.needsUpdate=!0}}class Ru extends Si{constructor(e,t,n,i,r,s,a,o,l,c,u,h){super(null,s,a,o,l,c,i,r,u,h),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Cu extends Ru{constructor(e,t,n,i,r,s){super(e,t,n,r,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=pe}}class Nu extends Ru{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,oe),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class Lu extends Si{constructor(e,t,n,i,r,s,a,o,l){super(e,t,n,i,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Pu{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new Qn:new Pi);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t){const n=new Pi,i=[],r=[],s=[],a=new Pi,o=new lr;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new Pi)}r[0]=new Pi,s[0]=new Pi;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),u=Math.abs(i[0].y),h=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),u<=l&&(l=u,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(Xn(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Xn(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Iu extends Pu{constructor(e=0,t=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t){const n=t||new Qn,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Du.subVectors(i[0],i[1]).add(i[0]),a=Du);const u=i[l%r],h=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],u=i[s>i.length-3?i.length-1:s+2];return n.set(Gu(a,o.x,l.x,c.x,u.x),Gu(a,o.y,l.y,c.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){const e=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-e/a;return s.getPointAt(o,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.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 e=[];let t=0;for(let n=0,i=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){const e=l.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class eh extends Es{constructor(e=[new Qn(0,-.5),new Qn(.5,0),new Qn(0,.5)],t=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:n,phiLength:i},t=Math.floor(t),i=Xn(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/t,u=new Pi,h=new Qn,d=new Pi,p=new Pi,m=new Pi;let f=0,g=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:f=e[t+1].x-e[t].x,g=e[t+1].y-e[t].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case e.length-1:o.push(m.x,m.y,m.z);break;default:f=e[t+1].x-e[t].x,g=e[t+1].y-e[t].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=t;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=e.length-1;n++){u.x=e[n].x*p,u.y=e[n].y,u.z=e[n].x*m,s.push(u.x,u.y,u.z),h.x=r/t,h.y=n/(e.length-1),a.push(h.x,h.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n0&&_(!0),t>0&&_(!1)),this.setIndex(c),this.setAttribute("position",new gs(u,3)),this.setAttribute("normal",new gs(h,3)),this.setAttribute("uv",new gs(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ih(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class rh extends ih{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new rh(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class sh extends Es{constructor(e=[],t=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:i};const r=[],s=[];function a(e,t,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=e.clone().lerp(n,i/r),o=t.clone().lerp(n,i/r),l=r-i;for(let e=0;e<=l;e++)s[i][e]=0===e&&i===r?a:a.clone().lerp(o,e/l)}for(let e=0;e.9&&a<.1&&(t<.2&&(s[e+0]+=1),n<.2&&(s[e+2]+=1),i<.2&&(s[e+4]+=1))}}()}(),this.setAttribute("position",new gs(r,3)),this.setAttribute("normal",new gs(r.slice(),3)),this.setAttribute("uv",new gs(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new sh(e.vertices,e.indices,e.radius,e.details)}}class ah extends sh{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,i=1/n;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,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[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],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new ah(e.radius,e.detail)}}const oh=new Pi,lh=new Pi,ch=new Pi,uh=new Wr;class hh extends Es{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const n=4,i=Math.pow(10,n),r=Math.cos(kn*t),s=e.getIndex(),a=e.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],u=new Array(3),h={},d=[];for(let e=0;e80*n){o=c=e[0],l=u=e[1];for(let t=n;tc&&(c=h),d>u&&(u=d);p=Math.max(c-o,u-l),p=0!==p?32767/p:0}return gh(s,a,n,o,l,p,0),a};function mh(e,t,n,i,r){let s,a;if(r===function(e,t,n,i){let r=0;for(let s=t,a=n-i;s0)for(s=t;s=t;s-=i)a=Oh(s,e[s],e[s+1],a);return a&&Ch(a,a.next)&&(Dh(a),a=a.next),a}function fh(e,t){if(!e)return e;t||(t=e);let n,i=e;do{if(n=!1,i.steiner||!Ch(i,i.next)&&0!==Rh(i.prev,i,i.next))i=i.next;else{if(Dh(i),i=t=i.prev,i===i.next)break;n=!0}}while(n||i!==t);return t}function gh(e,t,n,i,r,s,a){if(!e)return;!a&&s&&function(e,t,n,i){let r=e;do{0===r.z&&(r.z=Mh(r.x,r.y,t,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,n,i,r,s,a,o,l,c=1;do{for(n=e,e=null,s=null,a=0;n;){for(a++,i=n,o=0,t=0;t0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:e=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(e,i,r,s);let o,l,c=e;for(;e.prev!==e.next;)if(o=e.prev,l=e.next,s?vh(e,i,r,s):_h(e))t.push(o.i/n|0),t.push(e.i/n|0),t.push(l.i/n|0),Dh(e),e=l.next,c=l.next;else if((e=l)===c){a?1===a?gh(e=xh(fh(e),t,n),t,n,i,r,s,2):2===a&&yh(e,t,n,i,r,s):gh(fh(e),t,n,i,r,s,1);break}}function _h(e){const t=e.prev,n=e,i=e.next;if(Rh(t,n,i)>=0)return!1;const r=t.x,s=n.x,a=i.x,o=t.y,l=n.y,c=i.y,u=rs?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==t;){if(m.x>=u&&m.x<=d&&m.y>=h&&m.y<=p&&Ah(r,o,s,l,a,c,m.x,m.y)&&Rh(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function vh(e,t,n,i){const r=e.prev,s=e,a=e.next;if(Rh(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,u=r.y,h=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,g=u>h?u>d?u:d:h>d?h:d,_=Mh(p,m,t,n,i),v=Mh(f,g,t,n,i);let x=e.prevZ,y=e.nextZ;for(;x&&x.z>=_&&y&&y.z<=v;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ah(o,u,l,h,c,d,x.x,x.y)&&Rh(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ah(o,u,l,h,c,d,y.x,y.y)&&Rh(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;x&&x.z>=_;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ah(o,u,l,h,c,d,x.x,x.y)&&Rh(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;y&&y.z<=v;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ah(o,u,l,h,c,d,y.x,y.y)&&Rh(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function xh(e,t,n){let i=e;do{const r=i.prev,s=i.next.next;!Ch(r,s)&&Nh(r,i,i.next,s)&&Ih(r,s)&&Ih(s,r)&&(t.push(r.i/n|0),t.push(i.i/n|0),t.push(s.i/n|0),Dh(i),Dh(i.next),i=e=s),i=i.next}while(i!==e);return fh(i)}function yh(e,t,n,i,r,s){let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&wh(a,e)){let o=Uh(a,e);return a=fh(a,a.next),o=fh(o,o.next),gh(a,t,n,i,r,s,0),void gh(o,t,n,i,r,s,0)}e=e.next}a=a.next}while(a!==e)}function bh(e,t){return e.x-t.x}function Sh(e,t){const n=function(e,t){let n,i=t,r=-1/0;const s=e.x,a=e.y;do{if(a<=i.y&&a>=i.next.y&&i.next.y!==i.y){const e=i.x+(a-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>r&&(r=e,n=i.x=i.x&&i.x>=l&&s!==i.x&&Ah(an.x||i.x===n.x&&Th(n,i)))&&(n=i,h=u)),i=i.next}while(i!==o);return n}(e,t);if(!n)return t;const i=Uh(n,e);return fh(i,i.next),fh(n,n.next)}function Th(e,t){return Rh(e.prev,e,t.prev)<0&&Rh(t.next,e,e.next)<0}function Mh(e,t,n,i,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Eh(e){let t=e,n=e;do{(t.x=(e-a)*(s-o)&&(e-a)*(i-o)>=(n-a)*(t-o)&&(n-a)*(s-o)>=(r-a)*(i-o)}function wh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&Nh(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}(e,t)&&(Ih(e,t)&&Ih(t,e)&&function(e,t){let n=e,i=!1;const r=(e.x+t.x)/2,s=(e.y+t.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==e);return i}(e,t)&&(Rh(e.prev,e,t.prev)||Rh(e,t.prev,t))||Ch(e,t)&&Rh(e.prev,e,e.next)>0&&Rh(t.prev,t,t.next)>0)}function Rh(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function Ch(e,t){return e.x===t.x&&e.y===t.y}function Nh(e,t,n,i){const r=Ph(Rh(e,t,n)),s=Ph(Rh(e,t,i)),a=Ph(Rh(n,i,e)),o=Ph(Rh(n,i,t));return r!==s&&a!==o||(!(0!==r||!Lh(e,n,t))||(!(0!==s||!Lh(e,i,t))||(!(0!==a||!Lh(n,e,i))||!(0!==o||!Lh(n,t,i)))))}function Lh(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ph(e){return e>0?1:e<0?-1:0}function Ih(e,t){return Rh(e.prev,e,e.next)<0?Rh(e,t,e.next)>=0&&Rh(e,e.prev,t)>=0:Rh(e,t,e.prev)<0||Rh(e,e.next,t)<0}function Uh(e,t){const n=new Fh(e.i,e.x,e.y),i=new Fh(t.i,t.x,t.y),r=e.next,s=t.prev;return e.next=t,t.prev=e,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function Oh(e,t,n,i){const r=new Fh(e,t,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Dh(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function Fh(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class Bh{static area(e){const t=e.length;let n=0;for(let i=t-1,r=0;r2&&e[t-1].equals(e[0])&&e.pop()}function zh(e,t){for(let n=0;nNumber.EPSILON){const h=Math.sqrt(u),d=Math.sqrt(l*l+c*c),p=t.x-o/h,m=t.y+a/h,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-e.x,r=m+o*f-e.y;const g=i*i+r*r;if(g<=2)return new Qn(i,r);s=Math.sqrt(g/2)}else{let e=!1;a>Number.EPSILON?l>Number.EPSILON&&(e=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(e=!0):Math.sign(o)===Math.sign(c)&&(e=!0),e?(i=-o,r=a,s=Math.sqrt(u)):(i=a,r=o,s=Math.sqrt(u/2))}return new Qn(i/s,r/s)}const L=[];for(let e=0,t=A.length,n=t-1,i=e+1;e=0;e--){const t=e/p,n=u*Math.cos(t*Math.PI/2),i=h*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=n;let r=n-1;r<0&&(r=e.length-1);for(let e=0,n=o+2*p;e0)&&d.push(t,r,l),(e!==n-1||o0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class sd extends Jr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new $r(16777215),this.specular=new $r(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Qn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ad extends Jr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new $r(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Qn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class od extends Jr{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Qn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class ld extends Jr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new $r(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Qn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class cd extends Jr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new $r(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Qn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ud extends lu{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function hd(e,t,n){return!e||!n&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function dd(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function pd(e){const t=e.length,n=new Array(t);for(let e=0;e!==t;++e)n[e]=e;return n.sort((function(t,n){return e[t]-e[n]})),n}function md(e,t,n){const i=e.length,r=new e.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*t;for(let n=0;n!==t;++n)r[a++]=e[i+n]}return r}function fd(e,t,n,i){let r=1,s=e[0];for(;void 0!==s&&void 0===s[i];)s=e[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(t.push(s.time),n.push.apply(n,a)),s=e[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(t.push(s.time),a.toArray(n,n.length)),s=e[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(t.push(s.time),n.push(a)),s=e[r++]}while(void 0!==s)}const gd={convertArray:hd,isTypedArray:dd,getKeyframeOrder:pd,sortedArray:md,flattenJSON:fd,subclip:function(e,t,n,i,r=30){const s=e.clone();s.name=t;const a=[];for(let e=0;e=i)){l.push(t.times[e]);for(let n=0;ns.tracks[e].times[0]&&(o=s.tracks[e].times[0]);for(let e=0;e=i.times[h]){const e=h*l+o,t=e+l-o;d=i.values.slice(e,t)}else{const e=i.createInterpolant(),t=o,n=l-o;e.evaluate(s),d=e.resultBuffer.slice(t,n)}if("quaternion"===r){(new Li).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let e=0;e=r)break e;{const a=t[1];e=r)break t}s=n,n=0}}for(;n>>1;et;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const e=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*e,s*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let t=0;t!==r;t++){const i=n[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,s),e=!1;break}s=i}if(void 0!==i&&dd(i))for(let t=0,n=i.length;t!==n;++t){const n=i[t];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,n),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Nt,r=e.length-1;let s=1;for(let a=1;a0){e[s]=e[r];for(let e=r*n,i=s*n,a=0;a!==n;++a)t[i+a]=t[e+a];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*n)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),n=new(0,this.constructor)(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}bd.prototype.TimeBufferType=Float32Array,bd.prototype.ValueBufferType=Float32Array,bd.prototype.DefaultInterpolation=Ct;class Sd extends bd{}Sd.prototype.ValueTypeName="bool",Sd.prototype.ValueBufferType=Array,Sd.prototype.DefaultInterpolation=Rt,Sd.prototype.InterpolantFactoryMethodLinear=void 0,Sd.prototype.InterpolantFactoryMethodSmooth=void 0;class Td extends bd{}Td.prototype.ValueTypeName="color";class Md extends bd{}Md.prototype.ValueTypeName="number";class Ed extends _d{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-t)/(i-t);let l=e*a;for(let e=l+a;l!==e;l+=4)Li.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Ad extends bd{InterpolantFactoryMethodLinear(e){return new Ed(this.times,this.values,this.getValueSize(),e)}}Ad.prototype.ValueTypeName="quaternion",Ad.prototype.DefaultInterpolation=Ct,Ad.prototype.InterpolantFactoryMethodSmooth=void 0;class wd extends bd{}wd.prototype.ValueTypeName="string",wd.prototype.ValueBufferType=Array,wd.prototype.DefaultInterpolation=Rt,wd.prototype.InterpolantFactoryMethodLinear=void 0,wd.prototype.InterpolantFactoryMethodSmooth=void 0;class Rd extends bd{}Rd.prototype.ValueTypeName="vector";class Cd{constructor(e,t=-1,n,i=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Wn(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,i=1/(e.fps||1);for(let e=0,r=n.length;e!==r;++e)t.push(Nd(n[e]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=n.length;e!==i;++e)t.push(bd.toJSON(n[e]));return i}static CreateFromMorphTargetSequence(e,t,n,i){const r=t.length,s=[];for(let e=0;e1){const e=s[1];let t=i[e];t||(i[e]=t=[]),t.push(n)}}const s=[];for(const e in i)s.push(this.CreateFromMorphTargetSequence(e,i[e],t,n));return s}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(e,t,n,i,r){if(0!==n.length){const s=[],a=[];fd(n,s,a,i),0!==s.length&&r.push(new e(t,s,a))}},i=[],r=e.name||"default",s=e.fps||30,a=e.blendMode;let o=e.length||-1;const l=e.hierarchy||[];for(let e=0;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==Od[e])return void Od[e].push({onLoad:t,onProgress:n,onError:i});Od[e]=[],Od[e].push({onLoad:t,onProgress:n,onError:i});const s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const n=Od[e],i=t.body.getReader(),r=t.headers.get("Content-Length")||t.headers.get("X-File-Size"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(e){!function t(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let e=0,t=n.length;e{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,a)));case"json":return e.json();default:if(void 0===a)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(a),n=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(n);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Ld.add(e,t);const n=Od[e];delete Od[e];for(let e=0,i=n.length;e{const n=Od[e];if(void 0===n)throw this.manager.itemError(e),t;delete Od[e];for(let e=0,i=n.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Bd extends Ud{constructor(e){super(e)}load(e,t,n,i){const r=this,s=new Fd(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,(function(n){try{t(r.parse(JSON.parse(n)))}catch(t){i?i(t):console.error(t),r.manager.itemError(e)}}),n,i)}parse(e){const t=[];for(let n=0;n0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const r=e.uniforms[t];switch(i.uniforms[t]={},r.type){case"t":i.uniforms[t].value=n(r.value);break;case"c":i.uniforms[t].value=(new $r).setHex(r.value);break;case"v2":i.uniforms[t].value=(new Qn).fromArray(r.value);break;case"v3":i.uniforms[t].value=(new Pi).fromArray(r.value);break;case"v4":i.uniforms[t].value=(new Ti).fromArray(r.value);break;case"m3":i.uniforms[t].value=(new ei).fromArray(r.value);break;case"m4":i.uniforms[t].value=(new lr).fromArray(r.value);break;default:i.uniforms[t].value=r.value}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(i.lights=e.lights),void 0!==e.clipping&&(i.clipping=e.clipping),void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=n(e.map)),void 0!==e.matcap&&(i.matcap=n(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=n(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=n(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=n(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Qn).fromArray(t)}return void 0!==e.displacementMap&&(i.displacementMap=n(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=n(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=n(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=n(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=n(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=n(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=n(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=n(e.envMap)),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=n(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=n(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=n(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=n(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=n(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Qn).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=n(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=n(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=n(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=n(e.thicknessMap)),void 0!==e.anisotropyMap&&(i.anisotropyMap=n(e.anisotropyMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=n(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=n(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}static createMaterialFromType(e){return new{ShadowMaterial:td,SpriteMaterial:nc,RawShaderMaterial:nd,ShaderMaterial:Zs,PointsMaterial:xu,MeshPhysicalMaterial:rd,MeshStandardMaterial:id,MeshPhongMaterial:sd,MeshToonMaterial:ad,MeshNormalMaterial:od,MeshLambertMaterial:ld,MeshDepthMaterial:Ol,MeshDistanceMaterial:Dl,MeshBasicMaterial:Qr,MeshMatcapMaterial:cd,LineDashedMaterial:ud,LineBasicMaterial:lu,Material:Jr}[e]}}class up{static decodeText(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let n=0,i=e.length;n0){const n=new Pd(t);r=new zd(n),r.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t0){i=new zd(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t{const t=new Oi;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const n=new Qi;return n.radius=e.sphereRadius,n.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:n}})),s._maxGeometryCount=e.maxGeometryCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._geometryCount=e.geometryCount,s._matricesTexture=u(e.matricesTexture.uuid);break;case"LOD":s=new yc;break;case"Line":s=new mu(l(e.geometry),c(e.material));break;case"LineLoop":s=new vu(l(e.geometry),c(e.material));break;case"LineSegments":s=new _u(l(e.geometry),c(e.material));break;case"PointCloud":case"Points":s=new Mu(l(e.geometry),c(e.material));break;case"Sprite":s=new gc(c(e.material));break;case"Group":s=new kl;break;case"Bone":s=new Lc;break;default:s=new Ir}if(s.uuid=e.uuid,void 0!==e.name&&(s.name=e.name),void 0!==e.matrix?(s.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(s.matrixAutoUpdate=e.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==e.position&&s.position.fromArray(e.position),void 0!==e.rotation&&s.rotation.fromArray(e.rotation),void 0!==e.quaternion&&s.quaternion.fromArray(e.quaternion),void 0!==e.scale&&s.scale.fromArray(e.scale)),void 0!==e.up&&s.up.fromArray(e.up),void 0!==e.castShadow&&(s.castShadow=e.castShadow),void 0!==e.receiveShadow&&(s.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.bias&&(s.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(s.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(s.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&s.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(s.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(s.visible=e.visible),void 0!==e.frustumCulled&&(s.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(s.renderOrder=e.renderOrder),void 0!==e.userData&&(s.userData=e.userData),void 0!==e.layers&&(s.layers.mask=e.layers),void 0!==e.children){const a=e.children;for(let e=0;e{t&&t(n),r.manager.itemEnd(e)})).catch((e=>{i&&i(e)})):(setTimeout((function(){t&&t(s),r.manager.itemEnd(e)}),0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(e,a).then((function(e){return e.blob()})).then((function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){return Ld.add(e,n),t&&t(n),r.manager.itemEnd(e),n})).catch((function(t){i&&i(t),Ld.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));Ld.add(e,o),r.manager.itemStart(e)}}let vp;class xp{static getContext(){return void 0===vp&&(vp=new(window.AudioContext||window.webkitAudioContext)),vp}static setContext(e){vp=e}}class yp extends Ud{constructor(e){super(e)}load(e,t,n,i){const r=this,s=new Fd(this.manager);function a(t){i?i(t):console.error(t),r.manager.itemError(e)}s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,(function(e){try{const n=e.slice(0);xp.getContext().decodeAudioData(n,(function(e){t(e)})).catch(a)}catch(e){a(e)}}),n,i)}}const bp=new lr,Sp=new lr,Tp=new lr;class Mp{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Js,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Js,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(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Tp.copy(e.projectionMatrix);const n=t.eyeSep/2,i=n*t.near/t.focus,r=t.near*Math.tan(kn*t.fov*.5)/t.zoom;let s,a;Sp.elements[12]=-n,bp.elements[12]=n,s=-r*t.aspect+i,a=r*t.aspect+i,Tp.elements[0]=2*t.near/(a-s),Tp.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(Tp),s=-r*t.aspect-i,a=r*t.aspect-i,Tp.elements[0]=2*t.near/(a-s),Tp.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(Tp)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Sp),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(bp)}}class Ep{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Ap(),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 e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=Ap();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Ap(){return("undefined"==typeof performance?Date:performance).now()}const wp=new Pi,Rp=new Li,Cp=new Pi,Np=new Pi;class Lp extends Ir{constructor(){super(),this.type="AudioListener",this.context=xp.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Ep}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(e){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,n=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(wp,Rp,Cp),Np.set(0,0,-1).applyQuaternion(Rp),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(wp.x,e),t.positionY.linearRampToValueAtTime(wp.y,e),t.positionZ.linearRampToValueAtTime(wp.z,e),t.forwardX.linearRampToValueAtTime(Np.x,e),t.forwardY.linearRampToValueAtTime(Np.y,e),t.forwardZ.linearRampToValueAtTime(Np.z,e),t.upX.linearRampToValueAtTime(n.x,e),t.upY.linearRampToValueAtTime(n.y,e),t.upZ.linearRampToValueAtTime(n.z,e)}else t.setPosition(wp.x,wp.y,wp.z),t.setOrientation(Np.x,Np.y,Np.z,n.x,n.y,n.z)}}class Pp extends Ir{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.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(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=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+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,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(){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(),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 e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(n[e]!==n[e+t]){a.setValue(n,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let e=n,r=i;e!==r;++e)t[e]=t[i+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let i=0;i!==r;++i)e[t+i]=e[n+i]}_slerp(e,t,n,i){Li.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){const s=this._workIndex*r;Li.multiplyQuaternionsFlat(e,s,e,t,e,n),Li.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=t+a;e[r]=e[r]*s+e[n+a]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){const r=t+s;e[r]=e[r]+e[n+s]*i}}}const zp="\\[\\]\\.:\\/",Gp=new RegExp("["+zp+"]","g"),kp="[^"+zp+"]",Hp="[^"+zp.replace("\\.","")+"]",Wp=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",kp)+/(WCOD+)?/.source.replace("WCOD",Hp)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",kp)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",kp)+"$"),Xp=["material","materials","bones","map"];class jp{constructor(e,t,n){this.path=t,this.parsedPath=n||jp.parseTrackName(t),this.node=jp.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new jp.Composite(e,t,n):new jp(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Gp,"")}static parseTrackName(e){const t=Wp.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=n.nodeName.substring(i+1);-1!==Xp.indexOf(e)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=e)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(void 0!==n)return n}if(e.children){const n=function(e){for(let i=0;i=r){const s=r++,c=e[s];t[c.uuid]=l,e[l]=c,t[o]=s,e[s]=a;for(let e=0,t=i;e!==t;++e){const t=n[e],i=t[s],r=t[l];t[l]=i,t[s]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=e.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=t[o];if(void 0!==l)if(delete t[o],l0&&(t[a.uuid]=l),e[l]=a,e.pop();for(let e=0,t=i;e!==t;++e){const t=n[e];t[l]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const n=this._bindingsIndicesByPath;let i=n[e];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,u=new Array(l);i=r.length,n[e]=i,s.push(e),a.push(t),r.push(u);for(let n=c,i=o.length;n!==i;++n){const i=o[n];u[n]=new jp(i,e,t)}return u}unsubscribe_(e){const t=this._bindingsIndicesByPath,n=t[e];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];t[e[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}}class Yp{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;const r=t.tracks,s=r.length,a=new Array(s),o={endingStart:Lt,endingEnd:Lt};for(let e=0;e!==s;++e){const t=r[e].createInterpolant(null);a[e]=t,t.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),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(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n){if(e.fadeOut(t),this.fadeIn(t),n){const n=this._clip.duration,i=e._clip.duration,r=i/n,s=n/i;e.warp(1,r,t),this.warp(s,1,t)}return this}crossFadeTo(e,t,n){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const i=this._mixer,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=e/s,l[1]=t/s,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*n;i<0||0===n?t=0:(this._startTime=null,t=n*i)}t*=this._updateTimeScale(e);const s=this._updateTime(t),a=this._updateWeight(e);if(a>0){const e=this._interpolants,t=this._propertyBindings;if(this.blendMode===Ot)for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(s),t[n].accumulateAdditive(a);else for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(s),t[n].accumulate(i,a)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){t*=n.evaluate(e)[0],e>n.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let i=this.time+e,r=this._loopCount;const s=2202===n;if(0===e)return-1===r?i:s&&1==(1&r)?t-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=t||i<0){const n=Math.floor(i/t);i-=t*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===a){const t=e<0;this._setEndings(t,!t,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return t-i}return i}_setEndings(e,t,n){const i=this._interpolantSettings;n?(i.endingStart=Pt,i.endingEnd=Pt):(i.endingStart=e?this.zeroSlopeAtStart?Pt:Lt:It,i.endingEnd=t?this.zeroSlopeAtEnd?Pt:Lt:It)}_scheduleFading(e,t,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=t,a[1]=r+e,o[1]=n,this}}const $p=new Float32Array(1);class Zp extends Vn{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const n=e._localRoot||this._root,i=e._clip.tracks,r=i.length,s=e._propertyBindings,a=e._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let e=0;e!==r;++e){const r=i[e],l=r.name;let u=c[l];if(void 0!==u)++u.referenceCount,s[e]=u;else{if(u=s[e],void 0!==u){null===u._cacheIndex&&(++u.referenceCount,this._addInactiveBinding(u,o,l));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;u=new Vp(jp.create(n,l,i),r.ValueTypeName,r.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,o,l),s[e]=u}a[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,n=e._clip.uuid,i=this._actionsByClip[n];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,n,t)}const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,i=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let a=0;a!==n;++a){t[a]._update(i,e,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let e=0;e!==o;++e)a[e].apply(s);return this}setTime(e){this.time=0;for(let e=0;ethis.max.x||e.ythis.max.y)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,om).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const cm=new Pi,um=new Pi;class hm{constructor(e=new Pi,t=new Pi){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){cm.subVectors(e,this.start),um.subVectors(this.end,this.start);const n=um.dot(um);let i=um.dot(cm)/n;return t&&(i=Xn(i,0,1)),i}closestPointToPoint(e,t,n){const i=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const dm=new Pi;class pm extends Ir{constructor(e,t){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const n=new Es,i=[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 e=0,t=1,n=32;e1)for(let n=0;n.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Bm.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Bm,t)}}setLength(e,t=.2*e,n=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class km extends _u{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=new Es;n.setAttribute("position",new gs(t,3)),n.setAttribute("color",new gs([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new lu({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,n){const i=new $r,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class Hm{constructor(){this.type="ShapePath",this.color=new $r,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Qu,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,i){return this.currentPath.quadraticCurveTo(e,t,n,i),this}bezierCurveTo(e,t,n,i,r,s){return this.currentPath.bezierCurveTo(e,t,n,i,r,s),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const n=t.length;let i=!1;for(let r=n-1,s=0;sNumber.EPSILON){if(l<0&&(n=t[s],o=-o,a=t[r],l=-l),e.ya.y)continue;if(e.y===n.y){if(e.x===n.x)return!0}else{const t=l*(e.x-n.x)-o*(e.y-n.y);if(0===t)return!0;if(t<0)continue;i=!i}}else{if(e.y!==n.y)continue;if(a.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=a.x)return!0}}return i}const n=Bh.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,s,a;const o=[];if(1===i.length)return s=i[0],a=new dh,a.curves=s.curves,o.push(a),o;let l=!n(i[0].getPoints());l=e?!l:l;const c=[],u=[];let h,d,p=[],m=0;u[m]=void 0,p[m]=[];for(let t=0,a=i.length;t1){let e=!1,n=0;for(let e=0,t=u.length;e0&&!1===e&&(p=c)}for(let e=0,t=u.length;e{this.requestId=self.requestAnimationFrame(e),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this.animationLoop&&this.animationLoop(t,n)};e()}dispose(){self.cancelAnimationFrame(this.requestId)}setAnimationLoop(e){this.animationLoop=e}}class qm{constructor(){this.weakMap=new WeakMap}get(e){if(Array.isArray(e)){let t=this.weakMap;for(let n=0;n{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;n.push(e);const s=e.isInterleavedBufferAttribute?e.data:e;i.add(s)}return this.attributes=n,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getMaterialCacheKey(){const{object:e,material:t}=this;let n=t.customProgramCacheKey();for(const e in t){if(/^(is[A-Z])|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;let i=t[e];if(null!==i){const e=typeof i;"number"===e?i=0!==i?"1":"0":"object"===e&&(i="{}")}n+=i+","}return e.skeleton&&(n+=e.skeleton.uuid+","),e.morphTargetInfluences&&(n+=e.morphTargetInfluences.length+","),n}get needsUpdate(){return this.initialNodesCacheKey!==this.getNodesCacheKey()}getNodesCacheKey(){return this._nodes.getCacheKey(this.scene,this.lightsNode)}getCacheKey(){return this.getMaterialCacheKey()+","+this.getNodesCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}class Zm{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this.chainMaps={}}get(e,t,n,i,r,s,a){const o=this.getChainMap(a),l=[e,t,s,r];let c=o.get(l);return void 0===c?(c=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a),o.set(l,c)):(c.version!==t.version||c.needsUpdate)&&(c.initialCacheKey!==c.getCacheKey()?(c.dispose(),c=this.get(e,t,n,i,r,s,a)):c.version=t.version),c}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new qm)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,c){const u=this.getChainMap(c),h=new $m(e,t,n,i,r,s,a,o,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),u.delete(h.getChainArray())},h}}class Km{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const Jm=1,Qm=2,ef=4,tf=16;class nf extends Km{constructor(e){super(),this.backend=e}delete(e){void 0!==super.delete(e)&&this.backend.destroyAttribute(e)}update(e,t){const n=this.get(e);if(void 0===n.version)t===Jm?this.backend.createAttribute(e):t===Qm?this.backend.createIndexAttribute(e):t===ef&&this.backend.createStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?ms:ds)(t,1);return r.version=rf(e),r}class af extends Km{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const n=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n)};t.addEventListener("dispose",n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)this.updateAttribute(e,Jm);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,Qm)}updateAttribute(e,t){const n=this.info.render.calls;this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=sf(t),e.set(t,n)):n.version!==rf(t)&&(this.attributes.delete(n),n=sf(t),e.set(t,n)),i=n}return i}}class of{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,drawCalls:0,triangles:0,points:0,lines:0},this.compute={calls:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine&&(this.render.lines+=n*(t-1))}reset(){this.render.drawCalls=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.memory.geometries=0,this.memory.textures=0}}class lf{constructor(e){this.cacheKey=e,this.usedTimes=0}}class cf extends lf{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class uf extends lf{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let hf=0;class df{constructor(e,t){this.id=hf++,this.code=e,this.stage=t,this.usedTimes=0}}class pf extends Km{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:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new df(s.computeShader,"compute"),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(e),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e){const{backend:t}=this,n=this.get(e);if(this._needsRenderUpdate(e)){const i=n.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const r=e.getNodeBuilderState();let s=this.programs.vertex.get(r.vertexShader);void 0===s&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),s=new df(r.vertexShader,"vertex"),this.programs.vertex.set(r.vertexShader,s),t.createProgram(s));let a=this.programs.fragment.get(r.fragmentShader);void 0===a&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),a=new df(r.fragmentShader,"fragment"),this.programs.fragment.set(r.fragmentShader,a),t.createProgram(a));const o=this._getRenderCacheKey(e,s,a);let l=this.caches.get(o);void 0===l?(i&&0===i.usedTimes&&this._releasePipeline(i),l=this._getRenderPipeline(e,s,a,o)):e.pipeline=l,l.usedTimes++,s.usedTimes++,a.usedTimes++,n.pipeline=l}return n.pipeline}delete(e){const t=this.get(e).pipeline;t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return void 0===r&&(r=new uf(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,n,i){i=i||this._getRenderCacheKey(e,t,n);let r=this.caches.get(i);return void 0===r&&(r=new cf(i,t,n),this.caches.set(i,r),e.pipeline=r,this.backend.createRenderPipeline(e)),r}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_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 mf extends Km{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),n=this.get(e);return n.bindings!==t&&(n.bindings=t,this._init(t),this.backend.createBindings(t)),n.bindings}getForCompute(e){const t=this.get(e);if(void 0===t.bindings){const n=this.nodes.getForCompute(e).bindings.compute;t.bindings=n,this._init(n),this.backend.createBindings(n)}return t.bindings}updateForCompute(e){this._update(e,this.getForCompute(e))}updateForRender(e){this._update(e,this.getForRender(e))}_init(e){for(const t of e)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute;this.attributes.update(e,ef)}}_update(e,t){const{backend:n}=this;let i=!1;for(const e of t){if(e.isNodeUniformsGroup){if(!this.nodes.updateGroup(e))continue}if(e.isUniformBuffer){e.update()&&n.updateBinding(e)}else if(e.isSampledTexture){const t=e.texture;e.needsBindingsUpdate&&(i=!0);if(e.update()&&this.textures.updateTexture(e.texture),!0===t.isStorageTexture){const n=this.get(t);!0===e.store?n.needsMipmap=!0:!0===t.generateMipmaps&&this.textures.needsMipmaps(t)&&!0===n.needsMipmap&&(this.backend.generateMipmaps(t),n.needsMipmap=!1)}}}if(!0===i){const n=this.pipelines.getForRender(e);this.backend.updateBindings(t,n)}}}const ff={VERTEX:"vertex",FRAGMENT:"fragment"},gf={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},_f={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX3:"mat3",MATRIX4:"mat4"},vf=["fragment","vertex"],xf=["setup","analyze","generate"],yf=[...vf,"compute"],bf=["x","y","z","w"];function Sf(e){let t="{";!0===e.isNode&&(t+=e.id);for(const{property:n,childNode:i}of Tf(e))t+=","+n.slice(0,-4)+":"+i.getCacheKey();return t+="}",t}function*Tf(e,t=!1){for(const n in e){if(!0===n.startsWith("_"))continue;const i=e[n];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer}var Rf=Object.freeze({__proto__:null,getCacheKey:Sf,getNodeChildren:Tf,getValueType:Mf,getValueFromType:Ef,arrayBufferToBase64:Af,base64ToArrayBuffer:wf});const Cf=new Map;let Nf=0;class Lf extends Vn{constructor(e=null){super(),this.nodeType=e,this.updateType=gf.NONE,this.updateBeforeType=gf.NONE,this.uuid=Jn.generateUUID(),this.isNode=!0,Object.defineProperty(this,"id",{value:Nf++})}get type(){return this.constructor.type}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return!1}*getChildren(){for(const{childNode:e}of Tf(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(){return Sf(this)}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}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);for(const e of this.getChildren())t["_node"+e.id]=e;return null}construct(e){return this.setup(e)}analyze(e){const t=e.getDataFromNode(this);if(t.dependenciesCount=void 0===t.dependenciesCount?1:t.dependenciesCount+1,1===t.dependenciesCount){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){}update(){}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){const t=e.getNodeProperties(this);if(!0!==t.initialized||!1===e.context.tempRead){const n=e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length!==n&&(t.outputNode=e.stack);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e)}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const n=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i&&(i=this.generate(e)||"",r.snippet=i),i=e.format(i,n,t)}else i=this.generate(e,t)||""}return e.removeChain(this),i}getSerializeChildren(){return Tf(this)}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:r,childNode:s}of t)void 0!==r?(void 0===n[i]&&(n[i]=Number.isInteger(r)?[]:{}),n[i][r]=s.toJSON(e.meta).uuid):n[i]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}function Pf(e,t){if("function"!=typeof t||!e)throw new Error(`Node class ${e} is not a class`);Cf.has(e)||(Cf.set(e,t),t.type=e)}function If(e){const t=Cf.get(e);if(void 0!==t)return new t}class Uf extends Lf{constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?Mf(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Mf(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=Af(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Ef(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){}}Pf("InputNode",Uf);class Of extends Lf{constructor(e,t=!1){super("string"),this.name=e,this.version=0,this.shared=t,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}}const Df=e=>new Of(e),Ff=e=>new Of(e,!0),Bf=Ff("frame"),Vf=Ff("render"),zf=Df("object");Pf("UniformGroupNode",Of);class Gf extends Lf{constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getNodeType(e)}generate(e){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}Pf("ArrayElementNode",Gf);class kf extends Lf{constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}Pf("ConvertNode",kf);class Hf extends Lf{constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).dependenciesCount>1}build(e,t){if("generate"===e.getBuildStage()){const n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(!1!==e.context.tempRead&&void 0!==i.propertyName)return e.format(i.propertyName,n,t);if(!1!==e.context.tempWrite&&"void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}Pf("TempNode",Hf);class Wf extends Hf{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,n)=>t+e.getTypeLength(n.getNodeType(e))),0))}generate(e,t){const n=this.getNodeType(e),i=this.nodes,r=e.getPrimitiveType(n),s=[];for(const t of i){let n=t.build(e);const i=e.getPrimitiveType(t.getNodeType(e));i!==r&&(n=e.format(n,i,r)),s.push(n)}const a=`${e.getType(n)}( ${s.join(", ")} )`;return e.format(a,n,t)}}Pf("JoinNode",Wf);const Xf=bf.join("");class jf extends Lf{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(bf.indexOf(t)+1,e);return e}getPrimitiveType(e){return e.getPrimitiveType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getPrimitiveType(e))}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getPrimitiveType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===Xf.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}Pf("SplitNode",jf);class qf extends Hf{constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getTypeFromLength(n.length),a=i.build(e,s),o=t.build(e,r),l=e.getTypeLength(r),c=[];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"),Qf={setup(e,t){const n=t.shift();return e(Tg(n),...t)},get(e,t,n){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>($f.assign(n,...e),n);if(Zf.has(t)){const i=Zf.get(t);return e.isStackNode?(...e)=>n.add(i(...e)):(...e)=>i(n,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Zf.has(t.slice(0,t.length-6))){const i=Zf.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>n.assign(e[0],i(...e)):(...e)=>n.assign(i(n,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Jf(t),Sg(new jf(n,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=(t=Jf(t.slice(3).toLowerCase())).split("").sort().join(""),n=>Sg(new qf(e,t,n));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Sg(new jf(e,t));if(!0===/^\d+$/.test(t))return Sg(new Gf(n,new Yf(Number(t),"uint")))}return Reflect.get(e,t,n)},set:(e,t,n,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,n,i):(i[t].assign(n),!0)},eg=new WeakMap,tg=new WeakMap,ng=function(e,t=null){for(const n in e)e[n]=Sg(e[n],t);return e},ig=function(e,t=null){const n=e.length;for(let i=0;iSg(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Mg(t))):null!==n?(n=Sg(n),(...i)=>r(new e(t,...Mg(i),n))):(...n)=>r(new e(t,...Mg(n)))},sg=function(e,...t){return Sg(new e(...Mg(t)))};class ag extends Lf{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){const{outputNode:t}=e.getNodeProperties(this);return t?t.getNodeType(e):super.getNodeType(e)}call(e){const{shaderNode:t,inputNodes:n}=this;if(t.layout){let i=tg.get(e.constructor);void 0===i&&(i=new WeakMap,tg.set(e.constructor,i));let r=i.get(t);return void 0===r&&(r=Sg(e.buildFunctionNode(t)),i.set(t,r)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(r),Sg(r.call(n))}const i=t.jsFunc,r=null!==n?i(n,e.stack,e):i(e.stack,e);return Sg(r)}setup(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);return null===n?this.call(e).build(e,t):super.generate(e,t)}}class og extends Lf{constructor(e){super(),this.jsFunc=e,this.layout=null}get isArrayInput(){return/^\((\s+)?\[/.test(this.jsFunc.toString())}setLayout(e){return this.layout=e,this}call(e=null){return Tg(e),Sg(new ag(this,e))}setup(){return this.call()}}const lg=[!1,!0],cg=[0,1,2,3],ug=[-1,-2],hg=[.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],dg=new Map;for(const e of lg)dg.set(e,new Yf(e));const pg=new Map;for(const e of cg)pg.set(e,new Yf(e,"uint"));const mg=new Map([...pg].map((e=>new Yf(e.value,"int"))));for(const e of ug)mg.set(e,new Yf(e,"int"));const fg=new Map([...mg].map((e=>new Yf(e.value))));for(const e of hg)fg.set(e,new Yf(e));for(const e of hg)fg.set(-e,new Yf(-e));const gg={bool:dg,uint:pg,ints:mg,float:fg},_g=new Map([...dg,...fg]),vg=(e,t)=>_g.has(e)?_g.get(e):!0===e.isNode?e:new Yf(e,t),xg=function(e,t=null){return(...n)=>{if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every((e=>"object"!=typeof e)))&&(n=[Ef(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Sg(t.get(n[0]));if(1===n.length){const t=vg(n[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Sg(t):Sg(new kf(t,e))}const i=n.map((e=>vg(e)));return Sg(new Wf(i,e))}},yg=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function bg(e){return new Proxy(new og(e),Qf)}const Sg=(e,t=null)=>function(e,t=null){const n=Mf(e);if("node"===n){let t=eg.get(e);return void 0===t&&(t=new Proxy(e,Qf),eg.set(e,t),eg.set(t,t)),t}return null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Sg(vg(e,t)):"shader"===n?Rg(e):e}(e,t),Tg=(e,t=null)=>new ng(e,t),Mg=(e,t=null)=>new ig(e,t),Eg=(...e)=>new rg(...e),Ag=(...e)=>new sg(...e),wg=e=>new bg(e),Rg=e=>{const t=new bg(e),n=(...e)=>{let n;return Tg(e),n=e[0]&&e[0].isNode?[...e]:e[0],t.call(n)};return n.shaderNode=t,n.setLayout=e=>(t.setLayout(e),n),n};Pf("ShaderNode",bg);const Cg=e=>{$f=e},Ng=()=>$f,Lg=(...e)=>$f.if(...e);function Pg(e){return $f&&$f.add(e),e}Kf("append",Pg);const Ig=new xg("color"),Ug=new xg("float",gg.float),Og=new xg("int",gg.int),Dg=new xg("uint",gg.uint),Fg=new xg("bool",gg.bool),Bg=new xg("vec2"),Vg=new xg("ivec2"),zg=new xg("uvec2"),Gg=new xg("bvec2"),kg=new xg("vec3"),Hg=new xg("ivec3"),Wg=new xg("uvec3"),Xg=new xg("bvec3"),jg=new xg("vec4"),qg=new xg("ivec4"),Yg=new xg("uvec4"),$g=new xg("bvec4"),Zg=new xg("mat3"),Kg=new xg("imat3"),Jg=new xg("umat3"),Qg=new xg("bmat3"),e_=new xg("mat4"),t_=new xg("imat4"),n_=new xg("umat4"),i_=new xg("bmat4"),r_=(e="")=>Sg(new Yf(e,"string")),s_=e=>Sg(new Yf(e,"ArrayBuffer"));Kf("color",Ig),Kf("float",Ug),Kf("int",Og),Kf("uint",Dg),Kf("bool",Fg),Kf("vec2",Bg),Kf("ivec2",Vg),Kf("uvec2",zg),Kf("bvec2",Gg),Kf("vec3",kg),Kf("ivec3",Hg),Kf("uvec3",Wg),Kf("bvec3",Xg),Kf("vec4",jg),Kf("ivec4",qg),Kf("uvec4",Yg),Kf("bvec4",$g),Kf("mat3",Zg),Kf("imat3",Kg),Kf("umat3",Jg),Kf("bmat3",Qg),Kf("mat4",e_),Kf("imat4",t_),Kf("umat4",n_),Kf("bmat4",i_),Kf("string",r_),Kf("arrayBuffer",s_);const a_=Eg(Gf),o_=(e,t)=>Sg(new kf(Sg(e),t)),l_=(e,t)=>Sg(new jf(Sg(e),t));Kf("element",a_),Kf("convert",o_);class c_ extends Uf{constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.groupNode=zf}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const s=r.getInputType(e),a=e.getUniformFromNode(r,s,e.shaderStage,e.context.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,n,t)}}const u_=(e,t)=>{const n=yg(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Sg(new c_(i,n))};Pf("UniformNode",c_);class h_ extends c_{constructor(e=[]){super(),this.isArrayUniformNode=!0,this.nodes=e}getNodeType(e){return this.nodes[0].getNodeType(e)}}Pf("ArrayUniformNode",h_);class d_ extends Hf{constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}generate(e,t){const n=this.targetNode,i=this.sourceNode,r=n.getNodeType(e),s=n.build(e),a=`${s} = ${i.build(e,r)}`;if("void"!==t){return"void"===i.getNodeType(e)?(e.addLineFlowCode(a),s):e.format(a,r,t)}e.addLineFlowCode(a)}}const p_=Eg(d_);Pf("AssignNode",d_),Kf("assign",p_);class m_ extends Lf{constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{name:t,node:n}=this,i=this.getNodeType(e),r=e.getVaryingFromNode(this,t,i);r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage);const s=e.getPropertyName(r,ff.VERTEX);return e.flowNodeFromShaderStage(ff.VERTEX,n,i,s),e.getPropertyName(r)}}const f_=Eg(m_);Kf("varying",f_),Pf("VaryingNode",m_);class g_ extends Lf{constructor(e,t=null){super(t),this._attributeName=e}isGlobal(){return!0}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=super.getNodeType(e);if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,n);return f_(this).build(e,n)}return e.generateConst(n)}}const __=(e,t)=>Sg(new g_(e,t));Pf("AttributeNode",g_);class v_ extends Lf{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.outputNode.build(e)}}const x_=Eg(v_);Kf("bypass",x_),Pf("BypassNode",v_);let y_=0;class b_{constructor(){this.id=y_++,this.nodesData=new WeakMap}getNodeData(e){return this.nodesData.get(e)}setNodeData(e,t){this.nodesData.set(e,t)}}class S_ extends Lf{constructor(e,t=new b_){super(),this.isCacheNode=!0,this.node=e,this.cache=t}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const n=e.getCache(),i=this.cache||e.globalCache;e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}}const T_=Eg(S_);Kf("cache",T_),Kf("globalCache",(e=>T_(e,null))),Pf("CacheNode",S_);class M_ extends Lf{constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.context=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.context});const n=this.node.build(e);return e.setContext(t),n}generate(e,t){const n=e.getContext();e.setContext({...e.context,...this.context});const i=this.node.build(e,t);return e.setContext(n),i}}const E_=Eg(M_),A_=(e,t)=>E_(e,{label:t});Kf("context",E_),Kf("label",A_),Pf("ContextNode",M_);class w_ extends Lf{constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===w_.VERTEX)i=e.getVertexIndex();else{if(n!==w_.INSTANCE)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getInstanceIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=f_(this).build(e,t)}return r}}w_.VERTEX="vertex",w_.INSTANCE="instance";const R_=Ag(w_,w_.VERTEX),C_=Ag(w_,w_.INSTANCE);Pf("IndexNode",w_);class N_{start(){}finish(){}direct(){}indirectDiffuse(){}indirectSpecular(){}ambientOcclusion(){}}class L_ extends Lf{constructor(e,t=null){super(),this.node=e,this.name=t,this.isVarNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:n}=this,i=e.getVarFromNode(this,n,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),s=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${s}`),r}}const P_=Eg(L_);Kf("temp",P_),Kf("toVar",((...e)=>P_(...e).append())),Pf("VarNode",L_);class I_{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class U_{constructor(e,t,n,i=void 0){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n.getSelf(),this.needsUpdate=i}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 O_{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class D_ extends O_{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class F_{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}class B_{constructor(){this.keywords=[],this.nodes=[],this.keywordsCallback={}}getNode(e){let t=this.nodes[e];return void 0===t&&void 0!==this.keywordsCallback[e]&&(t=this.keywordsCallback[e](e),this.nodes[e]=t),t}addKeyword(e,t){return this.keywords.push(e),this.keywordsCallback[e]=t,this}parse(e){const t=this.keywords,n=new RegExp(`\\b${t.join("\\b|\\b")}\\b`,"g"),i=e.match(n),r=[];if(null!==i)for(const e of i){const t=this.getNode(e);void 0!==t&&-1===r.indexOf(t)&&r.push(t)}return r}include(e,t){const n=this.parse(t);for(const t of n)t.build(e)}}class V_ extends Lf{constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const z_=(e,t)=>Sg(new V_(e,t)),G_=(e,t)=>Sg(new V_(e,t,!0)),k_=Ag(V_,"vec4","DiffuseColor"),H_=Ag(V_,"float","Roughness"),W_=Ag(V_,"float","Metalness"),X_=Ag(V_,"float","Clearcoat"),j_=Ag(V_,"float","ClearcoatRoughness"),q_=Ag(V_,"vec3","Sheen"),Y_=Ag(V_,"float","SheenRoughness"),$_=Ag(V_,"float","Iridescence"),Z_=Ag(V_,"float","IridescenceIOR"),K_=Ag(V_,"float","IridescenceThickness"),J_=Ag(V_,"color","SpecularColor"),Q_=Ag(V_,"float","Shininess"),ev=Ag(V_,"vec4","Output"),tv=Ag(V_,"float","dashSize"),nv=Ag(V_,"float","gapSize"),iv=Ag(V_,"float","pointWidth");Pf("PropertyNode",V_);class rv extends V_{constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const sv=(e,t)=>Sg(new rv(e,t));Pf("ParameterNode",rv);class av extends Lf{constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=n,this.includes=t}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const ov=Eg(av),lv=(e,t)=>ov(e,t,"js"),cv=(e,t)=>ov(e,t,"wgsl"),uv=(e,t)=>ov(e,t,"glsl");Pf("CodeNode",av);class hv extends av{constructor(e="",t=[],n=""){super(e,t,n),this.keywords={}}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);""!==i&&(s.name=i);const a=e.getPropertyName(s);let o=this.getNodeFunction(e).getCode(a);const l=this.keywords,c=Object.keys(l);if(c.length>0)for(const t of c){const n=new RegExp(`\\b${t}\\b`,"g"),i=l[t].build(e,"property");o=o.replace(n,i)}return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}const dv=(e,t=[],n="")=>{for(let e=0;ei.call(...e);return r.functionNode=i,r},pv=(e,t)=>dv(e,t,"glsl"),mv=(e,t)=>dv(e,t,"wgsl");Pf("FunctionNode",hv);class fv extends g_{constructor(e=0){super(null,"vec2"),this.isUVNode=!0,this.index=e}getAttributeName(){const e=this.index;return"uv"+(e>0?e:"")}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const gv=(...e)=>Sg(new fv(...e));Pf("UVNode",fv);class _v extends Lf{constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),i=this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const vv=Eg(_v);Kf("textureSize",vv),Pf("TextureSizeNode",_v);class xv extends Hf{constructor(e,t,n,...i){if(super(),this.op=e,i.length>0){let t=n;for(let n=0;n>"===n||"<<"===n)return e.getIntegerType(s);if("=="===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("<"===n||">"===n||"<="===n||">="===n){const n=t?e.getTypeLength(t):Math.max(e.getTypeLength(s),e.getTypeLength(a));return n>1?`bvec${n}`:"bool"}return"float"===s&&e.isMatrix(a)?a:e.isMatrix(s)&&e.isVector(a)?e.getVectorFromMatrix(s):e.isVector(s)&&e.isMatrix(a)?e.getVectorFromMatrix(a):e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,i=this.aNode,r=this.bNode,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=r.getNodeType(e),"<"===n||">"===n||"<="===n||">="===n||"=="===n?e.isVector(a)?o=a:a=o="float":">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):e.isMatrix(a)&&e.isVector(o)?o=e.getVectorFromMatrix(a):a=e.isVector(a)&&e.isMatrix(o)?e.getVectorFromMatrix(o):o=s):a=o=s;const l=i.build(e,a),c=r.build(e,o),u=e.getTypeLength(t),h=e.getFunctionOperator(n);return"void"!==t?"<"===n&&u>1?e.format(`${e.getMethod("lessThan")}( ${l}, ${c} )`,s,t):"<="===n&&u>1?e.format(`${e.getMethod("lessThanEqual")}( ${l}, ${c} )`,s,t):">"===n&&u>1?e.format(`${e.getMethod("greaterThan")}( ${l}, ${c} )`,s,t):">="===n&&u>1?e.format(`${e.getMethod("greaterThanEqual")}( ${l}, ${c} )`,s,t):h?e.format(`${h}( ${l}, ${c} )`,s,t):e.format(`( ${l} ${n} ${c} )`,s,t):"void"!==a?h?e.format(`${h}( ${l}, ${c} )`,s,t):e.format(`${l} ${n} ${c}`,s,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const yv=Eg(xv,"+"),bv=Eg(xv,"-"),Sv=Eg(xv,"*"),Tv=Eg(xv,"/"),Mv=Eg(xv,"%"),Ev=Eg(xv,"=="),Av=Eg(xv,"!="),wv=Eg(xv,"<"),Rv=Eg(xv,">"),Cv=Eg(xv,"<="),Nv=Eg(xv,">="),Lv=Eg(xv,"&&"),Pv=Eg(xv,"||"),Iv=Eg(xv,"^^"),Uv=Eg(xv,"&"),Ov=Eg(xv,"|"),Dv=Eg(xv,"^"),Fv=Eg(xv,"<<"),Bv=Eg(xv,">>");Kf("add",yv),Kf("sub",bv),Kf("mul",Sv),Kf("div",Tv),Kf("remainder",Mv),Kf("equal",Ev),Kf("notEqual",Av),Kf("lessThan",wv),Kf("greaterThan",Rv),Kf("lessThanEqual",Cv),Kf("greaterThanEqual",Nv),Kf("and",Lv),Kf("or",Pv),Kf("xor",Iv),Kf("bitAnd",Uv),Kf("bitOr",Ov),Kf("bitXor",Dv),Kf("shiftLeft",Fv),Kf("shiftRight",Bv),Pf("OperatorNode",xv);class Vv extends Hf{constructor(e,t,n=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=n,this.cNode=i}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>s&&r>a?t:s>a?n:a>r?i:t}getNodeType(e){const t=this.method;return t===Vv.LENGTH||t===Vv.DISTANCE||t===Vv.DOT?"float":t===Vv.CROSS?"vec3":t===Vv.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const n=this.method,i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=!0===e.renderer.isWebGLRenderer;if(n===Vv.TRANSFORM_DIRECTION){let n=s,i=a;e.isMatrix(n.getNodeType(e))?i=jg(kg(i),0):n=jg(kg(n),0);const r=Sv(n,i).xyz;return Jv(r).build(e,t)}if(n===Vv.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);if(n===Vv.ONE_MINUS)return bv(1,s).build(e,t);if(n===Vv.RECIPROCAL)return Tv(1,s).build(e,t);if(n===Vv.DIFFERENCE)return ax(bv(s,a)).build(e,t);{const c=[];return n===Vv.CROSS||n===Vv.MOD?c.push(s.build(e,i),a.build(e,i)):n===Vv.STEP?c.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l&&(n===Vv.MIN||n===Vv.MAX)||n===Vv.MOD?c.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):n===Vv.REFRACT?c.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===Vv.MIX?c.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(c.push(s.build(e,r)),null!==a&&c.push(a.build(e,r)),null!==o&&c.push(o.build(e,r))),e.format(`${e.getMethod(n,i)}( ${c.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Vv.RADIANS="radians",Vv.DEGREES="degrees",Vv.EXP="exp",Vv.EXP2="exp2",Vv.LOG="log",Vv.LOG2="log2",Vv.SQRT="sqrt",Vv.INVERSE_SQRT="inversesqrt",Vv.FLOOR="floor",Vv.CEIL="ceil",Vv.NORMALIZE="normalize",Vv.FRACT="fract",Vv.SIN="sin",Vv.COS="cos",Vv.TAN="tan",Vv.ASIN="asin",Vv.ACOS="acos",Vv.ATAN="atan",Vv.ABS="abs",Vv.SIGN="sign",Vv.LENGTH="length",Vv.NEGATE="negate",Vv.ONE_MINUS="oneMinus",Vv.DFDX="dFdx",Vv.DFDY="dFdy",Vv.ROUND="round",Vv.RECIPROCAL="reciprocal",Vv.TRUNC="trunc",Vv.FWIDTH="fwidth",Vv.BITCAST="bitcast",Vv.ATAN2="atan2",Vv.MIN="min",Vv.MAX="max",Vv.MOD="mod",Vv.STEP="step",Vv.REFLECT="reflect",Vv.DISTANCE="distance",Vv.DIFFERENCE="difference",Vv.DOT="dot",Vv.CROSS="cross",Vv.POW="pow",Vv.TRANSFORM_DIRECTION="transformDirection",Vv.MIX="mix",Vv.CLAMP="clamp",Vv.REFRACT="refract",Vv.SMOOTHSTEP="smoothstep",Vv.FACEFORWARD="faceforward";const zv=Ug(1e-6),Gv=Ug(1e6),kv=Eg(Vv,Vv.RADIANS),Hv=Eg(Vv,Vv.DEGREES),Wv=Eg(Vv,Vv.EXP),Xv=Eg(Vv,Vv.EXP2),jv=Eg(Vv,Vv.LOG),qv=Eg(Vv,Vv.LOG2),Yv=Eg(Vv,Vv.SQRT),$v=Eg(Vv,Vv.INVERSE_SQRT),Zv=Eg(Vv,Vv.FLOOR),Kv=Eg(Vv,Vv.CEIL),Jv=Eg(Vv,Vv.NORMALIZE),Qv=Eg(Vv,Vv.FRACT),ex=Eg(Vv,Vv.SIN),tx=Eg(Vv,Vv.COS),nx=Eg(Vv,Vv.TAN),ix=Eg(Vv,Vv.ASIN),rx=Eg(Vv,Vv.ACOS),sx=Eg(Vv,Vv.ATAN),ax=Eg(Vv,Vv.ABS),ox=Eg(Vv,Vv.SIGN),lx=Eg(Vv,Vv.LENGTH),cx=Eg(Vv,Vv.NEGATE),ux=Eg(Vv,Vv.ONE_MINUS),hx=Eg(Vv,Vv.DFDX),dx=Eg(Vv,Vv.DFDY),px=Eg(Vv,Vv.ROUND),mx=Eg(Vv,Vv.RECIPROCAL),fx=Eg(Vv,Vv.TRUNC),gx=Eg(Vv,Vv.FWIDTH),_x=Eg(Vv,Vv.BITCAST),vx=Eg(Vv,Vv.ATAN2),xx=Eg(Vv,Vv.MIN),yx=Eg(Vv,Vv.MAX),bx=Eg(Vv,Vv.MOD),Sx=Eg(Vv,Vv.STEP),Tx=Eg(Vv,Vv.REFLECT),Mx=Eg(Vv,Vv.DISTANCE),Ex=Eg(Vv,Vv.DIFFERENCE),Ax=Eg(Vv,Vv.DOT),wx=Eg(Vv,Vv.CROSS),Rx=Eg(Vv,Vv.POW),Cx=Eg(Vv,Vv.POW,2),Nx=Eg(Vv,Vv.POW,3),Lx=Eg(Vv,Vv.POW,4),Px=Eg(Vv,Vv.TRANSFORM_DIRECTION),Ix=e=>Sv(ox(e),Rx(ax(e),1/3)),Ux=Eg(Vv,Vv.MIX),Ox=(e,t=0,n=1)=>Sg(new Vv(Vv.CLAMP,Sg(e),Sg(t),Sg(n))),Dx=e=>Ox(e),Fx=Eg(Vv,Vv.REFRACT),Bx=Eg(Vv,Vv.SMOOTHSTEP),Vx=Eg(Vv,Vv.FACEFORWARD);Kf("radians",kv),Kf("degrees",Hv),Kf("exp",Wv),Kf("exp2",Xv),Kf("log",jv),Kf("log2",qv),Kf("sqrt",Yv),Kf("inverseSqrt",$v),Kf("floor",Zv),Kf("ceil",Kv),Kf("normalize",Jv),Kf("fract",Qv),Kf("sin",ex),Kf("cos",tx),Kf("tan",nx),Kf("asin",ix),Kf("acos",rx),Kf("atan",sx),Kf("abs",ax),Kf("sign",ox),Kf("length",lx),Kf("negate",cx),Kf("oneMinus",ux),Kf("dFdx",hx),Kf("dFdy",dx),Kf("round",px),Kf("reciprocal",mx),Kf("trunc",fx),Kf("fwidth",gx),Kf("atan2",vx),Kf("min",xx),Kf("max",yx),Kf("mod",bx),Kf("step",Sx),Kf("reflect",Tx),Kf("distance",Mx),Kf("dot",Ax),Kf("cross",wx),Kf("pow",Rx),Kf("pow2",Cx),Kf("pow3",Nx),Kf("pow4",Lx),Kf("transformDirection",Px),Kf("mix",((e,t,n)=>Ux(t,n,e))),Kf("clamp",Ox),Kf("refract",Fx),Kf("smoothstep",((e,t,n)=>Bx(t,n,e))),Kf("faceForward",Vx),Kf("difference",Ex),Kf("saturate",Dx),Kf("cbrt",Ix),Pf("MathNode",Vv);const zx=Rg((e=>{const{value:t}=e,{rgb:n}=t,i=n.mul(.9478672986).add(.0521327014).pow(2.4),r=n.mul(.0773993808),s=n.lessThanEqual(.04045),a=Ux(i,r,s);return jg(a,t.a)})),Gx=Rg((e=>{const{value:t}=e,{rgb:n}=t,i=n.pow(.41666).mul(1.055).sub(.055),r=n.mul(12.92),s=n.lessThanEqual(.0031308),a=Ux(i,r,s);return jg(a,t.a)})),kx=e=>{let t=null;return e===qt?t="Linear":e===jt&&(t="sRGB"),t},Hx=(e,t)=>kx(e)+"To"+kx(t);class Wx extends Hf{constructor(e,t){super("vec4"),this.method=e,this.node=t}setup(){const{method:e,node:t}=this;return e===Wx.LINEAR_TO_LINEAR?t:Xx[e]({value:t})}}Wx.LINEAR_TO_LINEAR="LinearToLinear",Wx.LINEAR_TO_sRGB="LinearTosRGB",Wx.sRGB_TO_LINEAR="sRGBToLinear";const Xx={[Wx.LINEAR_TO_sRGB]:Gx,[Wx.sRGB_TO_LINEAR]:zx},jx=(e,t)=>Sg(new Wx(Hx(qt,t),Sg(e))),qx=(e,t)=>Sg(new Wx(Hx(t,qt),Sg(e))),Yx=Eg(Wx,Wx.LINEAR_TO_sRGB),$x=Eg(Wx,Wx.sRGB_TO_LINEAR);Kf("linearTosRGB",Yx),Kf("sRGBToLinear",$x),Kf("linearToColorSpace",jx),Kf("colorSpaceToLinear",qx),Pf("ColorSpaceNode",Wx);class Zx extends Lf{constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(`( ${i} )`,n,t);e.addLineFlowCode(i)}}const Kx=Eg(Zx);Pf("ExpressionNode",Zx);class Jx extends c_{constructor(e){super(0),this.textureNode=e,this.updateType=gf.FRAME}get texture(){return this.textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Qx=Eg(Jx);Pf("MaxMipLevelNode",Jx);class ey extends c_{constructor(e,t=null,n=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.compareNode=null,this.depthNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=gf.NONE,this.setUpdateMatrix(null===t)}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":"vec4"}getInputType(){return"texture"}getDefaultUV(){return gv(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){const t=this.value;return u_(t.matrix).mul(kg(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?gf.FRAME:gf.NONE,this}setupUV(e,t){const n=this.value;return!e.isFlipY()||!0!==n.isRenderTargetTexture&&!0!==n.isFramebufferTexture&&!0!==n.isDepthTexture||(t=t.setY(t.y.oneMinus())),t}setup(e){const t=e.getNodeProperties(this);let n=this.uvNode;null!==n&&!0!==e.context.forceUVContext||!e.context.getUV||(n=e.context.getUV(this)),n||(n=this.getDefaultUV()),!0===this.updateMatrix&&(n=this.getTransformedUV(n)),n=this.setupUV(e,n);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),null!==i&&void 0!==e.context.getTextureLevelAlgorithm&&(i=e.context.getTextureLevelAlgorithm(this,i)),t.uvNode=n,t.levelNode=i,t.compareNode=this.compareNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,n,i,r,s){const a=this.value;let o;return o=i?e.generateTextureLevel(a,t,n,i,r):s?e.generateTextureCompare(a,t,n,s,r):!1===this.sampler?e.generateTextureLoad(a,t,n,r):e.generateTexture(a,t,n,r),o}generate(e,t){const n=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this);let a=s.propertyName;if(void 0===a){const{uvNode:t,levelNode:i,compareNode:o,depthNode:l}=n,c=this.generateUV(e,t),u=i?i.build(e,"float"):null,h=l?l.build(e,"int"):null,d=o?o.build(e,"float"):null,p=e.getVarFromNode(this);a=e.getPropertyName(p);const m=this.generateSnippet(e,r,c,u,h,d);e.addLineFlowCode(`${a} = ${m}`),!1!==e.context.tempWrite&&(s.snippet=m,s.propertyName=a)}let o=a;const l=this.getNodeType(e);return e.needsColorSpaceToLinear(i)&&(o=qx(Kx(o,l),i.colorSpace).setup(e).build(e,l)),e.format(o,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=e,Sg(t)}blur(e){const t=this.clone();return t.levelNode=e.mul(Qx(t)),Sg(t)}level(e){const t=this.clone();return t.levelNode=e,t}size(e){return vv(this,e)}compare(e){const t=this.clone();return t.compareNode=Sg(e),Sg(t)}depth(e){const t=this.clone();return t.depthNode=Sg(e),Sg(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value]}update(){const e=this.value;!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e}}const ty=Eg(ey),ny=(...e)=>ty(...e).setSampler(!1),iy=e=>(!0===e.isNode?e:ty(e)).convert("sampler");Kf("texture",ty),Pf("TextureNode",ey);class ry extends Lf{constructor(e,t,n=null){super(),this.property=e,this.index=null,this.uniformType=t,this.object=n,this.reference=null,this.node=null,this.updateType=gf.OBJECT,this.setNodeType(t)}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setIndex(e){return this.index=e,this}getIndex(){return this.index}setNodeType(e){let t=null;t="texture"===e?ty(null):u_(e),this.node=t}getNodeType(e){return this.node.getNodeType(e)}update(){let e=this.reference[this.property];null!==this.index&&(e=e[this.index]),this.node.value=e}setup(){return this.node}}const sy=(e,t,n)=>Sg(new ry(e,t,n)),ay=(e,t,n,i)=>Sg(new ry(e,n,i).setIndex(t));Pf("ReferenceNode",ry);class oy extends ry{constructor(e,t,n=null){super(e,t,n),this.material=n}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}setup(e){const t=null!==this.material?this.material:e.material;return this.node.value=t[this.property],super.setup(e)}}const ly=(e,t,n)=>Sg(new oy(e,t,n));Pf("MaterialReferenceNode",oy);class cy extends Lf{constructor(e=cy.VIEW_MATRIX,t=null){super(),this.scope=e,this.object3d=t,this.updateType=gf.OBJECT,this._uniformNode=new c_(null)}getNodeType(){const e=this.scope;return e===cy.WORLD_MATRIX||e===cy.VIEW_MATRIX?"mat4":e===cy.NORMAL_MATRIX?"mat3":e===cy.POSITION||e===cy.VIEW_POSITION||e===cy.DIRECTION||e===cy.SCALE?"vec3":void 0}update(e){const t=this.object3d,n=this._uniformNode,i=this.scope;if(i===cy.VIEW_MATRIX)n.value=t.modelViewMatrix;else if(i===cy.NORMAL_MATRIX)n.value=t.normalMatrix;else if(i===cy.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===cy.POSITION)n.value=n.value||new Pi,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===cy.SCALE)n.value=n.value||new Pi,n.value.setFromMatrixScale(t.matrixWorld);else if(i===cy.DIRECTION)n.value=n.value||new Pi,t.getWorldDirection(n.value);else if(i===cy.VIEW_POSITION){const i=e.camera;n.value=n.value||new Pi,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===cy.WORLD_MATRIX||t===cy.VIEW_MATRIX?this._uniformNode.nodeType="mat4":t===cy.NORMAL_MATRIX?this._uniformNode.nodeType="mat3":t!==cy.POSITION&&t!==cy.VIEW_POSITION&&t!==cy.DIRECTION&&t!==cy.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}cy.VIEW_MATRIX="viewMatrix",cy.NORMAL_MATRIX="normalMatrix",cy.WORLD_MATRIX="worldMatrix",cy.POSITION="position",cy.SCALE="scale",cy.VIEW_POSITION="viewPosition",cy.DIRECTION="direction";const uy=Eg(cy,cy.DIRECTION),hy=Eg(cy,cy.VIEW_MATRIX),dy=Eg(cy,cy.NORMAL_MATRIX),py=Eg(cy,cy.WORLD_MATRIX),my=Eg(cy,cy.POSITION),fy=Eg(cy,cy.SCALE),gy=Eg(cy,cy.VIEW_POSITION);Pf("Object3DNode",cy);class _y extends cy{constructor(e=_y.POSITION){super(e),this.updateType=gf.RENDER}getNodeType(e){const t=this.scope;return t===_y.PROJECTION_MATRIX?"mat4":t===_y.NEAR||t===_y.FAR||t===_y.LOG_DEPTH?"float":super.getNodeType(e)}update(e){const t=e.camera,n=this._uniformNode,i=this.scope;i===_y.VIEW_MATRIX?n.value=t.matrixWorldInverse:i===_y.PROJECTION_MATRIX?n.value=t.projectionMatrix:i===_y.NEAR?n.value=t.near:i===_y.FAR?n.value=t.far:i===_y.LOG_DEPTH?n.value=2/(Math.log(t.far+1)/Math.LN2):(this.object3d=t,super.update(e))}generate(e){const t=this.scope;return t===_y.PROJECTION_MATRIX?this._uniformNode.nodeType="mat4":t!==_y.NEAR&&t!==_y.FAR&&t!==_y.LOG_DEPTH||(this._uniformNode.nodeType="float"),super.generate(e)}}_y.PROJECTION_MATRIX="projectionMatrix",_y.NEAR="near",_y.FAR="far",_y.LOG_DEPTH="logDepth";const vy=A_(Ag(_y,_y.PROJECTION_MATRIX),"projectionMatrix"),xy=Ag(_y,_y.NEAR),yy=Ag(_y,_y.FAR),by=Ag(_y,_y.LOG_DEPTH),Sy=Ag(_y,_y.VIEW_MATRIX),Ty=Ag(_y,_y.NORMAL_MATRIX),My=Ag(_y,_y.WORLD_MATRIX),Ey=Ag(_y,_y.POSITION);Pf("CameraNode",_y);class Ay extends cy{constructor(e=Ay.VIEW_MATRIX){super(e)}update(e){this.object3d=e.object,super.update(e)}}const wy=Ag(Ay,Ay.DIRECTION),Ry=Ag(Ay,Ay.VIEW_MATRIX).label("modelViewMatrix").temp("ModelViewMatrix"),Cy=Ag(Ay,Ay.NORMAL_MATRIX),Ny=Ag(Ay,Ay.WORLD_MATRIX),Ly=Ag(Ay,Ay.POSITION),Py=Ag(Ay,Ay.SCALE),Iy=Ag(Ay,Ay.VIEW_POSITION);Pf("ModelNode",Ay);class Uy extends Lf{constructor(e=Uy.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`normal-${this.scope}`}generate(e){const t=this.scope;let n=null;if(t===Uy.GEOMETRY)n=__("normal","vec3");else if(t===Uy.LOCAL)n=f_(Oy);else if(t===Uy.VIEW){const e=Cy.mul(Dy);n=Jv(f_(e))}else if(t===Uy.WORLD){const e=Fy.transformDirection(Sy);n=Jv(f_(e))}return n.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Uy.GEOMETRY="geometry",Uy.LOCAL="local",Uy.VIEW="view",Uy.WORLD="world";const Oy=Ag(Uy,Uy.GEOMETRY),Dy=Ag(Uy,Uy.LOCAL).temp("Normal"),Fy=Ag(Uy,Uy.VIEW),By=Ag(Uy,Uy.WORLD),Vy=z_("vec3","TransformedNormalView"),zy=Vy.transformDirection(Sy).normalize(),Gy=z_("vec3","TransformedClearcoatNormalView");Pf("NormalNode",Uy);const ky=new Map;class Hy extends Lf{constructor(e){super(),this.scope=e}getCache(e,t){let n=ky.get(e);return void 0===n&&(n=ly(e,t),ky.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===Hy.COLOR){const e=this.getColor(n);i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===Hy.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===Hy.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture(n).r:Ug(1);else if(n===Hy.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===Hy.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===Hy.EMISSIVE){const e=this.getColor(n);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?e.mul(this.getTexture(n)):e}else if(n===Hy.NORMAL)i=t.normalMap?this.getTexture("normal").normalMap(this.getCache("normalScale","vec2")):t.bumpMap?this.getTexture("bump").r.bumpMap(this.getFloat("bumpScale")):Fy;else if(n===Hy.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Hy.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Hy.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?this.getTexture(n).normalMap(this.getCache(n+"Scale","vec2")):Fy;else if(n===Hy.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===Hy.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(.07,1)}else if(n===Hy.IRIDESCENCE_THICKNESS){const e=sy(1,"float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=sy(0,"float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}Hy.ALPHA_TEST="alphaTest",Hy.COLOR="color",Hy.OPACITY="opacity",Hy.SHININESS="shininess",Hy.SPECULAR_COLOR="specular",Hy.SPECULAR_STRENGTH="specularStrength",Hy.REFLECTIVITY="reflectivity",Hy.ROUGHNESS="roughness",Hy.METALNESS="metalness",Hy.NORMAL="normal",Hy.CLEARCOAT="clearcoat",Hy.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Hy.CLEARCOAT_NORMAL="clearcoatNormal",Hy.EMISSIVE="emissive",Hy.ROTATION="rotation",Hy.SHEEN="sheen",Hy.SHEEN_ROUGHNESS="sheenRoughness",Hy.IRIDESCENCE="iridescence",Hy.IRIDESCENCE_IOR="iridescenceIOR",Hy.IRIDESCENCE_THICKNESS="iridescenceThickness",Hy.LINE_SCALE="scale",Hy.LINE_DASH_SIZE="dashSize",Hy.LINE_GAP_SIZE="gapSize",Hy.LINE_WIDTH="linewidth",Hy.LINE_DASH_OFFSET="dashOffset",Hy.POINT_WIDTH="pointWidth";const Wy=Ag(Hy,Hy.ALPHA_TEST),Xy=Ag(Hy,Hy.COLOR),jy=Ag(Hy,Hy.SHININESS),qy=Ag(Hy,Hy.EMISSIVE),Yy=Ag(Hy,Hy.OPACITY),$y=Ag(Hy,Hy.SPECULAR_COLOR),Zy=Ag(Hy,Hy.SPECULAR_STRENGTH),Ky=Ag(Hy,Hy.REFLECTIVITY),Jy=Ag(Hy,Hy.ROUGHNESS),Qy=Ag(Hy,Hy.METALNESS),eb=Ag(Hy,Hy.NORMAL),tb=Ag(Hy,Hy.CLEARCOAT),nb=Ag(Hy,Hy.CLEARCOAT_ROUGHNESS),ib=Ag(Hy,Hy.CLEARCOAT_NORMAL),rb=Ag(Hy,Hy.ROTATION),sb=Ag(Hy,Hy.SHEEN),ab=Ag(Hy,Hy.SHEEN_ROUGHNESS),ob=Ag(Hy,Hy.IRIDESCENCE),lb=Ag(Hy,Hy.IRIDESCENCE_IOR),cb=Ag(Hy,Hy.IRIDESCENCE_THICKNESS),ub=Ag(Hy,Hy.LINE_SCALE),hb=Ag(Hy,Hy.LINE_DASH_SIZE),db=Ag(Hy,Hy.LINE_GAP_SIZE),pb=Ag(Hy,Hy.LINE_WIDTH),mb=Ag(Hy,Hy.LINE_DASH_OFFSET),fb=Ag(Hy,Hy.POINT_WIDTH);Pf("MaterialNode",Hy);class gb extends Lf{constructor(e=gb.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`position-${this.scope}`}generate(e){const t=this.scope;let n=null;if(t===gb.GEOMETRY)n=__("position","vec3");else if(t===gb.LOCAL)n=f_(_b);else if(t===gb.WORLD){const e=Ny.mul(vb);n=f_(e)}else if(t===gb.VIEW){const e=Ry.mul(vb);n=f_(e)}else if(t===gb.VIEW_DIRECTION){const e=bb.negate();n=Jv(f_(e))}else if(t===gb.WORLD_DIRECTION){const e=vb.transformDirection(Ny);n=Jv(f_(e))}return n.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}gb.GEOMETRY="geometry",gb.LOCAL="local",gb.WORLD="world",gb.WORLD_DIRECTION="worldDirection",gb.VIEW="view",gb.VIEW_DIRECTION="viewDirection";const _b=Ag(gb,gb.GEOMETRY),vb=Ag(gb,gb.LOCAL).temp("Position"),xb=Ag(gb,gb.WORLD),yb=Ag(gb,gb.WORLD_DIRECTION),bb=Ag(gb,gb.VIEW),Sb=Ag(gb,gb.VIEW_DIRECTION);Pf("PositionNode",gb);class Tb extends Hf{constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return f_(e.context.mvp);const t=this.positionNode||vb;return vy.mul(Ry).mul(t)}}const Mb=Eg(Tb);Pf("ModelViewProjectionNode",Tb);class Eb extends Uf{constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=En,this.instanced=!1,this.attribute=null,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}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),n=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,s=this.bufferOffset,a=!0===n.isInterleavedBuffer?n:new Ql(n,r),o=new tc(a,i,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let r=null;if("vertex"===e.shaderStage)r=i;else{r=f_(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this}setInstanced(e){return this.instanced=e,this}}const Ab=(e,t,n,i)=>Sg(new Eb(e,t,n,i)),wb=(e,t,n,i)=>Ab(e,t,n,i).setUsage(An),Rb=(e,t,n,i)=>Ab(e,t,n,i).setInstanced(!0),Cb=(e,t,n,i)=>wb(e,t,n,i).setInstanced(!0);Kf("toAttribute",(e=>Ab(e.value))),Pf("BufferAttributeNode",Eb);class Nb extends Lf{constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null}setup(){let e=this.instanceMatrixNode;if(null===e){const t=this.instanceMesh.instanceMatrix,n=new em(t.array,16,1),i=t.usage===An?Cb:Rb,r=[i(n,"vec4",16,0),i(n,"vec4",16,4),i(n,"vec4",16,8),i(n,"vec4",16,12)];e=e_(...r),this.instanceMatrixNode=e}const t=e.mul(vb).xyz,n=Zg(e[0].xyz,e[1].xyz,e[2].xyz),i=Dy.div(kg(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2]))),r=n.mul(i).xyz;vb.assign(t),Dy.assign(r)}}const Lb=Eg(Nb);Pf("InstanceNode",Nb);class Pb extends c_{constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n}getInputType(){return"buffer"}}const Ib=(e,t,n)=>Sg(new Pb(e,t,n));Pf("BufferNode",Pb);class Ub extends Lf{constructor(e=Ub.LOCAL){super(),this.scope=e}getHash(){return`tangent-${this.scope}`}getNodeType(){return this.scope===Ub.GEOMETRY?"vec4":"vec3"}generate(e){const t=this.scope;let n=null;if(t===Ub.GEOMETRY)n=__("tangent","vec4");else if(t===Ub.LOCAL)n=f_(Ob.xyz);else if(t===Ub.VIEW){const e=Ry.mul(Db).xyz;n=Jv(f_(e))}else if(t===Ub.WORLD){const e=Fb.transformDirection(Sy);n=Jv(f_(e))}return n.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Ub.GEOMETRY="geometry",Ub.LOCAL="local",Ub.VIEW="view",Ub.WORLD="world";const Ob=Ag(Ub,Ub.GEOMETRY),Db=Ag(Ub,Ub.LOCAL),Fb=Ag(Ub,Ub.VIEW),Bb=Ag(Ub,Ub.WORLD),Vb=P_(Fb,"TransformedTangentView"),zb=Jv(Vb.transformDirection(Sy));Pf("TangentNode",Ub);class Gb extends Lf{constructor(e){super("void"),this.skinnedMesh=e,this.updateType=gf.OBJECT,this.skinIndexNode=__("skinIndex","uvec4"),this.skinWeightNode=__("skinWeight","vec4"),this.bindMatrixNode=u_(e.bindMatrix,"mat4"),this.bindMatrixInverseNode=u_(e.bindMatrixInverse,"mat4"),this.boneMatricesNode=Ib(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)}setup(e){const{skinIndexNode:t,skinWeightNode:n,bindMatrixNode:i,bindMatrixInverseNode:r,boneMatricesNode:s}=this,a=s.element(t.x),o=s.element(t.y),l=s.element(t.z),c=s.element(t.w),u=i.mul(vb),h=yv(a.mul(n.x).mul(u),o.mul(n.y).mul(u),l.mul(n.z).mul(u),c.mul(n.w).mul(u)),d=r.mul(h).xyz;let p=yv(n.x.mul(a),n.y.mul(o),n.z.mul(l),n.w.mul(c));p=r.mul(p).mul(i);const m=p.transformDirection(Dy).xyz;vb.assign(d),Dy.assign(m),e.hasGeometryAttribute("tangent")&&Db.assign(m)}generate(e,t){if("void"!==t)return vb.build(e,t)}update(){this.skinnedMesh.skeleton.update()}}const kb=Eg(Gb);Pf("SkinningNode",Gb);const Hb=new WeakMap,Wb=new Ti,Xb=Rg((({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=Og(R_).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return ny(e,Vg(l,o)).depth(r).mul(t)}));class jb extends Lf{constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=u_(1),this.updateType=gf.OBJECT}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=Hb.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const r=e.morphAttributes.position||[],o=e.morphAttributes.normal||[],l=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===i&&(c=3);let u=e.attributes.position.count*c,h=1;const d=4096;u>d&&(h=Math.ceil(u/d),u=d);const p=new Float32Array(u*h*4*s),m=new Ai(p,u,h,s);m.type=Le,m.needsUpdate=!0;const f=4*c;for(let e=0;ee+t),0)}}const qb=Eg(jb);Pf("MorphNode",jb);class Yb extends Lf{constructor(){super("vec3")}getHash(){return"reflectVector"}setup(){return Sb.negate().reflect(Vy).transformDirection(Sy)}}const $b=Ag(Yb);Pf("ReflectVectorNode",Yb);class Zb extends ey{constructor(e,t=null,n=null){super(e,t,n),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){return $b}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.renderer.coordinateSystem!==Bn&&n.isRenderTargetTexture?t:kg(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Kb=Eg(Zb);Kf("cubeTexture",Kb),Pf("CubeTextureNode",Zb);class Jb extends Lf{constructor(){super("vec3")}generate(){}}Pf("LightingNode",Jb);let Qb=null;class eS extends Jb{constructor(e=null){super(),this.updateType=gf.FRAME,this.light=e,this.rtt=null,this.shadowNode=null,this.color=new $r,this._defaultColorNode=u_(this.color),this.colorNode=this._defaultColorNode,this.isAnalyticLightNode=!0}getCacheKey(){return super.getCacheKey()+"-"+this.light.id+"-"+(this.light.castShadow?"1":"0")}getHash(){return this.light.uuid}setupShadow(e){let t=this.shadowNode;if(null===t){null===Qb&&(Qb=e.createNodeMaterial("MeshBasicNodeMaterial"));const n=this.light.shadow,i=e.getRenderTarget(n.mapSize.width,n.mapSize.height),r=new $a;r.minFilter=fe,r.magFilter=fe,r.image.width=n.mapSize.width,r.image.height=n.mapSize.height,r.compareFunction=vn,i.depthTexture=r,n.camera.updateProjectionMatrix();const s=sy("bias","float",n),a=sy("normalBias","float",n);let o=u_(n.matrix).mul(xb.add(By.mul(a)));o=o.xyz.div(o.w);const l=o.x.greaterThanEqual(0).and(o.x.lessThanEqual(1)).and(o.y.greaterThanEqual(0)).and(o.y.lessThanEqual(1)).and(o.z.lessThanEqual(1));let c=o.z.add(s);e.renderer.coordinateSystem===Bn&&(c=c.mul(2).sub(1)),o=kg(o.x,o.y.oneMinus(),c);const u=(e,t,n)=>ty(e,t).compare(n);t=u(r,o.xy,o.z),this.rtt=i,this.colorNode=this.colorNode.mul(l.mix(1,t)),this.shadowNode=t,this.updateBeforeType=gf.RENDER}}setup(e){this.light.castShadow?this.setupShadow(e):null!==this.shadowNode&&this.disposeShadow()}updateShadow(e){const{rtt:t,light:n}=this,{renderer:i,scene:r}=e,s=r.overrideMaterial;r.overrideMaterial=Qb,t.setSize(n.shadow.mapSize.width,n.shadow.mapSize.height),n.shadow.updateMatrices(n);const a=i.getRenderTarget(),o=i.getRenderObjectFunction();i.setRenderObjectFunction(((e,...t)=>{!0===e.castShadow&&i.renderObject(e,...t)})),i.setRenderTarget(t),i.render(r,n.shadow.camera),i.setRenderTarget(a),i.setRenderObjectFunction(o),r.overrideMaterial=s}disposeShadow(){this.rtt.dispose(),this.shadowNode=null,this.rtt=null,this.colorNode=this._defaultColorNode}updateBefore(e){const{light:t}=this;t.castShadow&&this.updateShadow(e)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}Pf("AnalyticLightNode",eS);const tS=new WeakMap;class nS extends Lf{constructor(e=[]){super("vec3"),this.totalDiffuseNode=kg().temp("totalDiffuse"),this.totalSpecularNode=kg().temp("totalSpecular"),this.outgoingLightNode=kg().temp("outgoingLight"),this.lightNodes=e,this._hash=null}get hasLight(){return this.lightNodes.length>0}getHash(){if(null===this._hash){const e=[];for(const t of this.lightNodes)e.push(t.getHash());this._hash="lights-"+e.join(",")}return this._hash}setup(e){const t=e.context,n=t.lightingModel;let i=this.outgoingLightNode;if(n){const{lightNodes:r,totalDiffuseNode:s,totalSpecularNode:a}=this;t.outgoingLight=i;const o=e.addStack();n.start(t,o,e);for(const t of r)t.build(e);n.indirectDiffuse(t,o,e),n.indirectSpecular(t,o,e),n.ambientOcclusion(t,o,e);const{backdrop:l,backdropAlpha:c}=t,{directDiffuse:u,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=u.add(d);null!==l&&(m=kg(null!==c?c.mix(m,l):l)),s.assign(m),a.assign(h.add(p)),i.assign(s.add(a)),n.finish(t,o,e),i=i.bypass(e.removeStack())}return i}_getLightNodeById(e){for(const t of this.lightNodes)if(t.isAnalyticLightNode&&t.light.id===e)return t;return null}fromLights(e=[]){const t=[];e=(e=>e.sort(((e,t)=>e.id-t.id)))(e);for(const n of e){let e=this._getLightNodeById(n.id);if(null===e){const t=n.constructor,i=tS.has(t)?tS.get(t):eS;e=Sg(new i(n))}t.push(e)}return this.lightNodes=t,this._hash=null,this}}const iS=e=>Sg((new nS).fromLights(e)),rS=Eg(nS);function sS(e,t){if(!tS.has(e)){if("function"!=typeof e)throw new Error(`Light ${e.name} is not a class`);if("function"!=typeof t||!t.type)throw new Error(`Light node ${t.type} is not a class`);tS.set(e,t)}}class aS extends Jb{constructor(e=null){super(),this.aoNode=e}setup(e){const t=this.aoNode.x.sub(1).mul(1).add(1);e.context.ambientOcclusion.mulAssign(t)}}Pf("AONode",aS);class oS extends M_{constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._context=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:kg().temp("directDiffuse"),directSpecular:kg().temp("directSpecular"),indirectDiffuse:kg().temp("indirectDiffuse"),indirectSpecular:kg().temp("indirectSpecular")};return{radiance:kg().temp("radiance"),irradiance:kg().temp("irradiance"),iblIrradiance:kg().temp("iblIrradiance"),ambientOcclusion:Ug(1).temp("ambientOcclusion"),reflectedLight:n,backdrop:e,backdropAlpha:t}}setup(e){return this.context=this._context||(this._context=this.getContext()),this.context.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const lS=Eg(oS);Kf("lightingContext",lS),Pf("LightingContextNode",oS);class cS extends Hf{constructor(e=yb){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.negate().clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Bg(t,n)}}const uS=Eg(cS);Pf("EquirectUVNode",cS);class hS extends Lf{constructor(e,t=null){super("float"),this.textureNode=e,this.roughnessNode=t}setup(){const{textureNode:e,roughnessNode:t}=this,n=Qx(e),i=t.mul(t).mul(Math.PI).div(t.add(1));return n.add(i.log2()).clamp(0,n)}}const dS=Eg(hS);Pf("SpecularMIPLevelNode",hS);const pS=new WeakMap;class mS extends Jb{constructor(e=null){super(),this.envNode=e}setup(e){let t=this.envNode;if(t.isTextureNode&&!0!==t.value.isCubeTexture){let n=pS.get(t.value);if(void 0===n){const i=t.value,r=e.renderer,s=e.getCubeRenderTarget(512).fromEquirectangularTexture(r,i);n=Kb(s.texture),pS.set(t.value,n)}t=n}const n=sy("envMapIntensity","float",e.material),i=E_(t,fS(H_,Vy)).mul(n),r=E_(t,gS(zy)).mul(Math.PI).mul(n),s=T_(i);e.context.radiance.addAssign(s),e.context.iblIrradiance.addAssign(r);const a=e.context.lightingModel.clearcoatRadiance;if(a){const e=E_(t,fS(j_,Gy)).mul(n),i=T_(e);a.addAssign(i)}}}const fS=(e,t)=>{let n=null,i=null;return{getUV:r=>{let s=null;return null===n&&(n=Sb.negate().reflect(t),n=e.mul(e).mix(n,t).normalize(),n=n.transformDirection(Sy)),r.isCubeTextureNode?s=n:r.isTextureNode&&(null===i&&(i=uS(n)),s=i),s},getTextureLevel:()=>e,getTextureLevelAlgorithm:(e,t)=>dS(e,t)}},gS=e=>{let t=null;return{getUV:n=>{let i=null;return n.isCubeTextureNode?i=e:n.isTextureNode&&(null===t&&(t=uS(e),t=Bg(t.x,t.y.oneMinus())),i=t),i},getTextureLevel:e=>Qx(e)}};let _S,vS;Pf("EnvironmentNode",mS);class xS extends Lf{constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===xS.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=gf.NONE;return this.scope!==xS.RESOLUTION&&this.scope!==xS.VIEWPORT||(e=gf.FRAME),this.updateType=e,e}update({renderer:e}){this.scope===xS.VIEWPORT?e.getViewport(vS):e.getDrawingBufferSize(_S)}setup(){const e=this.scope;if(e===xS.COORDINATE)return;let t=null;if(e===xS.RESOLUTION)t=u_(_S||(_S=new Qn));else if(e===xS.VIEWPORT)t=u_(vS||(vS=new Ti));else{t=yS.div(bS);let n=t.x,i=t.y;/bottom/i.test(e)&&(i=i.oneMinus()),/right/i.test(e)&&(n=n.oneMinus()),t=Bg(n,i)}return t}generate(e){if(this.scope===xS.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(bS).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}xS.COORDINATE="coordinate",xS.RESOLUTION="resolution",xS.VIEWPORT="viewport",xS.TOP_LEFT="topLeft",xS.BOTTOM_LEFT="bottomLeft",xS.TOP_RIGHT="topRight",xS.BOTTOM_RIGHT="bottomRight";const yS=Ag(xS,xS.COORDINATE),bS=Ag(xS,xS.RESOLUTION),SS=Ag(xS,xS.VIEWPORT),TS=Ag(xS,xS.TOP_LEFT),MS=Ag(xS,xS.BOTTOM_LEFT),ES=Ag(xS,xS.TOP_RIGHT),AS=Ag(xS,xS.BOTTOM_RIGHT);Pf("ViewportNode",xS);const wS=new Qn;class RS extends ey{constructor(e=TS,t=null,n=null){null===n&&((n=new wu).minFilter=Te),super(n,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=gf.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(wS);const n=this.value;n.image.width===wS.width&&n.image.height===wS.height||(n.image.width=wS.width,n.image.height=wS.height,n.needsUpdate=!0);const i=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=i}clone(){return new this.constructor(this.uvNode,this.levelNode,this.value)}}const CS=Eg(RS),NS=Eg(RS,null,null,{generateMipmaps:!0});Kf("viewportTexture",CS),Kf("viewportMipTexture",NS),Pf("ViewportTextureNode",RS);let LS=null;class PS extends RS{constructor(e=TS,t=null){null===LS&&(LS=new $a,LS.minFilter=ge,LS.type=Ne,LS.format=ze),super(e,t,LS)}}const IS=Eg(PS);Kf("viewportDepthTexture",IS),Pf("ViewportDepthTextureNode",PS);class US extends Lf{constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===US.DEPTH_PIXEL?e.getFragDepth():super.generate(e)}setup(){const{scope:e}=this;let t=null;if(e===US.DEPTH)t=OS(bb.z,xy,yy);else if(e===US.DEPTH_TEXTURE){const e=this.valueNode||IS(),n=BS(e,xy,yy);t=OS(n,xy,yy)}else e===US.DEPTH_PIXEL&&null!==this.valueNode&&(t=VS().assign(this.valueNode));return t}}const OS=(e,t,n)=>e.add(t).div(t.sub(n)),DS=(e,t,n)=>t.sub(n).mul(e).sub(t),FS=(e,t,n)=>t.add(e).mul(n).div(t.sub(n).mul(e)),BS=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n));US.DEPTH="depth",US.DEPTH_TEXTURE="depthTexture",US.DEPTH_PIXEL="depthPixel";const VS=Eg(US,US.DEPTH_PIXEL),zS=Ag(US,US.DEPTH),GS=Eg(US,US.DEPTH_TEXTURE),kS=Ag(US,US.DEPTH_PIXEL);kS.assign=e=>VS(e),Pf("ViewportDepthNode",US);const HS=new Map;class WS extends Zs{constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!0,this.normals=!0,this.colorSpaced=!0,this.lightsNode=null,this.envNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.positionNode=null,this.depthNode=null,this.outputNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+Sf(this)}build(e){this.setup(e)}setup(e){let t;if(e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),e.addFlow("vertex",e.removeStack()),e.addStack(),null===this.fragmentNode){!0===this.depthWrite&&this.setupDepth(e),!0===this.normals&&this.setupNormal(e),this.setupDiffuseColor(e),this.setupVariants(e);const n=this.setupLighting(e);t=this.setupOutput(e,jg(n,k_.a)),ev.assign(t),null!==this.outputNode&&(t=this.outputNode)}else t=this.setupOutput(e,this.fragmentNode);e.stack.outputNode=t,e.addFlow("fragment",e.removeStack())}setupDepth(e){const{renderer:t}=e;let n=this.depthNode;if(null===n&&!0===t.logarithmicDepthBuffer){n=Mb().w.add(1).log2().mul(by).mul(.5)}null!==n&&kS.assign(n).append()}setupPosition(e){const{object:t}=e,n=t.geometry;e.addStack(),(n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&qb(t).append(),!0===t.isSkinnedMesh&&kb(t).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&!0===e.isAvailable("instance")&&Lb(t).append(),null!==this.positionNode&&vb.assign(this.positionNode);const i=Mb();return e.context.vertex=e.removeStack(),e.context.mvp=i,i}setupDiffuseColor({geometry:e}){let t=this.colorNode?jg(this.colorNode):Xy;!0===this.vertexColors&&e.hasAttribute("color")&&(t=jg(t.xyz.mul(__("color","vec3")),t.a)),k_.assign(t);const n=this.opacityNode?Ug(this.opacityNode):Yy;if(k_.a.assign(k_.a.mul(n)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Ug(this.alphaTestNode):Wy;k_.a.lessThanEqual(e).discard()}}setupVariants(){}setupNormal(){if(!0===this.flatShading){const e=bb.dFdx().cross(bb.dFdy()).normalize();Vy.assign(e)}else{const e=this.normalNode?kg(this.normalNode):eb;Vy.assign(e)}}getEnvNode(e){let t=null;return this.envNode?t=this.envNode:this.envMap?t=this.envMap.isCubeTexture?Kb(this.envMap):ty(this.envMap):e.environmentNode&&(t=e.environmentNode),t}setupLights(e){const t=this.getEnvNode(e),n=[];t&&n.push(new mS(t)),e.material.aoMap&&n.push(new aS(ty(e.material.aoMap)));let i=this.lightsNode||e.lightsNode;return n.length>0&&(i=rS([...i.lightNodes,...n])),i}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=k_.rgb;if(s&&!1!==s.hasLight){const t=this.setupLightingModel(e);a=lS(s,t,n,i)}else null!==n&&(a=kg(null!==i?Ux(a,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(a=a.add(kg(r||qy))),a}setupOutput(e,t){const n=e.renderer,i=e.toneMappingNode;if(!0===this.toneMapped&&i&&(t=jg(i.context({color:t.rgb}),t.a)),!0===this.fog){const n=e.fogNode;n&&(t=jg(n.mixAssign(t.rgb),t.a))}if(!0===this.colorSpaced){const e=n.currentColorSpace;e!==qt&&e!==Xt&&(t=t.linearToColorSpace(e))}return t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}Object.assign(this.defines,e.defines);const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const n=Jr.prototype.toJSON.call(this,e),i=Tf(this);n.inputNodes={};for(const{property:t,childNode:r}of i)n.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),s=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.positionNode=e.positionNode,this.depthNode=e.depthNode,this.outputNode=e.outputNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}static fromMaterial(e){if(!0===e.isNodeMaterial)return e;const t=jS(e.type.replace("Material","NodeMaterial"));if(void 0===t)throw new Error(`NodeMaterial: Material "${e.type}" is not compatible.`);for(const n in e)t[n]=e[n];return t}}function XS(e,t){if("function"!=typeof t||!e)throw new Error(`Node material ${e} is not a class`);HS.has(e)||(HS.set(e,t),t.type=e)}function jS(e){const t=HS.get(e);if(void 0!==t)return new t}XS("NodeMaterial",WS);class qS{constructor(e,t=null){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 YS extends qS{constructor(e,t=0){super(e,t),this.isFloatUniform=!0,this.boundary=4,this.itemSize=1}}class $S extends qS{constructor(e,t=new Qn){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class ZS extends qS{constructor(e,t=new Pi){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class KS extends qS{constructor(e,t=new Ti){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class JS extends qS{constructor(e,t=new $r){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class QS extends qS{constructor(e,t=new ei){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class eT extends qS{constructor(e,t=new lr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class tT extends YS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class nT extends $S{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class iT extends ZS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class rT extends KS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class sT extends JS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class aT extends QS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class oT extends eT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class lT extends Lf{constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const n=this.elseNode.getNodeType(e);if(e.getTypeLength(n)>e.getTypeLength(t))return n}return t}generate(e){const t=this.getNodeType(e),n={tempWrite:!1},{ifNode:i,elseNode:r}=this,s="void"!==i.getNodeType(e)||r&&"void"!==r.getNodeType(e),a=s?z_(t).build(e):"",o=E_(this.condNode).build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${o} ) {\n\n`).addFlowTab();let l=E_(this.ifNode,n).build(e,t);if(l=s?a+" = "+l+";":l,e.removeFlowTab().addFlowCode(e.tab+"\t"+l+"\n\n"+e.tab+"}"),null!==r){e.addFlowCode(" else {\n\n").addFlowTab();let i=E_(r,n).build(e,t);i=a?a+" = "+i+";":i,e.removeFlowTab().addFlowCode(e.tab+"\t"+i+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return a}}const cT=Eg(lT);Kf("cond",cT),Pf("CondNode",lT);class uT extends Lf{constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}if(e,t){const n=new bg(t);return this._currentCond=cT(e,n),this.add(this._currentCond)}elseif(e,t){const n=new bg(t),i=cT(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}else(e){return this._currentCond.elseNode=new bg(e),this}build(e,...t){const n=Ng();Cg(this);for(const t of this.nodes)t.build(e,"void");return Cg(n),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}}const hT=Eg(uT);Pf("StackNode",uT);class dT extends na{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Xs(5,5,5),s=uS(yb),a=jS("MeshBasicNodeMaterial");a.colorNode=ty(t,s,0),a.side=d,a.blending=0;const o=new Hs(r,a),l=new Jl;l.add(o),t.minFilter===Te&&(t.minFilter=ye);return new ea(1,10,this).update(e,l),t.minFilter=n,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}}const pT=new qm,mT=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),fT=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),gT=e=>(e=Number(e))+(e%1?"":".0");class _T{constructor(e,t,n,i=null,r=null){this.object=e,this.material=r||e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=i,this.nodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.hashNodes={},this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.toneMappingNode=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.bindingsOffset={vertex:0,fragment:0,compute:0},this.bindingsArray=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=hT(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={keywords:new B_,material:this.material},this.cache=new b_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getRenderTarget(e,t,n){return new Mi(e,t,n)}getCubeRenderTarget(e,t){return new dT(e,t)}includes(e){return this.nodes.includes(e)}_getSharedBindings(e){const t=[];for(const n of e)if(!0===n.shared){const e=n.getNodes();let i=pT.get(e);void 0===i&&(pT.set(e,n),i=n),t.push(i)}else t.push(n);return t}getBindings(){let e=this.bindingsArray;if(null===e){const t=this.bindings;this.bindingsArray=e=this._getSharedBindings(null!==this.material?[...t.vertex,...t.fragment]:t.compute)}return e}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}buildUpdateNodes(){for(const e of this.nodes){const t=e.getUpdateType(),n=e.getUpdateBeforeType();t!==gf.NONE&&this.updateNodes.push(e.getSelf()),n!==gf.NONE&&this.updateBeforeNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}setCache(e){this.cache=e}getCache(){return this.cache}isAvailable(){return!1}getVertexIndex(){}getInstanceIndex(){}getFrontFacing(){}getFragCoord(){}isFlipY(){return!1}generateTexture(){}generateTextureLod(){}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new $r:"vec2"===e?t=new Qn:"vec3"===e?t=new Pi:"vec4"===e&&(t=new Ti)),"float"===e)return gT(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${gT(t.r)}, ${gT(t.g)}, ${gT(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}generateMethod(e){return e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new I_(e,t);return n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"texture"===e||"cubeTexture"===e}needsColorSpaceToLinear(){return!1}getTextureEncodingFromMap(e){return this.getTextureColorSpaceFromMap(e)===jt?zt:Vt}getTextureColorSpaceFromMap(e){let t;return t=e&&e.isTexture?e.colorSpace:e&&e.isWebGLRenderTarget?e.texture.colorSpace:Xt,t}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?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;const n=mT.get(e);return("float"===t?"":t[0])+n}getTypeFromArray(e){return fT.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof fs||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/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=hT(this.stack),this.stacks.push(Ng()||this.stack),Cg(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Cg(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getNodeData(e);return void 0===i&&(i={},n.setNodeData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e);let i=n.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new I_("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const n=this.getDataFromNode(e,t);if(void 0===n.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),n.structType=e}return e}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new U_(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),r.uniform=s}return s}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let s=r.variable;if(void 0===s){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),s=new O_(t,n),e.push(s),r.variable=s}return s}getVaryingFromNode(e,t=null,n=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,s=e.length;null===t&&(t="nodeVarying"+s),r=new D_(t,n),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new F_("nodeCode"+s,t),e.push(r),i.code=r}return r}addLineFlowCode(e){return""===e||(e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}buildFunctionNode(e){const t=new hv,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout;let n;if(e.isArrayInput){n=[];for(const e of t.inputs)n.push(new rv(e.type,e.name))}else{n={};for(const e of t.inputs)n[e.name]=new rv(e.type,e.name)}e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.buildStage,s={code:""};this.flow=s,this.vars={};for(const n of xf)this.setBuildStage(n),s.result=e.build(this,t);return s.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.setBuildStage(r),s}getFunctionOperator(){return null}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const s=this.flowChildNode(t,n);return null!==i&&(s.code+=`${this.tab+i} = ${s.result};\n`),this.flowCode[e]=this.flowCode[e]+s.code,this.setShaderStage(r),s}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){}getVaryings(){}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){}build(e=!0){const{object:t,material:n}=this;e&&(null!==n?WS.fromMaterial(n).build(this):this.addFlow("compute",t));for(const e of xf){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of yf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t)return new tT(e);if("vec2"===t)return new nT(e);if("vec3"===t)return new iT(e);if("vec4"===t)return new rT(e);if("color"===t)return new sT(e);if("mat3"===t)return new aT(e);if("mat4"===t)return new oT(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e){return jS(e)}getPrimitiveType(e){let t;return t="i"===e[0]?"int":"u"===e[0]?"uint":"float",t}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),n):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t[0]!==n[0]&&(e=`${this.getType(this.getPrimitiveType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${e} - NodeMaterial System\n`}}class vT{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===gf.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(e)!==this.frameId&&(t.set(e,this.frameId),e.updateBefore(this))}else if(t===gf.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(e)!==this.renderId&&(t.set(e,this.renderId),e.updateBefore(this))}else t===gf.OBJECT&&e.updateBefore(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===gf.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,n);t.get(e)!==this.frameId&&(t.set(e,this.frameId),e.update(this))}else if(t===gf.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,n);t.get(e)!==this.renderId&&(t.set(e,this.renderId),e.update(this))}else t===gf.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 xT{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}xT.isNodeFunctionInput=!0;class yT extends Lf{constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}Pf("StructTypeNode",yT);class bT extends Lf{constructor(...e){super(),this.isOutputStructNode=!0,this.members=e}setup(e){super.setup(e);const t=this.members,n=[];for(let i=0;iwT(e).append();Kf("discard",RT),Pf("DiscardNode",AT);class CT extends Lf{constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let n=this._candidateFnCall;if(null===n){let i=null,r=-1;for(const n of this.functionNodes){const s=n.shaderNode.layout;if(null===s)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=s.inputs;if(t.length===a.length){let s=0;for(let n=0;nr&&(i=n,r=s)}}this._candidateFnCall=n=i(...t)}return n}}const NT=Eg(CT),LT=e=>(...t)=>NT(e,...t);Pf("FunctionOverloadingNode",CT);class PT extends Lf{constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;eNumber(s)?">=":"<"));const u={start:r,end:s,condition:l},h=u.start,d=u.end;let p="",m="",f="";c||(c="int"===o?l.includes("<")?"++":"--":l.includes("<")?"+= 1":"-= 1"),p+=e.getVar(o,a)+" = "+h,m+=a+" "+l+" "+d,f+=a+" "+c;const g=`for ( ${p}; ${m}; ${f} )`;e.addFlowCode((0===t?"\n":"")+e.tab+g+" {\n\n").addFlowTab()}const r=E_(i,{tempWrite:!1}).build(e,"void"),s=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,n=this.params.length-1;tSg(new PT(Mg(e,"int"))).append();Kf("loop",((e,...t)=>x_(e,IT(...t)))),Pf("LoopNode",PT);class UT extends Hf{constructor(){super("vec2")}setup(){const e=kg(Sb.z,0,Sb.x.negate()).normalize(),t=Sb.cross(e);return Bg(e.dot(Vy),t.dot(Vy)).mul(.495).add(.5)}}const OT=Ag(UT);Pf("MatcapUVNode",UT);class DT extends c_{constructor(e=DT.LOCAL,t=1,n=0){super(n),this.scope=e,this.scale=t,this.updateType=gf.FRAME}update(e){const t=this.scope,n=this.scale;t===DT.LOCAL?this.value+=e.deltaTime*n:t===DT.DELTA?this.value=e.deltaTime*n:t===DT.FRAME?this.value=e.frameId:this.value=e.time*n}serialize(e){super.serialize(e),e.scope=this.scope,e.scale=this.scale}deserialize(e){super.deserialize(e),this.scope=e.scope,this.scale=e.scale}}DT.LOCAL="local",DT.GLOBAL="global",DT.DELTA="delta",DT.FRAME="frame";const FT=(e,t=0)=>Sg(new DT(DT.LOCAL,e,t)),BT=(e,t=0)=>Sg(new DT(DT.GLOBAL,e,t)),VT=(e,t=0)=>Sg(new DT(DT.DELTA,e,t)),zT=Ag(DT,DT.FRAME).uint();Pf("TimerNode",DT);class GT extends Lf{constructor(e=GT.SINE,t=FT()){super(),this.method=e,this.timeNode=t}getNodeType(e){return this.timeNode.getNodeType(e)}setup(){const e=this.method,t=Sg(this.timeNode);let n=null;return e===GT.SINE?n=t.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5):e===GT.SQUARE?n=t.fract().round():e===GT.TRIANGLE?n=t.add(.5).fract().mul(2).sub(1).abs():e===GT.SAWTOOTH&&(n=t.fract()),n}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}GT.SINE="sine",GT.SQUARE="square",GT.TRIANGLE="triangle",GT.SAWTOOTH="sawtooth";const kT=Eg(GT,GT.SINE),HT=Eg(GT,GT.SQUARE),WT=Eg(GT,GT.TRIANGLE),XT=Eg(GT,GT.SAWTOOTH);Pf("OscNode",GT);class jT extends Hf{constructor(e,t){super(),this.scope=e,this.node=t}getNodeType(e){return this.node.getNodeType(e)}setup(){const{scope:e,node:t}=this;let n=null;return e===jT.DIRECTION_TO_COLOR?n=t.mul(.5).add(.5):e===jT.COLOR_TO_DIRECTION&&(n=t.mul(2).sub(1)),n}}jT.DIRECTION_TO_COLOR="directionToColor",jT.COLOR_TO_DIRECTION="colorToDirection";const qT=Eg(jT,jT.DIRECTION_TO_COLOR),YT=Eg(jT,jT.COLOR_TO_DIRECTION);Kf("directionToColor",qT),Kf("colorToDirection",YT),Pf("PackingNode",jT);class $T extends Lf{constructor(e,t,n,i=Ug(0),r=Ug(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:i,outHighNode:r,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const ZT=Eg($T,null,null,{doClamp:!1}),KT=Eg($T);Kf("remap",ZT),Kf("remapClamp",KT),Pf("RemapNode",$T);class JT extends Hf{constructor(e,t,n=Bg(.5)){super("vec2"),this.uvNode=e,this.rotationNode=t,this.centerNode=n}setup(){const{uvNode:e,rotationNode:t,centerNode:n}=this,i=t.cos(),r=t.sin(),s=e.sub(n);return Bg(Bg(i,r).dot(s),Bg(r.negate(),i).dot(s)).add(n)}}const QT=Eg(JT);Kf("rotateUV",QT),Pf("RotateUVNode",JT);class eM extends Lf{constructor(e,t=gv(),n=Ug(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=n}setup(){const{frameNode:e,uvNode:t,countNode:n}=this,{width:i,height:r}=n,s=e.mod(i.mul(r)).floor(),a=s.mod(i),o=r.sub(s.add(1).div(i).ceil()),l=n.reciprocal(),c=Bg(a,o);return t.add(c).mul(l)}}const tM=Eg(eM);Pf("SpriteSheetUVNode",eM);class nM extends Lf{constructor(e,t=null,n=null,i=Ug(1),r=vb,s=Dy){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=n,this.scaleNode=i,this.positionNode=r,this.normalNode=s}setup(){const{textureXNode:e,textureYNode:t,textureZNode:n,scaleNode:i,positionNode:r,normalNode:s}=this;let a=s.abs().normalize();a=a.div(a.dot(kg(1)));const o=r.yz.mul(i),l=r.zx.mul(i),c=r.xy.mul(i),u=e.value,h=null!==t?t.value:u,d=null!==n?n.value:u,p=ty(u,o).mul(a.x),m=ty(h,l).mul(a.y),f=ty(d,c).mul(a.z);return yv(p,m,f)}}const iM=Eg(nM),rM=(...e)=>iM(...e);Kf("triplanarTexture",rM),Pf("TriplanarTexturesNode",nM);class sM extends Lf{constructor(e=sM.LOCAL){super("vec3"),this.scope=e}getHash(){return`bitangent-${this.scope}`}generate(e){const t=this.scope;let n;t===sM.GEOMETRY?n=Oy.cross(Ob):t===sM.LOCAL?n=Dy.cross(Db):t===sM.VIEW?n=Fy.cross(Fb):t===sM.WORLD&&(n=By.cross(Bb));const i=n.mul(Ob.w).xyz;return Jv(f_(i)).build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}sM.GEOMETRY="geometry",sM.LOCAL="local",sM.VIEW="view",sM.WORLD="world";const aM=Ag(sM,sM.GEOMETRY),oM=Ag(sM,sM.LOCAL),lM=Ag(sM,sM.VIEW),cM=Ag(sM,sM.WORLD),uM=Jv(Vy.cross(Vb).mul(Ob.w)),hM=Jv(uM.transformDirection(Sy));Pf("BitangentNode",sM);class dM extends g_{constructor(e=0){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Ti(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const pM=(...e)=>Sg(new dM(...e));Pf("VertexColorNode",dM);const mM=1/6,fM=e=>Sv(mM,Sv(e,Sv(e,e.negate().add(3)).sub(3)).add(1)),gM=e=>Sv(mM,Sv(e,Sv(e,Sv(3,e).sub(6))).add(4)),_M=e=>Sv(mM,Sv(e,Sv(e,Sv(-3,e).add(3)).add(3)).add(1)),vM=e=>Sv(mM,Rx(e,3)),xM=e=>fM(e).add(gM(e)),yM=e=>_M(e).add(vM(e)),bM=e=>yv(-1,gM(e).div(fM(e).add(gM(e)))),SM=e=>yv(1,vM(e).div(_M(e).add(vM(e)))),TM=(e,t,n)=>{const i=e.uvNode,r=Sv(i,t.zw).add(.5),s=Zv(r),a=Qv(r),o=xM(a.x),l=yM(a.x),c=bM(a.x),u=SM(a.x),h=bM(a.y),d=SM(a.y),p=Bg(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=Bg(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=Bg(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),g=Bg(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),_=xM(a.y).mul(yv(o.mul(e.uv(p).level(n)),l.mul(e.uv(m).level(n)))),v=yM(a.y).mul(yv(o.mul(e.uv(f).level(n)),l.mul(e.uv(g).level(n))));return _.add(v)};class MM extends Hf{constructor(e,t=Ug(3)){super("vec4"),this.textureNode=e,this.blurNode=t}setup(){return((e,t)=>{const n=Bg(e.size(Og(t))),i=Bg(e.size(Og(t.add(1)))),r=Tv(1,n),s=Tv(1,i),a=TM(e,jg(r,n),Zv(t)),o=TM(e,jg(s,i),Kv(t));return Qv(t).mix(a,o)})(this.textureNode,this.blurNode)}}const EM=Eg(MM);Kf("bicubic",EM),Pf("TextureBicubicNode",MM);class AM extends Lf{constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const wM=Ag(AM);Pf("PointUVNode",AM);class RM extends Lf{constructor(e=RM.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=null!==this.scene?this.scene:e.scene;let i;return t===RM.BACKGROUND_BLURRINESS?i=sy("backgroundBlurriness","float",n):t===RM.BACKGROUND_INTENSITY&&(i=sy("backgroundIntensity","float",n)),i}}RM.BACKGROUND_BLURRINESS="backgroundBlurriness",RM.BACKGROUND_INTENSITY="backgroundIntensity";const CM=Ag(RM,RM.BACKGROUND_BLURRINESS),NM=Ag(RM,RM.BACKGROUND_INTENSITY);Pf("SceneNode",RM);class LM extends Pb{constructor(e,t,n=0){super(e,t,n),this.isStorageBufferNode=!0}getInputType(){return"storageBuffer"}}const PM=(e,t,n)=>Sg(new LM(e,t,n));Pf("StorageBufferNode",LM);class IM extends ey{constructor(e,t,n=null){super(e,t),this.storeNode=n,this.isStoreTextureNode=!0}getNodeType(){return"void"}}const UM=Eg(IM);Pf("TextureStoreNode",IM);class OM extends ry{constructor(e,t,n=null){super(e,t,n),this.userData=n}update(e){this.reference=null!==this.userData?this.userData:e.object.userData,super.update(e)}}const DM=(e,t,n)=>Sg(new OM(e,t,n));Pf("UserDataNode",OM);const FM=Rg((({base:e,blend:t})=>{const n=n=>t[n].lessThan(zv).cond(t[n],e[n].oneMinus().div(t[n]).oneMinus().max(0));return kg(n("x"),n("y"),n("z"))})),BM=Rg((({base:e,blend:t})=>{const n=n=>t[n].equal(1).cond(t[n],e[n].div(t[n].oneMinus()).max(0));return kg(n("x"),n("y"),n("z"))})),VM=Rg((({base:e,blend:t})=>{const n=n=>e[n].oneMinus().mul(t[n].oneMinus()).oneMinus();return kg(n("x"),n("y"),n("z"))})),zM=Rg((({base:e,blend:t})=>{const n=n=>e[n].lessThan(.5).cond(e[n].mul(t[n],2),e[n].oneMinus().mul(t[n].oneMinus()).oneMinus());return kg(n("x"),n("y"),n("z"))}));class GM extends Hf{constructor(e,t,n){super(),this.blendMode=e,this.baseNode=t,this.blendNode=n}setup(){const{blendMode:e,baseNode:t,blendNode:n}=this,i={base:t,blend:n};let r=null;return e===GM.BURN?r=FM(i):e===GM.DODGE?r=BM(i):e===GM.SCREEN?r=VM(i):e===GM.OVERLAY&&(r=zM(i)),r}}GM.BURN="burn",GM.DODGE="dodge",GM.SCREEN="screen",GM.OVERLAY="overlay";const kM=Eg(GM,GM.BURN),HM=Eg(GM,GM.DODGE),WM=Eg(GM,GM.OVERLAY),XM=Eg(GM,GM.SCREEN);Kf("burn",kM),Kf("dodge",HM),Kf("overlay",WM),Kf("screen",XM),Pf("BlendModeNode",GM);class jM extends Lf{constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){return e.getFrontFacing()}}const qM=Ag(jM),YM=Ug(qM).mul(2).sub(1);Pf("FrontFacingNode",jM);const $M=Rg((({textureNode:e,bumpScale:t})=>{let n=e;if(!0!==n.isTextureNode&&n.traverse((e=>{!0===e.isTextureNode&&(n=e)})),!0!==n.isTextureNode)throw new Error("THREE.TSL: dHdxy_fwd() requires a TextureNode.");const i=Ug(e),r=n.uvNode||gv(),s=t=>e.cache().context({getUV:()=>t,forceUVContext:!0});return Bg(Ug(s(r.add(r.dFdx()))).sub(i),Ug(s(r.add(r.dFdy()))).sub(i)).mul(t)})),ZM=Rg((e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(YM),c=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(c).normalize()}));class KM extends Hf{constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=$M({textureNode:this.textureNode,bumpScale:e});return ZM({surf_pos:bb,surf_norm:Fy,dHdxy:t})}}const JM=Eg(KM);Kf("bumpMap",JM),Pf("BumpMapNode",KM);const QM=Rg((({color:e,adjustment:t})=>t.mix(oE(e.rgb),e.rgb))),eE=Rg((({color:e,adjustment:t})=>{const n=yv(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(n).mul(t).mul(-3);return Ux(e.rgb,i,r)})),tE=Rg((({color:e,adjustment:t})=>{const n=kg(.57735,.57735,.57735),i=t.cos();return kg(e.rgb.mul(i).add(n.cross(e.rgb).mul(t.sin()).add(n.mul(Ax(n,e.rgb).mul(i.oneMinus())))))}));class nE extends Hf{constructor(e,t,n=Ug(1)){super("vec3"),this.method=e,this.colorNode=t,this.adjustmentNode=n}setup(){const{method:e,colorNode:t,adjustmentNode:n}=this,i={color:t,adjustment:n};let r=null;return e===nE.SATURATION?r=QM(i):e===nE.VIBRANCE?r=eE(i):e===nE.HUE&&(r=tE(i)),r}}nE.SATURATION="saturation",nE.VIBRANCE="vibrance",nE.HUE="hue";const iE=Eg(nE,nE.SATURATION),rE=Eg(nE,nE.VIBRANCE),sE=Eg(nE,nE.HUE),aE=kg(.2125,.7154,.0721),oE=(e,t=aE)=>Ax(e,t);Kf("saturation",iE),Kf("vibrance",rE),Kf("hue",sE),Pf("ColorAdjustmentNode",nE);const lE=Rg((e=>{const{eye_pos:t,surf_norm:n,mapN:i,uv:r}=e,s=t.dFdx(),a=t.dFdy(),o=r.dFdx(),l=r.dFdy(),c=n,u=a.cross(c),h=c.cross(s),d=u.mul(o.x).add(h.mul(l.x)),p=u.mul(o.y).add(h.mul(l.y)),m=d.dot(d).max(p.dot(p)),f=YM.mul(m.inverseSqrt());return yv(d.mul(i.x,f),p.mul(i.y,f),c.mul(i.z)).normalize()}));class cE extends Hf{constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:n}=this;let i=this.node.mul(2).sub(1);null!==n&&(i=kg(i.xy.mul(n),i.z));let r=null;if(1===t)r=Cy.mul(i).normalize();else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?hE.mul(i).normalize():lE({eye_pos:bb,surf_norm:Fy,mapN:i,uv:gv()})}return r}}const uE=Eg(cE),hE=Zg(Fb,lM,Fy);Kf("normalMap",uE),Pf("NormalMapNode",cE);class dE extends Hf{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 pE=Eg(dE);Kf("posterize",pE),Pf("PosterizeNode",dE);const mE=Rg((({color:e,exposure:t})=>e.mul(t).clamp())),fE=Rg((({color:e,exposure:t})=>(e=e.mul(t)).div(e.add(1)).clamp())),gE=Rg((({color:e,exposure:t})=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(i).pow(2.2)})),_E=Rg((({color:e})=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)})),vE=Rg((({color:e,exposure:t})=>{const n=Zg(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Zg(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=_E({color:e}),(e=i.mul(e)).clamp()})),xE={[J]:mE,[Q]:fE,[ee]:gE,[te]:vE};class yE extends Hf{constructor(e=K,t=Ug(1),n=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=n}getCacheKey(){let e=super.getCacheKey();return e="{toneMapping:"+this.toneMapping+",nodes:"+e+"}",e}setup(e){const t=this.colorNode||e.context.color,n=this.toneMapping;if(n===K)return t;const i={exposure:this.exposureNode,color:t},r=xE[n];let s=null;return s=r?r(i):t,s}}const bE=(e,t,n)=>Sg(new yE(e,Sg(t),Sg(n)));Pf("ToneMappingNode",yE);let SE=null;class TE extends RS{constructor(e=TS,t=null){null===SE&&(SE=new wu),super(e,t,SE)}}const ME=Eg(TE);Kf("viewportSharedTexture",ME),Pf("ViewportSharedTextureNode",TE);const EE=new Ta(-1,1,1,-1,0,1);const AE=new class extends Es{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new gs([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new gs(t,2))}};class wE{constructor(e=null){this._mesh=new Hs(AE,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,EE)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}const RE=new wE,CE=new wE;class NE extends Hf{constructor(e,t=2){super(e),this.textureNode=e,this.sigma=t,this.directionNode=Bg(1),this._invSize=u_(new Qn),this._passDirection=u_(new Qn),this._horizontalRT=new Mi,this._horizontalRT.texture.name="GaussianBlurNode.horizontal",this._verticalRT=new Mi,this._verticalRT.texture.name="GaussianBlurNode.vertical",this.updateBeforeType=gf.RENDER,this.resolution=new Qn(1,1)}setSize(e,t){e=Math.max(Math.round(e*this.resolution.x),1),t=Math.max(Math.round(t*this.resolution.y),1),this._invSize.value.set(1/e,1/t),this._horizontalRT.setSize(e,t),this._verticalRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,n=this.textureNode,i=n.value,r=t.getRenderTarget(),s=n.value;RE.material=this._material,CE.material=this._material,this.setSize(i.image.width,i.image.height),t.setRenderTarget(this._horizontalRT),this._passDirection.value.set(1,0),RE.render(t),n.value=this._horizontalRT.texture,t.setRenderTarget(this._verticalRT),this._passDirection.value.set(0,1),CE.render(t),t.setRenderTarget(r),n.value=s}setup(e){const t=this.textureNode;if(!0!==t.isTextureNode)return jg();const n=t.uvNode||gv(),i=e=>t.cache().context({getUV:()=>e,forceUVContext:!0}),r=Rg((()=>{const e=3+2*this.sigma,t=this._getCoefficients(e),r=this._invSize,s=Bg(this.directionNode).mul(this._passDirection),a=Ug(t[0]).toVar(),o=jg(i(n).mul(a)).toVar();for(let l=1;lSg(new NE(Sg(e),t));Kf("gaussianBlur",LE);const PE=new wE;class IE extends Hf{constructor(e,t=.96){super(e),this.textureNode=e,this.textureNodeOld=ty(),this.damp=u_(t),this._compRT=new Mi,this._compRT.texture.name="AfterImageNode.comp",this._oldRT=new Mi,this._oldRT.texture.name="AfterImageNode.old",this.updateBeforeType=gf.RENDER}setSize(e,t){this._compRT.setSize(e,t),this._oldRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,n=this.textureNode,i=t.getRenderTarget(),r=n.value;this.textureNodeOld.value=this._oldRT.texture,t.setRenderTarget(this._compRT),PE.render(t);const s=this._oldRT;this._oldRT=this._compRT,this._compRT=s;const a=r;this.setSize(a.image.width,a.image.height),t.setRenderTarget(i),n.value=r}setup(e){const t=this.textureNode,n=this.textureNodeOld;if(!0!==t.isTextureNode)return jg();const i=t.uvNode||gv();n.uvNode=i;const r=Rg((([e,t])=>{const n=Ug(t).toVar(),i=jg(e).toVar();return yx(ox(i.sub(n)),0)})),s=Rg((()=>{const e=jg(n),s=jg((e=>t.cache().context({getUV:()=>e,forceUVContext:!0}))(i));return e.mulAssign(this.damp.mul(r(e,.1))),yx(s,e)})),a=this._materialComposed||(this._materialComposed=e.createNodeMaterial("MeshBasicNodeMaterial"));a.fragmentNode=s(),PE.material=a;return e.getNodeProperties(this).textureNode=t,ty(this._compRT.texture)}}const UE=(e,t)=>Sg(new IE(Sg(e),t));Kf("afterImage",UE);class OE extends ey{constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class DE extends Hf{constructor(e,t,n){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this._pixelRatio=1,this._width=1,this._height=1;const i=new $a;i.isRenderTargetTexture=!0,i.type=Le,i.name="PostProcessingDepth";const r=new Mi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Pe});r.texture.name="PostProcessing",r.depthTexture=i,this.renderTarget=r,this.updateBeforeType=gf.FRAME,this._textureNode=Sg(new OE(this,r.texture)),this._depthTextureNode=Sg(new OE(this,i)),this._depthNode=null,this._cameraNear=u_(0),this._cameraFar=u_(0),this.isPassNode=!0}isGlobal(){return!0}getTextureNode(){return this._textureNode}getTextureDepthNode(){return this._depthTextureNode}getDepthNode(){if(null===this._depthNode){const e=this._cameraNear,t=this._cameraFar;this._depthNode=OS(BS(this._depthTextureNode,e,t),e,t)}return this._depthNode}setup(){return this.scope===DE.COLOR?this.getTextureNode():this.getDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(new Qn);this.setSize(r.width,r.height);const s=t.toneMapping,a=t.toneMappingNode,o=t.getRenderTarget();this._cameraNear.value=i.near,this._cameraFar.value=i.far,t.toneMapping=K,t.toneMappingNode=null,t.setRenderTarget(this.renderTarget),t.render(n,i),t.toneMapping=s,t.toneMappingNode=a,t.setRenderTarget(o)}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}DE.COLOR="color",DE.DEPTH="depth";const FE=(e,t)=>Sg(new DE(DE.COLOR,e,t)),BE=(e,t)=>Sg(new DE(DE.DEPTH,e,t));Pf("PassNode",DE);class VE extends Hf{constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],n=this.functionNode,i=n.getInputs(e),r=this.parameters;if(Array.isArray(r))for(let n=0;n(t=t.length>1||t[0]&&!0===t[0].isNode?Mg(t):Tg(t[0]),Sg(new VE(Sg(e),t)));Kf("call",zE),Pf("FunctionCallNode",VE);class GE extends Lf{constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new Vn,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:Ug()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Af(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?wf(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 kE=Eg(GE);Kf("scriptableValue",kE),Pf("ScriptableValueNode",GE);class HE extends Map{get(e,t=null,...n){if(this.has(e))return super.get(e);if(null!==t){const i=t(...n);return this.set(e,i),i}}}class WE{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 XE=new HE;class jE extends Lf{constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new HE,this._output=kE(),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 n=this._outputs;return void 0===n[e]?n[e]=kE(t):n[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const n=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),n[e]=t,n[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),n[e]=t,n[e].events.addEventListener("refresh",this.onRefresh)):void 0===n[e]?(n[e]=kE(t),n[e].events.addEventListener("refresh",this.onRefresh)):n[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 n=this.getObject()[e];if("function"==typeof n)return n(...t)}async callAsync(e,...t){const n=this.getObject()[e];if("function"==typeof n)return"AsyncFunction"===n.constructor.name?await n(...t):n(...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 WE(this),t=XE.get("THREE"),n=XE.get("TSL"),i=this.getMethod(this.codeNode),r=[e,this._local,XE,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,n];this._object=i(...r);const s=this._object.layout;if(s&&(!1===s.cache&&this._local.clear(),this._output.outputType=s.outputType||null,Array.isArray(s.elements)))for(const e of s.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:Ug()}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+" };",n="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],n),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()}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 qE=Eg(jE);Kf("scriptable",qE),Pf("ScriptableNode",jE);class YE extends Lf{constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}mixAssign(e){return this.mix(e,this.colorNode)}setup(){return this.factorNode}}const $E=Eg(YE);Kf("fog",$E),Pf("FogNode",YE);class ZE extends YE{constructor(e,t,n){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=n}setup(){return Bx(this.nearNode,this.farNode,bb.z.negate())}}const KE=Eg(ZE);Kf("rangeFog",KE),Pf("FogRangeNode",ZE);class JE extends YE{constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(){const e=bb.z.negate(),t=this.densityNode;return t.mul(t,e,e).negate().exp().oneMinus()}}const QE=Eg(JE);Kf("densityFog",QE),Pf("FogExp2Node",JE);let eA=null,tA=null;class nA extends Lf{constructor(e=Ug(),t=Ug()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Mf(this.minNode.value)),n=e.getTypeLength(Mf(this.maxNode.value));return t>n?t:n}getNodeType(e){return!0===e.object.isInstancedMesh?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let n=null;if(!0===t.isInstancedMesh){const i=this.minNode.value,r=this.maxNode.value,s=e.getTypeLength(Mf(i)),a=e.getTypeLength(Mf(r));eA=eA||new Ti,tA=tA||new Ti,eA.setScalar(0),tA.setScalar(0),1===s?eA.setScalar(i):i.isColor?eA.set(i.r,i.g,i.b):eA.set(i.x,i.y,i.z||0,i.w||0),1===a?tA.setScalar(r):r.isColor?tA.set(r.r,r.g,r.b):tA.set(r.x,r.y,r.z||0,r.w||0);const o=4,l=o*t.count,c=new Float32Array(l);for(let e=0;eSg(new rA(Sg(e),t,n));Kf("compute",sA),Pf("ComputeNode",rA);class aA extends Lf{constructor(e=aA.TARGET_DIRECTION,t=null){super(),this.scope=e,this.light=t}setup(){const{scope:e,light:t}=this;let n=null;return e===aA.TARGET_DIRECTION&&(n=Sy.transformDirection(my(t).sub(my(t.target)))),n}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}aA.TARGET_DIRECTION="targetDirection";const oA=Eg(aA,aA.TARGET_DIRECTION);Pf("LightNode",aA);const lA=Rg((e=>{const{lightDistance:t,cutoffDistance:n,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return n.greaterThan(0).cond(r.mul(t.div(n).pow4().oneMinus().clamp().pow2()),r)}));class cA extends eS{constructor(e=null){super(e),this.cutoffDistanceNode=u_(0),this.decayExponentNode=u_(0)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=e.context.lightingModel,a=gy(r).sub(bb),o=a.normalize(),l=a.length(),c=lA({lightDistance:l,cutoffDistance:n,decayExponent:i}),u=t.mul(c),h=e.context.reflectedLight;s.direct({lightDirection:o,lightColor:u,reflectedLight:h},e.stack,e)}}Pf("PointLightNode",cA),sS(np,cA);class uA extends eS{constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,n=this.colorNode,i=oA(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:n,reflectedLight:r},e.stack,e)}}Pf("DirectionalLightNode",uA),sS(rp,uA);class hA extends eS{constructor(e=null){super(e),this.coneCosNode=u_(0),this.penumbraCosNode=u_(0),this.cutoffDistanceNode=u_(0),this.decayExponentNode=u_(0)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e){const{coneCosNode:t,penumbraCosNode:n}=this;return Bx(t,n,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:n,cutoffDistanceNode:i,decayExponentNode:r,light:s}=this,a=gy(s).sub(bb),o=a.normalize(),l=o.dot(oA(s)),c=this.getSpotAttenuation(l),u=a.length(),h=lA({lightDistance:u,cutoffDistance:i,decayExponent:r}),d=n.mul(c).mul(h),p=e.context.reflectedLight;t.direct({lightDirection:o,lightColor:d,reflectedLight:p},e.stack,e)}}Pf("SpotLightNode",hA),sS(Kd,hA);class dA extends hA{getSpotAttenuation(e){const t=this.light.iesMap;let n=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);n=ty(t,Bg(i,0),0).r}else n=super.getSpotAttenuation(e);return n}}Pf("IESSpotLightNode",dA),sS(class extends Kd{constructor(e,t,n,i,r,s){super(e,t,n,i,r,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}},dA);class pA extends eS{constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}Pf("AmbientLightNode",pA),sS(sp,pA);class mA extends eS{constructor(e=null){super(e),this.lightPositionNode=my(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=u_(new $r)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,r=Fy.dot(i).mul(.5).add(.5),s=Ux(n,t,r);e.context.irradiance.addAssign(s)}}Pf("HemisphereLightNode",mA),sS(Xd,mA);const fA=Rg((e=>{const t=e.uv.mul(2),n=t.x.floor(),i=t.y.floor();return n.add(i).mod(2).sign()}));class gA extends Hf{constructor(e=gv()){super("float"),this.uvNode=e}setup(){return fA({uv:this.uvNode})}}const _A=Eg(gA);Kf("checker",_A),Pf("CheckerNode",gA);class vA extends Ud{constructor(e){super(e),this.textures={}}load(e,t,n,i){const r=new Fd(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,(n=>{try{t(this.parse(JSON.parse(n)))}catch(t){i&&i(t),this.manager.itemError(e)}}),n,i)}parseNodes(e){const t={};if(void 0!==e){for(const n of e){const{uuid:e,type:i}=n;t[e]=Sg(If(i)),t[e].uuid=e}const n={nodes:t,textures:this.textures};for(const i of e){i.meta=n;t[i.uuid].deserialize(i),delete i.meta}}return t}parse(e){const t=Sg(If(e.type));t.uuid=e.uuid;const n={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=n,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}}const xA=new xu;class yA extends WS{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.setDefaultValues(xA),this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor;this.vertexNode=Rg((()=>{f_(Bg(),"vUv").assign(gv());const e=__("instancePosition"),t=z_("vec4","mvPos");t.assign(Ry.mul(jg(e,1)));const n=SS.z.div(SS.w),i=vy.mul(t),r=z_("vec2","offset");return r.assign(_b.xy),r.assign(r.mul(fb)),r.assign(r.div(SS.z)),r.y.assign(r.y.mul(n)),r.assign(r.mul(i.w)),i.assign(i.add(jg(r,0,0))),i}))(),this.fragmentNode=Rg((()=>{const n=f_(Bg(),"vUv"),i=z_("float","alpha");i.assign(1);const r=n.x,s=n.y,a=r.mul(r).add(s.mul(s));if(e){const e=z_("float","dlen");e.assign(a.fwidth()),i.assign(Bx(e.oneMinus(),e.add(1),a).oneMinus())}else a.greaterThan(1).discard();let o;if(this.pointColorNode)o=this.pointColorNode;else if(t){o=__("instanceColor").mul(Xy)}else o=Xy;return jg(o,i)}))(),this.needsUpdate=!0}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}XS("InstancedPointsNodeMaterial",yA);const bA=new lu;class SA extends WS{constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(bA),this.setValues(e)}}XS("LineBasicNodeMaterial",SA);const TA=new ud;class MA extends WS{constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(TA),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Ug(this.dashScaleNode):ub,n=this.dashSizeNode?Ug(this.dashSizeNode):hb,i=this.dashSizeNode?Ug(this.dashGapNode):db;tv.assign(n),nv.assign(i);const r=f_(__("lineDistance").mul(t));(e?r.add(e):r).mod(tv.add(nv)).greaterThan(tv).discard()}}XS("LineDashedNodeMaterial",MA);const EA=new ud;class AA extends WS{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.setDefaultValues(EA),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor,n=this.dashed,i=this.worldUnits,r=Rg((({start:e,end:t})=>{const n=vy.element(2).element(2),i=vy.element(3).element(2).mul(-.5).div(n).sub(e.z).div(t.z.sub(e.z));return jg(Ux(e.xyz,t.xyz,i),t.w)}));this.vertexNode=Rg((()=>{G_("vec2","vUv").assign(gv());const e=__("instanceStart"),t=__("instanceEnd"),s=z_("vec4","start"),a=z_("vec4","end");s.assign(Ry.mul(jg(e,1))),a.assign(Ry.mul(jg(t,1))),i&&(G_("vec3","worldStart").assign(s.xyz),G_("vec3","worldEnd").assign(a.xyz));const o=SS.z.div(SS.w),l=vy.element(2).element(3).equal(-1);Lg(l,(()=>{Lg(s.z.lessThan(0).and(a.z.greaterThan(0)),(()=>{a.assign(r({start:s,end:a}))})).elseif(a.z.lessThan(0).and(s.z.greaterThanEqual(0)),(()=>{s.assign(r({start:a,end:s}))}))}));const c=vy.mul(s),u=vy.mul(a),h=c.xyz.div(c.w),d=u.xyz.div(u.w),p=d.xy.sub(h.xy).temp();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const m=P_(jg());if(i){const e=a.xyz.sub(s.xyz).normalize(),t=Ux(s.xyz,a.xyz,.5).normalize(),i=e.cross(t).normalize(),r=e.cross(i),o=G_("vec4","worldPos");o.assign(_b.y.lessThan(.5).cond(s,a));const l=pb.mul(.5);o.addAssign(jg(_b.x.lessThan(0).cond(i.mul(l),i.mul(l).negate()),0)),n||(o.addAssign(jg(_b.y.lessThan(.5).cond(e.mul(l).negate(),e.mul(l)),0)),o.addAssign(jg(r.mul(l),0)),Lg(_b.y.greaterThan(1).or(_b.y.lessThan(0)),(()=>{o.subAssign(jg(r.mul(2).mul(l),0))}))),m.assign(vy.mul(o));const c=P_(kg());c.assign(_b.y.lessThan(.5).cond(h,d)),m.z.assign(c.z.mul(m.w))}else{const e=z_("vec2","offset");e.assign(Bg(p.y,p.x.negate())),p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(_b.x.lessThan(0).cond(e.negate(),e)),Lg(_b.y.lessThan(0),(()=>{e.assign(e.sub(p))})).elseif(_b.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(pb)),e.assign(e.div(SS.w)),m.assign(_b.y.lessThan(.5).cond(c,u)),e.assign(e.mul(m.w)),m.assign(m.add(jg(e,0,0)))}return m}))();const s=Rg((({p1:e,p2:t,p3:n,p4:i})=>{const r=e.sub(n),s=i.sub(n),a=t.sub(e),o=r.dot(s),l=s.dot(a),c=r.dot(a),u=s.dot(s),h=a.dot(a).mul(u).sub(l.mul(l)),d=o.mul(l).sub(c.mul(u)).div(h).clamp(),p=o.add(l.mul(d)).div(u).clamp();return Bg(d,p)}));this.fragmentNode=Rg((()=>{const r=G_("vec2","vUv");if(n){const e=this.offsetNode?Ug(this.offsetNodeNode):mb,t=this.dashScaleNode?Ug(this.dashScaleNode):ub,n=this.dashSizeNode?Ug(this.dashSizeNode):hb,i=this.dashSizeNode?Ug(this.dashGapNode):db;tv.assign(n),nv.assign(i);const s=__("instanceDistanceStart"),a=__("instanceDistanceEnd"),o=_b.y.lessThan(.5).cond(t.mul(s),ub.mul(a)),l=f_(o.add(mb)),c=e?l.add(e):l;r.y.lessThan(-1).or(r.y.greaterThan(1)).discard(),c.mod(tv.add(nv)).greaterThan(tv).discard()}const a=z_("float","alpha");if(a.assign(1),i){const t=G_("vec3","worldStart"),i=G_("vec3","worldEnd"),r=G_("vec4","worldPos").xyz.normalize().mul(1e5),o=i.sub(t),l=s({p1:t,p2:i,p3:kg(0,0,0),p4:r}),c=t.add(o.mul(l.x)),u=r.mul(l.y),h=c.sub(u).length().div(pb);if(!n)if(e){const e=h.fwidth();a.assign(Bx(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(e){const e=r.x,t=r.y.greaterThan(0).cond(r.y.sub(1),r.y.add(1)),n=e.mul(e).add(t.mul(t)),i=z_("float","dlen");i.assign(n.fwidth()),Lg(r.y.abs().greaterThan(1),(()=>{a.assign(Bx(i.oneMinus(),i.add(1),n).oneMinus())}))}else Lg(r.y.abs().greaterThan(1),(()=>{const e=r.x,t=r.y.greaterThan(0).cond(r.y.sub(1),r.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let o;if(this.lineColorNode)o=this.lineColorNode;else if(t){const e=__("instanceColorStart"),t=__("instanceColorEnd");o=_b.y.lessThan(.5).cond(e,t).mul(Xy)}else o=Xy;return jg(o,a)}))(),this.needsUpdate=!0}get worldUnits(){return this.useWorldUnits}set worldUnits(e){this.useWorldUnits!==e&&(this.useWorldUnits=e,this.setupShaders())}get dashed(){return this.useDash}set dashed(e){this.useDash!==e&&(this.useDash=e,this.setupShaders())}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}XS("Line2NodeMaterial",AA);const wA=new od;class RA extends WS{constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.colorSpaced=!1,this.setDefaultValues(wA),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Ug(this.opacityNode):Yy;k_.assign(jg(qT(Vy),e))}}XS("MeshNormalNodeMaterial",RA);const CA=new Qr;class NA extends WS{constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(CA),this.setValues(e)}}XS("MeshBasicNodeMaterial",NA);const LA=Rg((({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),PA=Rg((e=>e.diffuseColor.mul(1/Math.PI))),IA=Rg((({dotNH:e})=>Q_.mul(.5/Math.PI).add(1).mul(e.pow(Q_)))),UA=Rg((({lightDirection:e})=>{const t=e.add(Sb).normalize(),n=Vy.dot(t).clamp(),i=Sb.dot(t).clamp(),r=LA({f0:J_,f90:1,dotVH:i}),s=Ug(.25),a=IA({dotNH:n});return r.mul(s).mul(a)}));class OA extends N_{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Vy.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(PA({diffuseColor:k_.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(UA({lightDirection:e})).mul(Zy))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(PA({diffuseColor:k_})))}}const DA=new ld;class FA extends WS{constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(DA),this.setValues(e)}setupLightingModel(){return new OA(!1)}}XS("MeshLambertNodeMaterial",FA);const BA=new sd;class VA extends WS{constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(BA),this.setValues(e)}setupLightingModel(){return new OA}setupVariants(){const e=(this.shininessNode?Ug(this.shininessNode):jy).max(1e-4);Q_.assign(e);const t=this.specularNode||$y;J_.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}XS("MeshPhongNodeMaterial",VA);const zA=Rg((()=>{const e=Oy.dFdx().abs().max(Oy.dFdy().abs());return e.x.max(e.y).max(e.z)})),GA=Rg((e=>{const{roughness:t}=e,n=zA();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i})),kA=Rg((e=>{const{alpha:t,dotNL:n,dotNV:i}=e,r=t.pow2(),s=n.mul(r.add(r.oneMinus().mul(i.pow2())).sqrt()),a=i.mul(r.add(r.oneMinus().mul(n.pow2())).sqrt());return Tv(.5,s.add(a).max(zv))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),HA=Rg((({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),WA=Rg((e=>{const{lightDirection:t,f0:n,f90:i,roughness:r,iridescenceFresnel:s}=e,a=e.normalView||Vy,o=r.pow2(),l=t.add(Sb).normalize(),c=a.dot(t).clamp(),u=a.dot(Sb).clamp(),h=a.dot(l).clamp(),d=Sb.dot(l).clamp();let p=LA({f0:n,f90:i,dotVH:d});s&&(p=$_.mix(p,s));const m=kA({alpha:o,dotNL:c,dotNV:u}),f=HA({alpha:o,dotNH:h});return p.mul(m).mul(f)})),XA=Rg((({roughness:e,dotNV:t})=>{const n=jg(-1,-.0275,-.572,.022),i=jg(1,.0425,1.04,-.04),r=e.mul(n).add(i),s=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return Bg(-1.04,1.04).mul(s).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),jA=Rg((e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=XA({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))})),qA=Rg((({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub(kg(t).mul(s)).div(s.oneMinus())})).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),YA=Rg((({roughness:e,dotNH:t})=>{const n=e.pow2(),i=Ug(1).div(n),r=t.pow2().oneMinus().max(.0078125);return Ug(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),$A=Rg((({dotNV:e,dotNL:t})=>Ug(1).div(Ug(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),ZA=Rg((({lightDirection:e})=>{const t=e.add(Sb).normalize(),n=Vy.dot(e).clamp(),i=Vy.dot(Sb).clamp(),r=Vy.dot(t).clamp(),s=YA({roughness:Y_,dotNH:r}),a=$A({dotNV:i,dotNL:n});return q_.mul(s).mul(a)})),KA=Zg(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),JA=(e,t)=>e.sub(t).div(e.add(t)).pow2(),QA=(e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=kg(54856e-17,44201e-17,52481e-17),r=kg(1681e3,1795300,2208400),s=kg(43278e5,93046e5,66121e5),a=Ug(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());o=kg(o.x.add(a),o.y,o.z).div(1.0685e-7);return KA.mul(o)},ew=Rg((({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=Ux(e,t,Bx(0,.03,i)),a=e.div(s).pow2().mul(Ug(1).sub(n.pow2())),o=Ug(1).sub(a).sqrt(),l=JA(s,e),c=LA({f0:l,f90:1,dotVH:n}),u=c.oneMinus(),h=s.lessThan(e).cond(Math.PI,0),d=Ug(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return kg(1).add(t).div(kg(1).sub(t))})(r.clamp(0,.9999)),m=JA(p,s.vec3()),f=LA({f0:m,f90:1,dotVH:o}),g=kg(p.x.lessThan(s).cond(Math.PI,0),p.y.lessThan(s).cond(Math.PI,0),p.z.lessThan(s).cond(Math.PI,0)),_=s.mul(i,o,2),v=kg(d).add(g),x=c.mul(f).clamp(1e-5,.9999),y=x.sqrt(),b=u.pow2().mul(f).div(kg(1).sub(x));let S=c.add(b),T=b.sub(u);for(let e=1;e<=2;++e){T=T.mul(y);const t=QA(Ug(e).mul(_),Ug(e).mul(v)).mul(2);S=S.add(T.mul(t))}return S.max(kg(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"}]}),tw=Rg((({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.pow2(),s=cT(n.lessThan(.25),Ug(-339.2).mul(r).add(Ug(161.4).mul(n)).sub(25.9),Ug(-8.48).mul(r).add(Ug(14.3).mul(n)).sub(9.95)),a=cT(n.lessThan(.25),Ug(44).mul(r).sub(Ug(23.7).mul(n)).add(3.26),Ug(1.97).mul(r).sub(Ug(3.27).mul(n)).add(.72));return cT(n.lessThan(.25),0,Ug(.1).mul(n).sub(.025)).add(s.mul(i).add(a).exp()).mul(1/Math.PI).saturate()})),nw=kg(.04),iw=kg(1);class rw extends N_{constructor(e=!1,t=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(){if(!0===this.clearcoat&&(this.clearcoatRadiance=kg().temp("clearcoatRadiance"),this.clearcoatSpecularDirect=kg().temp("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=kg().temp("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=kg().temp("sheenSpecularDirect"),this.sheenSpecularIndirect=kg().temp("sheenSpecularIndirect")),!0===this.iridescence){const e=Vy.dot(Sb).clamp();this.iridescenceFresnel=ew({outsideIOR:Ug(1),eta2:Z_,cosTheta1:e,thinFilmThickness:K_,baseF0:J_}),this.iridescenceF0=qA({f:this.iridescenceFresnel,f90:1,dotVH:e})}}computeMultiscattering(e,t,n=Ug(1)){const i=Vy.dot(Sb).clamp(),r=XA({roughness:H_,dotNV:i}),s=(this.iridescenceF0?$_.mix(J_,this.iridescenceF0):J_).mul(r.x).add(n.mul(r.y)),a=r.x.add(r.y).oneMinus(),o=J_.add(J_.oneMinus().mul(.047619)),l=s.mul(o).div(a.mul(o).oneMinus());e.addAssign(s),t.addAssign(l.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Vy.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(ZA({lightDirection:e}))),!0===this.clearcoat){const n=Gy.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(WA({lightDirection:e,f0:nw,f90:iw,roughness:j_,normalView:Gy})))}n.directDiffuse.addAssign(i.mul(PA({diffuseColor:k_.rgb}))),n.directSpecular.addAssign(i.mul(WA({lightDirection:e,f0:J_,f90:1,roughness:H_,iridescence:this.iridescence,iridescenceFresnel:this.iridescenceFresnel})))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(PA({diffuseColor:k_})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:n}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(q_,tw({normal:Vy,viewDir:Sb,roughness:Y_}))),!0===this.clearcoat){const e=Gy.dot(Sb).clamp(),t=jA({dotNV:e,specularColor:nw,specularF90:iw,roughness:j_});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=kg().temp("singleScattering"),r=kg().temp("multiScattering"),s=t.mul(1/Math.PI);this.computeMultiscattering(i,r);const a=i.add(r),o=k_.mul(a.r.max(a.g).max(a.b).oneMinus());n.indirectSpecular.addAssign(e.mul(i)),n.indirectSpecular.addAssign(r.mul(s)),n.indirectDiffuse.addAssign(o.mul(s))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const n=Vy.dot(Sb).clamp().add(e),i=H_.mul(-16).oneMinus().negate().exp2(),r=e.sub(n.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Gy.dot(Sb).clamp(),n=LA({dotVH:e,f0:nw,f90:iw}),i=t.mul(X_.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(X_));t.assign(i)}if(!0===this.sheen){const e=q_.r.max(q_.g).max(q_.b).mul(.157).oneMinus(),n=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const sw=new id;class aw extends WS{constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(sw),this.setValues(e)}setupLightingModel(){return new rw}setupVariants(){const e=this.metalnessNode?Ug(this.metalnessNode):Qy;W_.assign(e);let t=this.roughnessNode?Ug(this.roughnessNode):Jy;t=GA({roughness:t}),H_.assign(t);const n=Ux(kg(.04),k_.rgb,e);J_.assign(n),k_.assign(jg(k_.rgb.mul(e.oneMinus()),k_.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}XS("MeshStandardNodeMaterial",aw);const ow=new rd;class lw extends aw{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.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.setDefaultValues(ow),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}setupLightingModel(){return new rw(this.useClearcoat,this.useSheen,this.useIridescence)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Ug(this.clearcoatNode):tb,t=this.clearcoatRoughnessNode?Ug(this.clearcoatRoughnessNode):nb;X_.assign(e),j_.assign(t)}if(this.useSheen){const e=this.sheenNode?kg(this.sheenNode):sb,t=this.sheenRoughnessNode?Ug(this.sheenRoughnessNode):ab;q_.assign(e),Y_.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Ug(this.iridescenceNode):ob,t=this.iridescenceIORNode?Ug(this.iridescenceIORNode):lb,n=this.iridescenceThicknessNode?Ug(this.iridescenceThicknessNode):cb;$_.assign(e),Z_.assign(t),K_.assign(n)}}setupNormal(e){super.setupNormal(e);const t=this.clearcoatNormalNode?kg(this.clearcoatNormalNode):ib;Gy.assign(t)}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,super.copy(e)}}XS("MeshPhysicalNodeMaterial",lw);class cw extends rw{constructor(e,t,n,i){super(e,t,n),this.useSSS=i}direct({lightDirection:e,lightColor:t,reflectedLight:n},i,r){if(!0===this.useSSS){const i=r.material,{thicknessColorNode:s,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:l,thicknessPowerNode:c,thicknessScaleNode:u}=i,h=e.add(Vy.mul(a)).normalize(),d=Ug(Sb.dot(h.negate()).saturate().pow(c).mul(u)),p=kg(d.add(o).mul(s));n.directDiffuse.addAssign(p.mul(l.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:n},i,r)}}class uw extends lw{constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Ug(.1),this.thicknessAmbientNode=Ug(0),this.thicknessAttenuationNode=Ug(.1),this.thicknessPowerNode=Ug(2),this.thicknessScaleNode=Ug(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new cw(this.useClearcoat,this.useSheen,this.useIridescence,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)}}XS("MeshSSSNodeMaterial",uw);const hw=new xu;class dw extends WS{constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.normals=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(hw),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}XS("PointsNodeMaterial",dw);const pw=new nc;class mw extends WS{constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this.normals=!1,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(pw),this.setValues(e)}setupPosition({object:e,context:t}){const{positionNode:n,rotationNode:i,scaleNode:r}=this,s=vb;let a=Ry.mul(kg(n||0)),o=Bg(Ny[0].xyz.length(),Ny[1].xyz.length());null!==r&&(o=o.mul(r));let l=s.xy;e.center&&!0===e.center.isVector2&&(l=l.sub(u_(e.center).sub(.5))),l=l.mul(o);const c=Ug(i||rb),u=c.cos(),h=c.sin(),d=Bg(Bg(u,h.negate()).dot(l),Bg(h,u).dot(l));a=jg(a.xy.add(d),a.zw);const p=vy.mul(a);return t.vertex=s,p}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}}XS("SpriteNodeMaterial",mw);const fw=cp.createMaterialFromType;cp.createMaterialFromType=function(e){const t=jS(e);return void 0!==t?t:fw.call(this,e)};class gw extends cp{constructor(e){super(e),this.nodes={}}parse(e){const t=super.parse(e),n=this.nodes,i=e.inputNodes;for(const e in i){const r=i[e];t[e]=n[r]}return t}setNodes(e){return this.nodes=e,this}}class _w extends pp{constructor(e){super(e),this._nodesJSON=null}parse(e,t){this._nodesJSON=e.nodes;const n=super.parse(e,t);return this._nodesJSON=null,n}parseNodes(e,t){if(void 0!==e){const n=new vA;return n.setTextures(t),n.parseNodes(e)}return{}}parseMaterials(e,t){const n={};if(void 0!==e){const i=this.parseNodes(this._nodesJSON,t),r=new gw;r.setTextures(t),r.setNodes(i);for(let t=0,i=e.length;t{const t=(e=e.trim()).indexOf(Sw),n=-1!==t?e.slice(t+12):e,i=n.match(yw);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=bw.exec(r));)s.push(a);const o=[];let l=0;for(;l{const i=Ug(n).toVar(),r=Ug(t).toVar(),s=Fg(e).toVar();return cT(s,r,i)})),Aw=Rg((([e,t])=>{const n=Fg(t).toVar(),i=Ug(e).toVar();return cT(n,i.negate(),i)})),ww=Rg((([e])=>{const t=Ug(e).toVar();return Og(Zv(t))})),Rw=Rg((([e,t])=>{const n=Ug(e).toVar();return t.assign(ww(n)),n.sub(Ug(t))})),Cw=Rg((([e,t,n,i,r,s])=>{const a=Ug(s).toVar(),o=Ug(r).toVar(),l=Ug(i).toVar(),c=Ug(n).toVar(),u=Ug(t).toVar(),h=Ug(e).toVar(),d=Ug(bv(1,o)).toVar();return bv(1,a).mul(h.mul(d).add(u.mul(o))).add(a.mul(c.mul(d).add(l.mul(o))))})),Nw=Rg((([e,t,n,i,r,s])=>{const a=Ug(s).toVar(),o=Ug(r).toVar(),l=kg(i).toVar(),c=kg(n).toVar(),u=kg(t).toVar(),h=kg(e).toVar(),d=Ug(bv(1,o)).toVar();return bv(1,a).mul(h.mul(d).add(u.mul(o))).add(a.mul(c.mul(d).add(l.mul(o))))})),Lw=LT([Cw,Nw]),Pw=Rg((([e,t,n,i,r,s,a,o,l,c,u])=>{const h=Ug(u).toVar(),d=Ug(c).toVar(),p=Ug(l).toVar(),m=Ug(o).toVar(),f=Ug(a).toVar(),g=Ug(s).toVar(),_=Ug(r).toVar(),v=Ug(i).toVar(),x=Ug(n).toVar(),y=Ug(t).toVar(),b=Ug(e).toVar(),S=Ug(bv(1,p)).toVar(),T=Ug(bv(1,d)).toVar();return Ug(bv(1,h)).toVar().mul(T.mul(b.mul(S).add(y.mul(p))).add(d.mul(x.mul(S).add(v.mul(p))))).add(h.mul(T.mul(_.mul(S).add(g.mul(p))).add(d.mul(f.mul(S).add(m.mul(p))))))})),Iw=Rg((([e,t,n,i,r,s,a,o,l,c,u])=>{const h=Ug(u).toVar(),d=Ug(c).toVar(),p=Ug(l).toVar(),m=kg(o).toVar(),f=kg(a).toVar(),g=kg(s).toVar(),_=kg(r).toVar(),v=kg(i).toVar(),x=kg(n).toVar(),y=kg(t).toVar(),b=kg(e).toVar(),S=Ug(bv(1,p)).toVar(),T=Ug(bv(1,d)).toVar();return Ug(bv(1,h)).toVar().mul(T.mul(b.mul(S).add(y.mul(p))).add(d.mul(x.mul(S).add(v.mul(p))))).add(h.mul(T.mul(_.mul(S).add(g.mul(p))).add(d.mul(f.mul(S).add(m.mul(p))))))})),Uw=LT([Pw,Iw]),Ow=Rg((([e,t,n])=>{const i=Ug(n).toVar(),r=Ug(t).toVar(),s=Dg(e).toVar(),a=Dg(s.bitAnd(Dg(7))).toVar(),o=Ug(Ew(a.lessThan(Dg(4)),r,i)).toVar(),l=Ug(Sv(2,Ew(a.lessThan(Dg(4)),i,r))).toVar();return Aw(o,Fg(a.bitAnd(Dg(1)))).add(Aw(l,Fg(a.bitAnd(Dg(2)))))})),Dw=Rg((([e,t,n,i])=>{const r=Ug(i).toVar(),s=Ug(n).toVar(),a=Ug(t).toVar(),o=Dg(e).toVar(),l=Dg(o.bitAnd(Dg(15))).toVar(),c=Ug(Ew(l.lessThan(Dg(8)),a,s)).toVar(),u=Ug(Ew(l.lessThan(Dg(4)),s,Ew(l.equal(Dg(12)).or(l.equal(Dg(14))),a,r))).toVar();return Aw(c,Fg(l.bitAnd(Dg(1)))).add(Aw(u,Fg(l.bitAnd(Dg(2)))))})),Fw=LT([Ow,Dw]),Bw=Rg((([e,t,n])=>{const i=Ug(n).toVar(),r=Ug(t).toVar(),s=Wg(e).toVar();return kg(Fw(s.x,r,i),Fw(s.y,r,i),Fw(s.z,r,i))})),Vw=Rg((([e,t,n,i])=>{const r=Ug(i).toVar(),s=Ug(n).toVar(),a=Ug(t).toVar(),o=Wg(e).toVar();return kg(Fw(o.x,a,s,r),Fw(o.y,a,s,r),Fw(o.z,a,s,r))})),zw=LT([Bw,Vw]),Gw=Rg((([e])=>{const t=Ug(e).toVar();return Sv(.6616,t)})),kw=Rg((([e])=>{const t=Ug(e).toVar();return Sv(.982,t)})),Hw=Rg((([e])=>{const t=kg(e).toVar();return Sv(.6616,t)})),Ww=LT([Gw,Hw]),Xw=Rg((([e])=>{const t=kg(e).toVar();return Sv(.982,t)})),jw=LT([kw,Xw]),qw=Rg((([e,t])=>{const n=Og(t).toVar(),i=Dg(e).toVar();return i.shiftLeft(n).bitOr(i.shiftRight(Og(32).sub(n)))})),Yw=Rg((([e,t,n])=>{e.subAssign(n),e.bitXorAssign(qw(n,Og(4))),n.addAssign(t),t.subAssign(e),t.bitXorAssign(qw(e,Og(6))),e.addAssign(n),n.subAssign(t),n.bitXorAssign(qw(t,Og(8))),t.addAssign(e),e.subAssign(n),e.bitXorAssign(qw(n,Og(16))),n.addAssign(t),t.subAssign(e),t.bitXorAssign(qw(e,Og(19))),e.addAssign(n),n.subAssign(t),n.bitXorAssign(qw(t,Og(4))),t.addAssign(e)})),$w=Rg((([e,t,n])=>{const i=Dg(n).toVar(),r=Dg(t).toVar(),s=Dg(e).toVar();return i.bitXorAssign(r),i.subAssign(qw(r,Og(14))),s.bitXorAssign(i),s.subAssign(qw(i,Og(11))),r.bitXorAssign(s),r.subAssign(qw(s,Og(25))),i.bitXorAssign(r),i.subAssign(qw(r,Og(16))),s.bitXorAssign(i),s.subAssign(qw(i,Og(4))),r.bitXorAssign(s),r.subAssign(qw(s,Og(14))),i.bitXorAssign(r),i.subAssign(qw(r,Og(24))),i})),Zw=Rg((([e])=>{const t=Dg(e).toVar();return Ug(t).div(Ug(Dg(Og(4294967295))))})),Kw=Rg((([e])=>{const t=Ug(e).toVar();return t.mul(t.mul(t.mul(t.mul(t.mul(6).sub(15)).add(10))))})),Jw=Rg((([e])=>{const t=Og(e).toVar(),n=Dg(Dg(1)).toVar(),i=Dg(Dg(Og(3735928559)).add(n.shiftLeft(Dg(2)).add(Dg(13)))).toVar();return $w(i.add(Dg(t)),i,i)})),Qw=Rg((([e,t])=>{const n=Og(t).toVar(),i=Og(e).toVar(),r=Dg(Dg(2)).toVar(),s=Dg().toVar(),a=Dg().toVar(),o=Dg().toVar();return s.assign(a.assign(o.assign(Dg(Og(3735928559)).add(r.shiftLeft(Dg(2)).add(Dg(13)))))),s.addAssign(Dg(i)),a.addAssign(Dg(n)),$w(s,a,o)})),eR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Og(t).toVar(),s=Og(e).toVar(),a=Dg(Dg(3)).toVar(),o=Dg().toVar(),l=Dg().toVar(),c=Dg().toVar();return o.assign(l.assign(c.assign(Dg(Og(3735928559)).add(a.shiftLeft(Dg(2)).add(Dg(13)))))),o.addAssign(Dg(s)),l.addAssign(Dg(r)),c.addAssign(Dg(i)),$w(o,l,c)})),tR=Rg((([e,t,n,i])=>{const r=Og(i).toVar(),s=Og(n).toVar(),a=Og(t).toVar(),o=Og(e).toVar(),l=Dg(Dg(4)).toVar(),c=Dg().toVar(),u=Dg().toVar(),h=Dg().toVar();return c.assign(u.assign(h.assign(Dg(Og(3735928559)).add(l.shiftLeft(Dg(2)).add(Dg(13)))))),c.addAssign(Dg(o)),u.addAssign(Dg(a)),h.addAssign(Dg(s)),Yw(c,u,h),c.addAssign(Dg(r)),$w(c,u,h)})),nR=Rg((([e,t,n,i,r])=>{const s=Og(r).toVar(),a=Og(i).toVar(),o=Og(n).toVar(),l=Og(t).toVar(),c=Og(e).toVar(),u=Dg(Dg(5)).toVar(),h=Dg().toVar(),d=Dg().toVar(),p=Dg().toVar();return h.assign(d.assign(p.assign(Dg(Og(3735928559)).add(u.shiftLeft(Dg(2)).add(Dg(13)))))),h.addAssign(Dg(c)),d.addAssign(Dg(l)),p.addAssign(Dg(o)),Yw(h,d,p),h.addAssign(Dg(a)),d.addAssign(Dg(s)),$w(h,d,p)})),iR=LT([Jw,Qw,eR,tR,nR]),rR=Rg((([e,t])=>{const n=Og(t).toVar(),i=Og(e).toVar(),r=Dg(iR(i,n)).toVar(),s=Wg().toVar();return s.x.assign(r.bitAnd(Og(255))),s.y.assign(r.shiftRight(Og(8)).bitAnd(Og(255))),s.z.assign(r.shiftRight(Og(16)).bitAnd(Og(255))),s})),sR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Og(t).toVar(),s=Og(e).toVar(),a=Dg(iR(s,r,i)).toVar(),o=Wg().toVar();return o.x.assign(a.bitAnd(Og(255))),o.y.assign(a.shiftRight(Og(8)).bitAnd(Og(255))),o.z.assign(a.shiftRight(Og(16)).bitAnd(Og(255))),o})),aR=LT([rR,sR]),oR=Rg((([e])=>{const t=Bg(e).toVar(),n=Og().toVar(),i=Og().toVar(),r=Ug(Rw(t.x,n)).toVar(),s=Ug(Rw(t.y,i)).toVar(),a=Ug(Kw(r)).toVar(),o=Ug(Kw(s)).toVar(),l=Ug(Lw(Fw(iR(n,i),r,s),Fw(iR(n.add(Og(1)),i),r.sub(1),s),Fw(iR(n,i.add(Og(1))),r,s.sub(1)),Fw(iR(n.add(Og(1)),i.add(Og(1))),r.sub(1),s.sub(1)),a,o)).toVar();return Ww(l)})),lR=Rg((([e])=>{const t=kg(e).toVar(),n=Og().toVar(),i=Og().toVar(),r=Og().toVar(),s=Ug(Rw(t.x,n)).toVar(),a=Ug(Rw(t.y,i)).toVar(),o=Ug(Rw(t.z,r)).toVar(),l=Ug(Kw(s)).toVar(),c=Ug(Kw(a)).toVar(),u=Ug(Kw(o)).toVar(),h=Ug(Uw(Fw(iR(n,i,r),s,a,o),Fw(iR(n.add(Og(1)),i,r),s.sub(1),a,o),Fw(iR(n,i.add(Og(1)),r),s,a.sub(1),o),Fw(iR(n.add(Og(1)),i.add(Og(1)),r),s.sub(1),a.sub(1),o),Fw(iR(n,i,r.add(Og(1))),s,a,o.sub(1)),Fw(iR(n.add(Og(1)),i,r.add(Og(1))),s.sub(1),a,o.sub(1)),Fw(iR(n,i.add(Og(1)),r.add(Og(1))),s,a.sub(1),o.sub(1)),Fw(iR(n.add(Og(1)),i.add(Og(1)),r.add(Og(1))),s.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return jw(h)})),cR=LT([oR,lR]),uR=Rg((([e])=>{const t=Bg(e).toVar(),n=Og().toVar(),i=Og().toVar(),r=Ug(Rw(t.x,n)).toVar(),s=Ug(Rw(t.y,i)).toVar(),a=Ug(Kw(r)).toVar(),o=Ug(Kw(s)).toVar(),l=kg(Lw(zw(aR(n,i),r,s),zw(aR(n.add(Og(1)),i),r.sub(1),s),zw(aR(n,i.add(Og(1))),r,s.sub(1)),zw(aR(n.add(Og(1)),i.add(Og(1))),r.sub(1),s.sub(1)),a,o)).toVar();return Ww(l)})),hR=Rg((([e])=>{const t=kg(e).toVar(),n=Og().toVar(),i=Og().toVar(),r=Og().toVar(),s=Ug(Rw(t.x,n)).toVar(),a=Ug(Rw(t.y,i)).toVar(),o=Ug(Rw(t.z,r)).toVar(),l=Ug(Kw(s)).toVar(),c=Ug(Kw(a)).toVar(),u=Ug(Kw(o)).toVar(),h=kg(Uw(zw(aR(n,i,r),s,a,o),zw(aR(n.add(Og(1)),i,r),s.sub(1),a,o),zw(aR(n,i.add(Og(1)),r),s,a.sub(1),o),zw(aR(n.add(Og(1)),i.add(Og(1)),r),s.sub(1),a.sub(1),o),zw(aR(n,i,r.add(Og(1))),s,a,o.sub(1)),zw(aR(n.add(Og(1)),i,r.add(Og(1))),s.sub(1),a,o.sub(1)),zw(aR(n,i.add(Og(1)),r.add(Og(1))),s,a.sub(1),o.sub(1)),zw(aR(n.add(Og(1)),i.add(Og(1)),r.add(Og(1))),s.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return jw(h)})),dR=LT([uR,hR]),pR=Rg((([e])=>{const t=Ug(e).toVar(),n=Og(ww(t)).toVar();return Zw(iR(n))})),mR=Rg((([e])=>{const t=Bg(e).toVar(),n=Og(ww(t.x)).toVar(),i=Og(ww(t.y)).toVar();return Zw(iR(n,i))})),fR=Rg((([e])=>{const t=kg(e).toVar(),n=Og(ww(t.x)).toVar(),i=Og(ww(t.y)).toVar(),r=Og(ww(t.z)).toVar();return Zw(iR(n,i,r))})),gR=Rg((([e])=>{const t=jg(e).toVar(),n=Og(ww(t.x)).toVar(),i=Og(ww(t.y)).toVar(),r=Og(ww(t.z)).toVar(),s=Og(ww(t.w)).toVar();return Zw(iR(n,i,r,s))})),_R=LT([pR,mR,fR,gR]),vR=Rg((([e])=>{const t=Ug(e).toVar(),n=Og(ww(t)).toVar();return kg(Zw(iR(n,Og(0))),Zw(iR(n,Og(1))),Zw(iR(n,Og(2))))})),xR=Rg((([e])=>{const t=Bg(e).toVar(),n=Og(ww(t.x)).toVar(),i=Og(ww(t.y)).toVar();return kg(Zw(iR(n,i,Og(0))),Zw(iR(n,i,Og(1))),Zw(iR(n,i,Og(2))))})),yR=Rg((([e])=>{const t=kg(e).toVar(),n=Og(ww(t.x)).toVar(),i=Og(ww(t.y)).toVar(),r=Og(ww(t.z)).toVar();return kg(Zw(iR(n,i,r,Og(0))),Zw(iR(n,i,r,Og(1))),Zw(iR(n,i,r,Og(2))))})),bR=Rg((([e])=>{const t=jg(e).toVar(),n=Og(ww(t.x)).toVar(),i=Og(ww(t.y)).toVar(),r=Og(ww(t.z)).toVar(),s=Og(ww(t.w)).toVar();return kg(Zw(iR(n,i,r,s,Og(0))),Zw(iR(n,i,r,s,Og(1))),Zw(iR(n,i,r,s,Og(2))))})),SR=LT([vR,xR,yR,bR]),TR=Rg((([e,t,n,i])=>{const r=Ug(i).toVar(),s=Ug(n).toVar(),a=Og(t).toVar(),o=kg(e).toVar(),l=Ug(0).toVar(),c=Ug(1).toVar();return IT({start:Og(0),end:a},(({i:e})=>{l.addAssign(c.mul(cR(o))),c.mulAssign(r),o.mulAssign(s)})),l})),MR=Rg((([e,t,n,i])=>{const r=Ug(i).toVar(),s=Ug(n).toVar(),a=Og(t).toVar(),o=kg(e).toVar(),l=kg(0).toVar(),c=Ug(1).toVar();return IT({start:Og(0),end:a},(({i:e})=>{l.addAssign(c.mul(dR(o))),c.mulAssign(r),o.mulAssign(s)})),l})),ER=Rg((([e,t,n,i])=>{const r=Ug(i).toVar(),s=Ug(n).toVar(),a=Og(t).toVar(),o=kg(e).toVar();return Bg(TR(o,a,s,r),TR(o.add(kg(Og(19),Og(193),Og(17))),a,s,r))})),AR=Rg((([e,t,n,i])=>{const r=Ug(i).toVar(),s=Ug(n).toVar(),a=Og(t).toVar(),o=kg(e).toVar(),l=kg(MR(o,a,s,r)).toVar(),c=Ug(TR(o.add(kg(Og(19),Og(193),Og(17))),a,s,r)).toVar();return jg(l,c)})),wR=Rg((([e,t,n,i,r,s,a])=>{const o=Og(a).toVar(),l=Ug(s).toVar(),c=Og(r).toVar(),u=Og(i).toVar(),h=Og(n).toVar(),d=Og(t).toVar(),p=Bg(e).toVar(),m=kg(SR(Bg(d.add(u),h.add(c)))).toVar(),f=Bg(m.x,m.y).toVar();f.subAssign(.5),f.mulAssign(l),f.addAssign(.5);const g=Bg(Bg(Ug(d),Ug(h)).add(f)).toVar(),_=Bg(g.sub(p)).toVar();return Lg(o.equal(Og(2)),(()=>ax(_.x).add(ax(_.y)))),Lg(o.equal(Og(3)),(()=>yx(ax(_.x),ax(_.y)))),Ax(_,_)})),RR=Rg((([e,t,n,i,r,s,a,o,l])=>{const c=Og(l).toVar(),u=Ug(o).toVar(),h=Og(a).toVar(),d=Og(s).toVar(),p=Og(r).toVar(),m=Og(i).toVar(),f=Og(n).toVar(),g=Og(t).toVar(),_=kg(e).toVar(),v=kg(SR(kg(g.add(p),f.add(d),m.add(h)))).toVar();v.subAssign(.5),v.mulAssign(u),v.addAssign(.5);const x=kg(kg(Ug(g),Ug(f),Ug(m)).add(v)).toVar(),y=kg(x.sub(_)).toVar();return Lg(c.equal(Og(2)),(()=>ax(y.x).add(ax(y.y).add(ax(y.z))))),Lg(c.equal(Og(3)),(()=>yx(yx(ax(y.x),ax(y.y)),ax(y.z)))),Ax(y,y)})),CR=LT([wR,RR]),NR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Ug(t).toVar(),s=Bg(e).toVar(),a=Og().toVar(),o=Og().toVar(),l=Bg(Rw(s.x,a),Rw(s.y,o)).toVar(),c=Ug(1e6).toVar();return IT({start:-1,end:Og(1),name:"x",condition:"<="},(({x:e})=>{IT({start:-1,end:Og(1),name:"y",condition:"<="},(({y:t})=>{const n=Ug(CR(l,e,t,a,o,r,i)).toVar();c.assign(xx(c,n))}))})),Lg(i.equal(Og(0)),(()=>{c.assign(Yv(c))})),c})),LR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Ug(t).toVar(),s=Bg(e).toVar(),a=Og().toVar(),o=Og().toVar(),l=Bg(Rw(s.x,a),Rw(s.y,o)).toVar(),c=Bg(1e6,1e6).toVar();return IT({start:-1,end:Og(1),name:"x",condition:"<="},(({x:e})=>{IT({start:-1,end:Og(1),name:"y",condition:"<="},(({y:t})=>{const n=Ug(CR(l,e,t,a,o,r,i)).toVar();Lg(n.lessThan(c.x),(()=>{c.y.assign(c.x),c.x.assign(n)})).elseif(n.lessThan(c.y),(()=>{c.y.assign(n)}))}))})),Lg(i.equal(Og(0)),(()=>{c.assign(Yv(c))})),c})),PR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Ug(t).toVar(),s=Bg(e).toVar(),a=Og().toVar(),o=Og().toVar(),l=Bg(Rw(s.x,a),Rw(s.y,o)).toVar(),c=kg(1e6,1e6,1e6).toVar();return IT({start:-1,end:Og(1),name:"x",condition:"<="},(({x:e})=>{IT({start:-1,end:Og(1),name:"y",condition:"<="},(({y:t})=>{const n=Ug(CR(l,e,t,a,o,r,i)).toVar();Lg(n.lessThan(c.x),(()=>{c.z.assign(c.y),c.y.assign(c.x),c.x.assign(n)})).elseif(n.lessThan(c.y),(()=>{c.z.assign(c.y),c.y.assign(n)})).elseif(n.lessThan(c.z),(()=>{c.z.assign(n)}))}))})),Lg(i.equal(Og(0)),(()=>{c.assign(Yv(c))})),c})),IR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Ug(t).toVar(),s=kg(e).toVar(),a=Og().toVar(),o=Og().toVar(),l=Og().toVar(),c=kg(Rw(s.x,a),Rw(s.y,o),Rw(s.z,l)).toVar(),u=Ug(1e6).toVar();return IT({start:-1,end:Og(1),name:"x",condition:"<="},(({x:e})=>{IT({start:-1,end:Og(1),name:"y",condition:"<="},(({y:t})=>{IT({start:-1,end:Og(1),name:"z",condition:"<="},(({z:n})=>{const s=Ug(CR(c,e,t,n,a,o,l,r,i)).toVar();u.assign(xx(u,s))}))}))})),Lg(i.equal(Og(0)),(()=>{u.assign(Yv(u))})),u})),UR=LT([NR,IR]),OR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Ug(t).toVar(),s=kg(e).toVar(),a=Og().toVar(),o=Og().toVar(),l=Og().toVar(),c=kg(Rw(s.x,a),Rw(s.y,o),Rw(s.z,l)).toVar(),u=Bg(1e6,1e6).toVar();return IT({start:-1,end:Og(1),name:"x",condition:"<="},(({x:e})=>{IT({start:-1,end:Og(1),name:"y",condition:"<="},(({y:t})=>{IT({start:-1,end:Og(1),name:"z",condition:"<="},(({z:n})=>{const s=Ug(CR(c,e,t,n,a,o,l,r,i)).toVar();Lg(s.lessThan(u.x),(()=>{u.y.assign(u.x),u.x.assign(s)})).elseif(s.lessThan(u.y),(()=>{u.y.assign(s)}))}))}))})),Lg(i.equal(Og(0)),(()=>{u.assign(Yv(u))})),u})),DR=LT([LR,OR]),FR=Rg((([e,t,n])=>{const i=Og(n).toVar(),r=Ug(t).toVar(),s=kg(e).toVar(),a=Og().toVar(),o=Og().toVar(),l=Og().toVar(),c=kg(Rw(s.x,a),Rw(s.y,o),Rw(s.z,l)).toVar(),u=kg(1e6,1e6,1e6).toVar();return IT({start:-1,end:Og(1),name:"x",condition:"<="},(({x:e})=>{IT({start:-1,end:Og(1),name:"y",condition:"<="},(({y:t})=>{IT({start:-1,end:Og(1),name:"z",condition:"<="},(({z:n})=>{const s=Ug(CR(c,e,t,n,a,o,l,r,i)).toVar();Lg(s.lessThan(u.x),(()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(s)})).elseif(s.lessThan(u.y),(()=>{u.z.assign(u.y),u.y.assign(s)})).elseif(s.lessThan(u.z),(()=>{u.z.assign(s)}))}))}))})),Lg(i.equal(Og(0)),(()=>{u.assign(Yv(u))})),u})),BR=LT([PR,FR]);Ew.setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),Aw.setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),ww.setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Cw.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"}]}),Nw.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"}]}),Pw.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"}]}),Iw.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"}]}),Ow.setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Dw.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"}]}),Bw.setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Vw.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"}]}),Gw.setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),kw.setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Hw.setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),Xw.setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),qw.setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),$w.setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Zw.setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),Kw.setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),Jw.setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Qw.setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),eR.setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),tR.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"}]}),nR.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"}]}),rR.setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),sR.setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),oR.setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),lR.setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]}),uR.setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),hR.setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),pR.setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),mR.setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),fR.setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),gR.setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]}),vR.setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),xR.setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),yR.setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),bR.setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]}),TR.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"}]}),MR.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"}]}),ER.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"}]}),AR.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"}]}),wR.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"}]}),RR.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"}]}),NR.setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),LR.setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),PR.setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),IR.setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),OR.setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),FR.setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]});const VR=Rg((([e])=>{const t=kg(e).toVar(),n=Ug(t.x).toVar(),i=Ug(t.y).toVar(),r=Ug(t.z).toVar();Lg(i.lessThan(1e-4),(()=>kg(r,r,r))).else((()=>{n.assign(Sv(6,n.sub(Zv(n))));const e=Og(fx(n)).toVar(),t=Ug(n.sub(Ug(e))).toVar(),s=Ug(r.mul(bv(1,i))).toVar(),a=Ug(r.mul(bv(1,i.mul(t)))).toVar(),o=Ug(r.mul(bv(1,i.mul(bv(1,t))))).toVar();return Lg(e.equal(Og(0)),(()=>kg(r,o,s))).elseif(e.equal(Og(1)),(()=>kg(a,r,s))).elseif(e.equal(Og(2)),(()=>kg(s,r,o))).elseif(e.equal(Og(3)),(()=>kg(s,a,r))).elseif(e.equal(Og(4)),(()=>kg(o,s,r))),kg(r,s,a)}))})),zR=Rg((([e])=>{const t=kg(e).toVar(),n=Ug(t.x).toVar(),i=Ug(t.y).toVar(),r=Ug(t.z).toVar(),s=Ug(xx(n,xx(i,r))).toVar(),a=Ug(yx(n,yx(i,r))).toVar(),o=Ug(a.sub(s)).toVar(),l=Ug().toVar(),c=Ug().toVar(),u=Ug().toVar();return u.assign(a),Lg(a.greaterThan(0),(()=>{c.assign(o.div(a))})).else((()=>{c.assign(0)})),Lg(c.lessThanEqual(0),(()=>{l.assign(0)})).else((()=>{Lg(n.greaterThanEqual(a),(()=>{l.assign(i.sub(r).div(o))})).elseif(i.greaterThanEqual(a),(()=>{l.assign(yv(2,r.sub(n).div(o)))})).else((()=>{l.assign(yv(4,n.sub(i).div(o)))})),l.mulAssign(1/6),Lg(l.lessThan(0),(()=>{l.addAssign(1)}))})),kg(l,c,u)}));VR.setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),zR.setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]});const GR=Rg((([e])=>{const t=kg(e).toVar(),n=Xg(Rv(t,kg(.04045))).toVar(),i=kg(t.div(12.92)).toVar(),r=kg(Rx(yx(t.add(kg(.055)),kg(0)).div(1.055),kg(2.4))).toVar();return Ux(i,r,n)}));GR.setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]});const kR=(e,t)=>{e=Ug(e),t=Ug(t);const n=Bg(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Bx(e.sub(n),e.add(n),t)},HR=(e,t,n,i)=>Ux(e,t,n[i].clamp()),WR=(e,t,n=gv())=>HR(e,t,n,"x"),XR=(e,t,n=gv())=>HR(e,t,n,"y"),jR=(e,t,n,i,r)=>Ux(e,t,kR(n,i[r])),qR=(e,t,n,i=gv())=>jR(e,t,n,i,"x"),YR=(e,t,n,i=gv())=>jR(e,t,n,i,"y"),$R=(e=1,t=0,n=gv())=>n.mul(e).add(t),ZR=(e,t=1)=>(e=Ug(e)).abs().pow(t).mul(e.sign()),KR=(e,t=1,n=.5)=>Ug(e).sub(n).mul(t).add(n),JR=(e=gv(),t=1,n=0)=>cR(e.convert("vec2|vec3")).mul(t).add(n),QR=(e=gv(),t=1,n=0)=>dR(e.convert("vec2|vec3")).mul(t).add(n),eC=(e=gv(),t=1,n=0)=>{e=e.convert("vec2|vec3");return jg(dR(e),cR(e.add(Bg(19,73)))).mul(t).add(n)},tC=(e=gv(),t=1)=>UR(e.convert("vec2|vec3"),t,Og(1)),nC=(e=gv(),t=1)=>DR(e.convert("vec2|vec3"),t,Og(1)),iC=(e=gv(),t=1)=>BR(e.convert("vec2|vec3"),t,Og(1)),rC=(e=gv())=>_R(e.convert("vec2|vec3")),sC=(e=gv(),t=3,n=2,i=.5,r=1)=>TR(e,Og(t),n,i).mul(r),aC=(e=gv(),t=3,n=2,i=.5,r=1)=>ER(e,Og(t),n,i).mul(r),oC=(e=gv(),t=3,n=2,i=.5,r=1)=>MR(e,Og(t),n,i).mul(r),lC=(e=gv(),t=3,n=2,i=.5,r=1)=>AR(e,Og(t),n,i).mul(r);function cC(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function uC(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}class hC{constructor(){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparent=[],this.lightsNode=new nS([]),this.lightsArray=[],this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparent.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,r,s){let a=this.renderItems[this.renderItemsIndex];return void 0===a?(a={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s},this.renderItems[this.renderItemsIndex]=a):(a.id=e.id,a.object=e,a.geometry=t,a.material=n,a.groupOrder=i,a.renderOrder=e.renderOrder,a.z=r,a.group=s),this.renderItemsIndex++,a}push(e,t,n,i,r,s){const a=this.getNextRenderItem(e,t,n,i,r,s);!0===e.occlusionTest&&this.occlusionQueryCount++,(!0===n.transparent?this.transparent:this.opaque).push(a)}unshift(e,t,n,i,r,s){const a=this.getNextRenderItem(e,t,n,i,r,s);(!0===n.transparent?this.transparent:this.opaque).unshift(a)}pushLight(e){this.lightsArray.push(e)}getLightsNode(){return this.lightsNode.fromLights(this.lightsArray)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||cC),this.transparent.length>1&&this.transparent.sort(t||uC)}finish(){this.lightsNode.fromLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,c=o.height>>t;let u=e.depthTexture||r[t],h=!1;void 0===u&&(u=new $a,u.format=Ge,u.type=Oe,u.image.width=l,u.image.height=c,r[t]=u),n.width===o.width&&o.height===n.height||(h=!0,u.needsUpdate=!0,u.image.width=l,u.image.height=c),n.width=o.width,n.height=o.height,n.textures=a,n.depthTexture=u,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.sampleCount!==i&&(h=!0,u.needsUpdate=!0,n.sampleCount=i);const d={sampleCount:i};for(let e=0;e{if(e.removeEventListener("dispose",t),void 0!==a)for(let e=0;e0){const i=e.image;if(void 0===i);else if(!1===i.complete);else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1),r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0}if(!0!==n.initialized){n.initialized=!0,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}n.version=e.version}getSize(e,t=gC){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),t.width=n.width,t.height=n.height,t.depth=e.isCubeTexture?6:n.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==fe&&e.minFilter!==ye)}isEnvironmentTexture(e){const t=e.mapping;return t===ce||t===ue||t===oe||t===le}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class vC extends $r{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}const xC=new vC;class yC extends Km{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(xC,this.renderer.currentColorSpace),xC.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(xC,this.renderer.currentColorSpace),xC.a=1,s=!0;else if(!0===r.isNode){const n=this.get(e),s=r;xC.copy(i._clearColor);let a=n.backgroundMesh;if(void 0===a){const e=E_(jg(s),{getUV:()=>By,getTextureLevel:()=>CM}).mul(NM);let t=Mb();t=t.setZ(t.w);const i=new WS;i.side=d,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.vertexNode=t,i.fragmentNode=e,n.backgroundMeshNode=e,n.backgroundMesh=a=new Hs(new qh(1,32,32),i),a.frustumCulled=!1,a.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)}}const o=s.getCacheKey();n.backgroundCacheKey!==o&&(n.backgroundMeshNode.node=jg(s),a.material.needsUpdate=!0,n.backgroundCacheKey=o),t.unshift(a,a.geometry,a.material,0,0,null)}if(!0===i.autoClear||!0===s){xC.multiplyScalar(xC.a);const e=n.clearColorValue;e.r=xC.r,e.g=xC.g,e.b=xC.b,e.a=xC.a,n.depthClearValue=i._clearDepth,n.stencilClearValue=i._clearStencil,n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}class bC{constructor(e,t,n,i,r,s,a){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){let n=t;!0!==t.shared&&(n=t.clone()),e.push(n)}return e}}class SC extends Km{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new vT,this.nodeBuilderCache=new Map,this.callHashCache=new qm,this.groupsData=new qm}updateGroup(e){const t=e.groupNode,n=t.name;if(n===zf.name)return!0;if(n===Vf.name){const t=this.get(e),n=this.nodeFrame.renderId;return t.renderId!==n&&(t.renderId=n,!0)}if(n===Bf.name){const t=this.get(e),n=this.nodeFrame.frameId;return t.frameId!==n&&(t.frameId=n,!0)}const i=[t,e];let r=this.groupsData.get(i);return void 0===r&&this.groupsData.set(i,r={}),r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(n=i.get(r),void 0===n){const t=this.backend.createNodeBuilder(e.object,this.renderer,e.scene);t.material=e.material,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.toneMappingNode=this.getToneMappingNode(),t.build(),n=this._createNodeBuilderState(t),i.set(r,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),n=this._createNodeBuilderState(i),t.nodeBuilderState=i}return n}_createNodeBuilderState(e){return new bC(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getToneMappingNode(){return!1===this.isToneMappingState?null:this.renderer.toneMappingNode||this.get(this.renderer).toneMappingNode||null}getCacheKey(e,t){const n=[e,t],i=this.renderer.info.calls;let r=this.callHashCache.get(n);if(void 0===r||r.callId!==i){const s=this.getEnvironmentNode(e),a=this.getFogNode(e),o=this.getToneMappingNode(),l=[];t&&l.push(t.getCacheKey()),s&&l.push(s.getCacheKey()),a&&l.push(a.getCacheKey()),o&&l.push(o.getCacheKey()),r={callId:i,cacheKey:l.join(",")},this.callHashCache.set(n,r)}return r.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e),this.updateToneMapping()}get isToneMappingState(){const e=this.renderer.getRenderTarget();return!e||!e.isCubeRenderTarget}updateToneMapping(){const e=this.renderer,t=this.get(e),n=e.toneMapping;if(this.isToneMappingState&&n!==K){if(t.toneMapping!==n){const i=t.rendererToneMappingNode||bE(n,sy("toneMappingExposure","float",e));i.toneMapping=n,t.rendererToneMappingNode=i,t.toneMappingNode=i,t.toneMapping=n}}else delete t.toneMappingNode,delete t.toneMapping}updateBackground(e){const t=this.get(e),n=e.background;if(n){if(t.background!==n){let e=null;if(!0===n.isCubeTexture)e=Kb(n,By);else if(!0===n.isTexture){let t=null;n.mapping===ce||n.mapping===ue?(t=uS(),n.flipY=!1):t=MS,e=ty(n,t).setUpdateMatrix(!0)}else n.isColor;t.backgroundNode=e,t.background=n}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){let e=null;n.isFogExp2?e=QE(sy("color","color",n),sy("density","float",n)):n.isFog&&(e=KE(sy("color","color",n),sy("near","float",n),sy("far","float",n))),t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){let e=null;!0===n.isCubeTexture?e=Kb(n):!0===n.isTexture&&(e=ty(n)),t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=i,s.material=r,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}updateBefore(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateBeforeNodes)t.updateBeforeNode(e)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}dispose(){super.dispose(),this.nodeFrame=new vT,this.nodeBuilderCache=new Map}}const TC=new Jl,MC=new Qn,EC=new Ti,AC=new ca,wC=new lr,RC=new Pi;class CC{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,alpha:i=!0}=t;this.domElement=e.getDomElement(),this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=n,this.outputColorSpace=jt,this.toneMapping=K,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=!0,this.stencil=!0,this.info=new of,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Ti(0,0,this._width,this._height),this._scissor=new Ti(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null;const r=!0===this.alpha?0:1;this._clearColor=new vC(0,0,0,r),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._initialized=!1,this._initPromise=null,this.shadowMap={enabled:!1,type:null},this.xr={enabled:!1}}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)=>{const n=this.backend;try{await n.init(this)}catch(e){return void t(e)}this._nodes=new SC(this,n),this._animation=new jm(this._nodes,this.info),this._attributes=new nf(n),this._background=new yC(this,this._nodes),this._geometries=new af(this._attributes,this.info),this._textures=new _C(n,this.info),this._pipelines=new pf(n,this._nodes),this._bindings=new mf(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Zm(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new dC,this._renderContexts=new fC,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compile(){}async render(e,t){!1===this._initialized&&await this.init();const n=this._nodes.nodeFrame,i=n.renderId,r=this._currentRenderContext,s=this._currentRenderObjectFunction,a=!0===e.isScene?e:TC,o=this._renderTarget,l=this._renderContexts.get(e,t,o),c=this._activeCubeFace,u=this._activeMipmapLevel;this._currentRenderContext=l,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,n.renderId=this.info.calls;const h=this.coordinateSystem;t.coordinateSystem!==h&&(t.coordinateSystem=h,t.updateProjectionMatrix()),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===this.info.autoReset&&this.info.reset();let d=this._viewport,p=this._scissor,m=this._pixelRatio;null!==o&&(d=o.viewport,p=o.scissor,m=1),this.getDrawingBufferSize(MC),EC.set(0,0,MC.width,MC.height);const f=void 0===d.minDepth?0:d.minDepth,g=void 0===d.maxDepth?1:d.maxDepth;l.viewportValue.copy(d).multiplyScalar(m).floor(),l.viewportValue.width>>=u,l.viewportValue.height>>=u,l.viewportValue.minDepth=f,l.viewportValue.maxDepth=g,l.viewport=!1===l.viewportValue.equals(EC),l.scissorValue.copy(p).multiplyScalar(m).floor(),l.scissor=this._scissorTest&&!1===l.scissorValue.equals(EC),l.scissorValue.width>>=u,l.scissorValue.height>>=u,l.depth=this.depth,l.stencil=this.stencil,a.onBeforeRender(this,e,t,o),wC.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),AC.setFromProjectionMatrix(wC,h);const _=this._renderLists.get(e,t);if(_.begin(),this._projectObject(e,t,0,_),_.finish(),!0===this.sortObjects&&_.sort(this._opaqueSort,this._transparentSort),null!==o){this._textures.updateRenderTarget(o,u);const e=this._textures.get(o);l.textures=e.textures,l.depthTexture=e.depthTexture,l.width=e.width,l.height=e.height,l.renderTarget=o}else l.textures=null,l.depthTexture=null,l.width=this.domElement.width,l.height=this.domElement.height;l.width>>=u,l.height>>=u,l.activeCubeFace=c,l.activeMipmapLevel=u,l.occlusionQueryCount=_.occlusionQueryCount,this._nodes.updateScene(a),this._background.update(a,_,l),this.backend.beginRender(l);const v=_.opaque,x=_.transparent,y=_.lightsNode;v.length>0&&this._renderObjects(v,t,a,y),x.length>0&&this._renderObjects(x,t,a,y),this.backend.finishRender(l),n.renderId=i,this._currentRenderContext=r,this._currentRenderObjectFunction=s,a.onAfterRender(this,e,t,o)}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)}getArrayBuffer(e){return this.getArrayBufferAsync(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.setSize(this._width,this._height,!1)}setDrawingBufferSize(e,t,n){this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,n=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._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,n,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=r,a.maxDepth=s}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,n=!0){let i=null;const r=this._renderTarget;null!==r&&(this._textures.updateRenderTarget(r),i=this._textures.get(r)),this.backend.clear(e,t,n,i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}get currentColorSpace(){const e=this._renderTarget;if(null!==e){const t=e.texture;return(Array.isArray(t)?t[0]:t).colorSpace}return this.outputColorSpace}dispose(){this.info.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}async compute(e){!1===this._initialized&&await this.init();const t=this._nodes.nodeFrame,n=t.renderId;this.info.calls++,this.info.compute.calls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,s=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.");i.beginCompute(e);for(const t of o){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),s.delete(t),a.delete(t)};t.addEventListener("dispose",e),t.onInit({renderer:this})}a.updateForCompute(t),s.updateForCompute(t);const n=s.getForCompute(t),o=r.getForCompute(t,n);i.compute(e,t,n,o)}i.finishCompute(e),t.renderId=n}hasFeature(e){return this.backend.hasFeature(e)}copyFramebufferToTexture(e){const t=this._currentRenderContext;this._textures.updateTexture(e),this.backend.copyFramebufferToTexture(e,t)}readRenderTargetPixelsAsync(e,t,n,i,r){return this.backend.copyTextureToBuffer(e.texture,t,n,i,r)}_projectObject(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||AC.intersectsSprite(e)){!0===this.sortObjects&&RC.setFromMatrixPosition(e.matrixWorld).applyMatrix4(wC);const t=e.geometry,r=e.material;r.visible&&i.push(e,t,r,n,RC.z,null)}}else if(e.isLineLoop);else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||AC.intersectsObject(e))){const t=e.geometry,r=e.material;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),RC.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(wC)),Array.isArray(r)){const s=t.groups;for(let a=0,o=s.length;a0?r:"";t=`${n.name} {\n\t${i} ${e.name}[${s}];\n};\n`}else{t=`${this.getVectorType(e.type)} ${e.name};`,r=!0}const s=e.node.precision;if(null!==s&&(t=WC[s]+" "+t),r){t="\t"+t;const n=e.groupNode.name;(i[n]||(i[n]=[])).push(t)}else t="uniform "+t,n.push(t)}let r="";for(const t in i){const n=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,n.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Ce){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e){const e=this.getAttributesArray();let n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[],n=e.getMemberTypes();for(let e=0;e0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${i.result};`)))}const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.flow=n}null!==this.material&&(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment))}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){if("texture"===t)a=new GC(r.name,r.node),this.bindings[n].push(a);else if("cubeTexture"===t)a=new kC(r.name,r.node),this.bindings[n].push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`;const t=new OC(e.name,e.value);r.name=`buffer${e.id}`,this.bindings[n].push(t),a=t}else{const i=e.groupNode,s=i.name,o=this.uniformGroups[n]||(this.uniformGroups[n]={});let l=o[s];void 0===l&&(l=new BC(n+"_"+s,i),o[s]=l,this.bindings[n].push(l)),a=this.getNodeUniform(r,t),l.addUniform(a)}s.uniformGPU=a}return r}}let YC=null,$C=null,ZC=null;class KC{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(e){}finish(e){}draw(e,t){}createProgram(e){}destroyProgram(e){}createBindings(e){}updateBindings(e){}createRenderPipeline(e){}createComputePipeline(e,t){}destroyPipeline(e){}needsRenderUpdate(e){}getRenderCacheKey(e){}createNodeBuilder(e){}createSampler(e){}createDefaultTexture(e){}createTexture(e){}copyTextureToBuffer(e,t,n,i,r){}createAttribute(e){}createIndexAttribute(e){}updateAttribute(e){}destroyAttribute(e){}getContext(){}updateSize(){}hasFeature(e){}getInstanceCount(e){const{object:t,geometry:n}=e;return n.isInstancedBufferGeometry?n.instanceCount:t.isInstancedMesh?t.count:1}getDrawingBufferSize(){return YC=YC||new Qn,this.renderer.getDrawingBufferSize(YC)}getScissor(){return $C=$C||new Ti,this.renderer.getScissor($C)}getClearColor(){const e=this.renderer;return ZC=ZC||new vC,e.getClearColor(ZC),ZC.getRGB(ZC,this.renderer.currentColorSpace),ZC}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:ai(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}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}delete(e){this.data.delete(e)}}class JC{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,c=o.bufferGPU;if(void 0===c&&(c=i.createBuffer(),i.bindBuffer(t,c),i.bufferData(t,r,s),i.bindBuffer(t,null),o.bufferGPU=c,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}n.set(e,{bufferGPU:c,type:l,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===Ce})}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()}))}}let rN,sN,aN,oN=!1;class lN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===oN&&(this._init(this.gl),oN=!0)}_init(e){rN={[de]:e.REPEAT,[pe]:e.CLAMP_TO_EDGE,[me]:e.MIRRORED_REPEAT},sN={[fe]:e.NEAREST,[ge]:e.NEAREST_MIPMAP_NEAREST,[ve]:e.NEAREST_MIPMAP_LINEAR,[ye]:e.LINEAR,[be]:e.LINEAR_MIPMAP_NEAREST,[Te]:e.LINEAR_MIPMAP_LINEAR},aN={[_n]:e.NEVER,[Mn]:e.ALWAYS,[vn]:e.LESS,[yn]:e.LEQUAL,[xn]:e.EQUAL,[Tn]:e.GEQUAL,[bn]:e.GREATER,[Sn]:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===fe||e===ge||e===ve?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r=!1){const{gl:s,extensions:a}=this;if(null!==e&&void 0!==s[e])return s[e];let o=t;return t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8)),t===s.RGBA&&(n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=i===jt&&!1===r?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_INT&&(o=s.DEPTH24_STENCIL8),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:i}=this;n.texParameteri(e,n.TEXTURE_WRAP_S,rN[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,rN[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||n.texParameteri(e,n.TEXTURE_WRAP_R,rN[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,sN[t.magFilter]);const r=t.minFilter===ye?Te:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,sN[r]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,aN[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fe)return;if(t.minFilter!==ve&&t.minFilter!==Te)return;if(t.type===Le&&!1===i.has("OES_texture_float_linear"))return;t.anisotropy}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:r,width:s,height:a,depth:o}=t,l=i.utils.convert(e.format,e.colorSpace),c=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,l,c,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,h),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,e.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,e.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.NONE),this.setTextureParameters(d,e),e.isDataArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,u,s,a,o):e.isVideoTexture||n.texStorage2D(d,r,u,s,a),i.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:c,glInternalFormat:u})}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:c}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===s)return;const u=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(a,s),e.isCompressedTexture){const i=e.mipmaps;for(let r=0;r0?(s&&s.isDepthTexture&&s.type===n.FLOAT&&(t=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,r,t,l,c)):n.renderbufferStorage(n.RENDERBUFFER,t,l,c),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else a&&o&&(r>0?n.renderbufferStorageMultisample(n.RENDERBUFFER,r,n.DEPTH24_STENCIL8,l,c):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,l,c),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,n,i,r){const{backend:s,gl:a}=this,{textureGPU:o,glFormat:l,glType:c}=this.backend.get(e),u=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,u),a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,o,0);const h=this._getTypedArrayType(c),d=i*r,p=d*this._getBytesPerTexel(l),m=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,m),a.bufferData(a.PIXEL_PACK_BUFFER,p,a.STREAM_READ),a.readPixels(t,n,i,r,l,c,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await s.utils._clientWaitAsync();const f=new h(d);return a.bindBuffer(a.PIXEL_PACK_BUFFER,m),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteFramebuffer(u),f}_getTypedArrayType(e){const{gl:t}=this;return e===t.UNSIGNED_BYTE?Uint8Array:e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT?Uint16Array:e===t.UNSIGNED_INT?Uint32Array:e===t.UNSIGNED_FLOAT?Float32Array:void 0}_getBytesPerTexel(e){const{gl:t}=this;return e===t.RGBA?4:e===t.RGB?3:e===t.ALPHA?1:void 0}}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)),t}has(e){return this.availableExtensions.includes(e)}}class uN{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 n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const hN={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"};class dN extends KC{constructor(e={}){super(e),this.isWebGLBackend=!0}init(e){super.init(e);const t=this.parameters,n=void 0!==t.context?t.context:e.domElement.getContext("webgl2");this.gl=n,this.extensions=new cN(this),this.capabilities=new uN(this),this.attributeUtils=new JC(this),this.textureUtils=new lN(this),this.state=new nN(this),this.utils=new iN(this),this.extensions.get("EXT_color_buffer_float"),this._currentContext=null}get coordinateSystem(){return Fn}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.gl}beginRender(e){const{gl:t}=this,n=this.get(e);n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e),e.viewport?this.updateViewport(e):t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight);const i=e.occlusionQueryCount;i>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e).previousContext,r=e.textures;if(null!==r)for(let e=0;e0){const r=i.msaaFrameBuffer,o=e.textures;n.bindFramebuffer(t.READ_FRAMEBUFFER,r),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,s);for(let n=0;n0){if(s>this.get(e).occlusionQueryIndex){const{gl:e}=this;e.endQuery(e.ANY_SAMPLES_PASSED)}this.resolveOccludedAsync(e)}}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=0;for(let t=0;t0&&e.add(i[t]),n[t]=null,r.deleteQuery(s),a++))}a1?o.drawElementsInstanced(_,h.count,e.type,f,v):o.drawElements(_,h.count,e.type,f),t.update(d,n,1)}else{const e=p.attributes.position,n=m.count!==1/0?m.count:e.count;v>1?o.drawArraysInstanced(_,0,n,v):o.drawArrays(_,0,n),t.update(d,n,1)}o.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(e){return e.id}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,n,i,r){return this.textureUtils.copyTextureToBuffer(e,t,n,i,r)}createSampler(){}destroySampler(){}createNodeBuilder(e,t,n=null){return new qC(e,t,n)}createProgram(e){const t=this.gl,{stage:n,code:i}=e,r="vertex"===n?t.createShader(t.VERTEX_SHADER):t.createShader(t.FRAGMENT_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(){}createRenderPipeline(e){const t=this.gl,n=e.pipeline,{fragmentProgram:i,vertexProgram:r}=n,s=t.createProgram(),a=this.get(i).shaderGPU,o=this.get(r).shaderGPU;t.attachShader(s,a),t.attachShader(s,o),t.linkProgram(s),t.getProgramParameter(s,t.LINK_STATUS),t.useProgram(s);const l=e.getBindings();for(const e of l){const n=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const i=t.getUniformBlockIndex(s,e.name);t.uniformBlockBinding(s,i,n)}else if(e.isSampledTexture){const i=t.getUniformLocation(s,e.name);t.uniform1i(i,n)}}const c=t.createVertexArray(),u=e.getIndex(),h=e.getAttributes();if(t.bindVertexArray(c),null!==u){const e=this.get(u);t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.bufferGPU)}for(let e=0;ehN[t]===e)),n=this.extensions;for(let e=0;e0){if(void 0===d){const i=[];d=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,d);const r=[],c=e.textures;for(let n=0;n,\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({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:_N,stripIndexFormat:UN},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:_N,stripIndexFormat:UN},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size,a=this.getTransferPipeline(i),o=this.getFlipYPipeline(i),l=this.device.createTexture({size:{width:r,height:s,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:lL,baseArrayLayer:n}),u=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:lL,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),d=(e,t,n)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),s=h.beginRenderPass({colorAttachments:[{view:n,loadOp:RN,storeOp:AN,clearValue:[0,0,0,0]}]});s.setPipeline(e),s.setBindGroup(0,r),s.draw(4,1,0,0),s.end()};d(a,c,u),d(o,u,c),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0){const i=this.getTransferPipeline(t.format),r=this.device.createCommandEncoder({}),s=i.getBindGroupLayout(0);let a=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:lL,baseArrayLayer:n});for(let o=1;o1&&(u=Math.pow(2,Math.floor(Math.log2(u))),2===u&&(u=4));const h=e.isRenderTargetTexture?1:u;let d=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(d|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&(d|=GPUTextureUsage.RENDER_ATTACHMENT);const p={label:e.name,size:{width:r,height:s,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:h,dimension:l,format:c,usage:d};if(e.isVideoTexture){const t=e.source.data,n=new VideoFrame(t);p.size.width=n.displayWidth,p.size.height=n.displayHeight,n.close(),i.externalTexture=t}else{if(void 0===c)return this.createDefaultTexture(e);i.texture=n.device.createTexture(p)}if(e.isRenderTargetTexture&&u>1){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=u,i.msaaTexture=n.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,n=t.get(e);n.texture.destroy(),void 0!==n.msaaTexture&&n.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else this._generateMipmaps(t.texture,t.textureDescriptorGPU)}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:n}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:n,depthOrArrayLayers:1},sampleCount:e.parameters.sampleCount,format:ON.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!0){const n=this.backend,{width:i,height:r}=n.getDrawingBufferSize(),s=this.depthTexture,a=n.get(s).texture;let o,l;if(t?(o=Ge,l=Oe):e&&(o=ze,l=Ne),void 0!==a){if(s.image.width===i&&s.image.height===r&&s.format===o&&s.type===l)return a;this.destroyTexture(s)}return s.name="depthBuffer",s.format=o,s.type=l,s.image.width=i,s.image.height=r,this.createTexture(s,{sampleCount:n.parameters.sampleCount,width:i,height:r}),n.get(s).texture}updateTexture(e,t){const n=this.backend.get(e),{textureDescriptorGPU:i}=n;if(!e.isRenderTargetTexture&&void 0!==i){if(e.isDataTexture||e.isData3DTexture)this._copyBufferToTexture(t.image,n.texture,i,0,!1);else if(e.isDataArrayTexture)for(let e=0;e]*\s*([a-z_0-9]+)?/i,ML=/[a-z_0-9]+|<(.*?)>+/gi,EL={f32:"float"};class AL extends xw{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s}=(e=>{const t=(e=e.trim()).match(TL);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=ML.exec(n));)i.push(r);const s=[];let a=0;for(;a "+this.type:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class wL extends vw{parseFunction(e){return new AL(e)}}const RL=window.GPUShaderStage,CL={vertex:RL?RL.VERTEX:1,fragment:RL?RL.FRAGMENT:2,compute:RL?RL.COMPUTE:4},NL={instance:!0},LL={"^^":"threejs_xor"},PL={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",mat3:"mat3x3",imat3:"mat3x3",umat3:"mat3x3",bmat3:"mat3x3",mat4:"mat4x4",imat4:"mat4x4",umat4:"mat4x4",bmat4:"mat4x4"},IL={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"threejs_mod_float",mod_vec2:"threejs_mod_vec2",mod_vec3:"threejs_mod_vec3",mod_vec4:"threejs_mod_vec4",lessThanEqual:"threejs_lessThanEqual",greaterThan:"threejs_greaterThan",inversesqrt:"inverseSqrt",bitcast:"bitcast"},UL={threejs_xor:new av("\nfn threejs_xor( a : bool, b : bool ) -> bool {\n\n\treturn ( a || b ) && !( a && b );\n\n}\n"),lessThanEqual:new av("\nfn threejs_lessThanEqual( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x <= b.x, a.y <= b.y, a.z <= b.z );\n\n}\n"),greaterThan:new av("\nfn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x > b.x, a.y > b.y, a.z > b.z );\n\n}\n"),mod_float:new av("fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new av("fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new av("fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new av("fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),repeatWrapping:new av("\nfn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n")};class OL extends _T{constructor(e,t,n=null){super(e,t,new wL,n),this.uniformGroups={},this.builtins={}}needsColorSpaceToLinear(e){return!0===e.isVideoTexture&&e.colorSpace!==Xt}_generateTextureSample(e,t,n,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureLod(e,t,n)}_generateVideoSample(e,t,n=this.shaderStage){if("fragment"===n)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`}_generateTextureSampleLevel(e,t,n,i,r,s=this.shaderStage){return"fragment"===s&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.generateTextureLod(e,t,n,i)}generateTextureLod(e,t,n,i="0"){this._include("repeatWrapping");return`textureLoad( ${t}, threejs_repeatWrapping( ${n}, ${`textureDimensions( ${t}, 0 )`} ), i32( ${i} ) )`}generateTextureLoad(e,t,n,i,r="0u"){return i?`textureLoad( ${t}, ${n}, ${i}, ${r} )`:`textureLoad( ${t}, ${n}, ${r} )`}isUnfilterable(e){return!0===e.isDataTexture&&e.type===Le}generateTexture(e,t,n,i,r=this.shaderStage){let s=null;return s=!0===e.isVideoTexture?this._generateVideoSample(t,n,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,n,"0",i,r):this._generateTextureSample(e,t,n,i,r),s}generateTextureCompare(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`}generateTextureLevel(e,t,n,i,r,s=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,n,s):this._generateTextureSampleLevel(e,t,n,i,r,s),a}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n?t:"buffer"===n||"storageBuffer"===n?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=LL[e];return void 0!==t?(this._include(t),t):null}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let i;const a=this.bindings[n];if("texture"===t||"cubeTexture"===t){let s=null;if("texture"===t?s=new GC(r.name,r.node):"cubeTexture"===t&&(s=new kC(r.name,r.node)),s.store=!0===e.isStoreTextureNode,s.setVisibility(CL[n]),"fragment"===n&&!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new gL(`${r.name}_sampler`,r.node);e.setVisibility(CL[n]),a.push(e,s),i=[e,s]}else a.push(s),i=[s]}else if("buffer"===t||"storageBuffer"===t){const r=new("storageBuffer"===t?_L:OC)("NodeBuffer_"+e.id,e.value);r.setVisibility(CL[n]),a.push(r),i=r}else{const s=e.groupNode,o=s.name,l=this.uniformGroups[n]||(this.uniformGroups[n]={});let c=l[o];if(void 0===c&&(c=new BC(o,s),c.setVisibility(CL[n]),l[o]=c,a.push(c)),!0===e.isArrayUniformNode){i=[];for(const n of e.nodes){const e=this.getNodeUniform(n,t);e.boundary=PC(e.itemSize),e.itemSize=IC(e.itemSize),c.addUniform(e),i.push(e)}}else i=this.getNodeUniform(r,t),c.addUniform(i)}s.uniformGPU=i,"vertex"===n&&(this.bindingsOffset.fragment=a.length)}return r}isReference(e){return super.isReference(e)||"texture_2d"===e||"texture_cube"===e||"texture_depth_2d"===e||"texture_storage_2d"===e}getBuiltin(e,t,n,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:n}),t}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));return`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n\treturn ${n.result};\n\n}`}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}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")}isFlipY(){return!1}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getAttributes(e){const t=[];if("compute"===e&&this.getBuiltin("global_invocation_id","id","vec3","attribute"),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e`)}return t.join(",\n")}getStructs(e){const t=[],n=this.structs[e];for(let e=0,i=n.length;e","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];for(let r=0;r";else if(!0===t.isDataArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i="texture_depth_2d";else if(!0===t.isVideoTexture)i="texture_external";else if(!0===r.node.isStoreTextureNode){i="texture_storage_2d<"+SL(t)+", write>"}else i="texture_2d";n.push(`@binding( ${a++} ) @group( 0 ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type){const e=r.node,t=this.getType(e.bufferType),n=e.bufferCount,s=n>0?", "+n:"",o=`\t${r.name} : array< ${t}${s} >\n`,l=e.isStorageBufferNode?"storage,read_write":"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,o,l,a++))}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name,n=s[t]||(s[t]={index:a++,snippets:[]});if(!0===Array.isArray(r.value)){const t=r.value.length;n.snippets.push(`uniform ${e}[ ${t} ] ${r.name}`)}else n.snippets.push(`\t${r.name} : ${e}`)}for(const e in s){const t=s[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index))}let o=n.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};for(const t in e){const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n\t`),i+=`${r.code}\n\t`,e===s&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(o)n.returnType=a.nodeType,i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar output : OutputStruct;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}n.flow=i}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getType(e){return PL[e]||e}isAvailable(e){return!0===NL[e]}_getWGSLMethod(e){return void 0!==UL[e]&&this._include(e),IL[e]}_include(e){const t=UL[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\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\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// system\nvar instanceIndex : u32;\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x;\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,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}class DL{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=ON.Depth24PlusStencil8:e.depth&&(t=ON.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).texture.format}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):ON.BGRA8Unorm,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?mN:e.isLine?fN:e.isMesh?gN:void 0}getSampleCount(e){return null!==e.textures?e.sampleCount:this.backend.parameters.sampleCount}}const FL=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),BL=new Map([[fs,["float16"]]]),VL=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class zL{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const e=i.device,a=n.array,o=a.byteLength+(4-a.byteLength%4)%4;s=e.createBuffer({label:n.name,size:o,usage:t,mappedAtCreation:!0}),new a.constructor(s.getMappedRange()).set(a),s.unmap(),r.buffer=s}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,i=n.device,r=n.get(t).buffer,s=t.array,a=t.updateRanges;if(0===a.length)i.queue.writeBuffer(r,0,s,0);else{for(let e=0,t=a.length;e1&&(S=Math.pow(2,Math.floor(Math.log2(S))),2===S&&(S=4)),u.pipeline=l.createRenderPipeline({vertex:Object.assign({},_,{buffers:d}),fragment:Object.assign({},v,{targets:g}),primitive:x,depthStencil:{format:b,depthWriteEnabled:n.depthWrite,depthCompare:y,stencilFront:m,stencilBack:{},stencilReadMask:n.stencilFuncMask,stencilWriteMask:n.stencilWriteMask},multisample:{count:S,alphaToCoverageEnabled:n.alphaToCoverage},layout:l.createPipelineLayout({bindGroupLayouts:[h.layout]})})}createComputePipeline(e,t){const n=this.backend,i=n.device,r=n.get(e.computeProgram).module,s=n.get(e),a=n.get(t);s.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:[a.layout]})})}_getBlending(e){let t,n;const i=e.blending;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:GN.One,r=null!==e.blendDstAlpha?e.blendDstAlpha:GN.Zero,s=null!==e.blendEquationAlpha?e.blendEquationAlpha:GN.Add;t={srcFactor:this._getBlendFactor(e.blendSrc),dstFactor:this._getBlendFactor(e.blendDst),operation:this._getBlendOperation(e.blendEquation)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(r),operation:this._getBlendOperation(s)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:kN},n={srcFactor:r,dstFactor:s,operation:kN}};if(e.premultipliedAlpha)switch(i){case 1:r(GN.SrcAlpha,GN.OneMinusSrcAlpha,GN.One,GN.OneMinusSrcAlpha);break;case 2:r(GN.SrcAlpha,GN.One,GN.One,GN.One);break;case 3:r(GN.Zero,GN.OneMinusSrc,GN.Zero,GN.One);break;case 4:r(GN.Zero,GN.Src,GN.Zero,GN.SrcAlpha)}else switch(i){case 1:r(GN.SrcAlpha,GN.OneMinusSrcAlpha,GN.One,GN.OneMinusSrcAlpha);break;case 2:r(GN.SrcAlpha,GN.One,GN.SrcAlpha,GN.One);break;case 3:r(GN.Zero,GN.OneMinusSrc,GN.Zero,GN.One);break;case 4:r(GN.Zero,GN.Src,GN.Zero,GN.Src)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n}}_getBlendFactor(e){let t;switch(e){case E:t=GN.Zero;break;case A:t=GN.One;break;case w:t=GN.Src;break;case R:t=GN.OneMinusSrc;break;case C:t=GN.SrcAlpha;break;case N:t=GN.OneMinusSrcAlpha;break;case I:t=GN.Dst;break;case U:t=GN.OneMinusDstColor;break;case L:t=GN.DstAlpha;break;case P:t=GN.OneMinusDstAlpha;break;case O:t=GN.SrcAlphaSaturated;break;case 211:t=GN.Constant;break;case 212:t=GN.OneMinusConstant}return t}_getStencilCompare(e){let t;switch(e.stencilFunc){case 512:t=vN;break;case gn:t=EN;break;case 513:t=xN;break;case 515:t=bN;break;case 514:t=yN;break;case 518:t=MN;break;case 516:t=SN;break;case 517:t=TN}return t}_getStencilOperation(e){let t;switch(e){case tn:t=$N;break;case 0:t=ZN;break;case 7681:t=KN;break;case 5386:t=JN;break;case 7682:t=QN;break;case 7683:t=eL;break;case 34055:t=tL;break;case 34056:t=nL}return t}_getBlendOperation(e){let t;switch(e){case y:t=kN;break;case b:t=HN;break;case S:t=WN;break;case T:t=XN;break;case M:t=jN}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?IN:UN),n.side){case h:i.frontFace=CN,i.cullMode=PN;break;case d:i.frontFace=CN,i.cullMode=LN;break;case 2:i.frontFace=CN,i.cullMode=NN}return i}_getColorWriteMask(e){return!0===e.colorWrite?YN:qN}_getDepthCompare(e){let t;if(!1===e.depthTest)t=EN;else{switch(e.depthFunc){case 0:t=vN;break;case 1:t=EN;break;case 2:t=xN;break;case 3:t=bN;break;case 4:t=yN;break;case 5:t=MN;break;case 6:t=SN;break;case 7:t=TN}}return t}}let HL=null;void 0!==navigator.gpu&&(HL=await navigator.gpu.requestAdapter());class WL extends KC{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.antialias=!0===e.antialias,!0===this.parameters.antialias?this.parameters.sampleCount=void 0===e.sampleCount?4:e.sampleCount:this.parameters.sampleCount=1,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.adapter=null,this.device=null,this.context=null,this.colorBuffer=null,this.utils=new DL(this),this.attributeUtils=new zL(this),this.bindingUtils=new GL(this),this.pipelineUtils=new kL(this),this.textureUtils=new bL(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters,n={powerPreference:t.powerPreference},i=await navigator.gpu.requestAdapter(n);if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(mL),s=[];for(const e of r)i.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits},o=await i.requestDevice(a),l=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.adapter=i,this.device=o,this.context=l;const c=t.alpha?"premultiplied":"opaque";this.context.configure({device:this.device,format:ON.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:c}),this.updateSize()}get coordinateSystem(){return Bn}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}beginRender(e){const t=this.get(e),n=this.device,i=e.occlusionQueryCount;let r;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:i}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null);const s={colorAttachments:[{view:null}],depthStencilAttachment:{view:null},occlusionQuerySet:r},a=s.colorAttachments[0],o=s.depthStencilAttachment,l=this.parameters.antialias;if(null!==e.textures){const t=e.textures;s.colorAttachments=[];const n=s.colorAttachments;for(let i=0;it.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),n>0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e>8&255]+Vn[e>>16&255]+Vn[e>>24&255]+"-"+Vn[255&t]+Vn[t>>8&255]+"-"+Vn[t>>16&15|64]+Vn[t>>24&255]+"-"+Vn[63&n|128]+Vn[n>>8&255]+"-"+Vn[n>>16&255]+Vn[n>>24&255]+Vn[255&i]+Vn[i>>8&255]+Vn[i>>16&255]+Vn[i>>24&255]).toLowerCase()}function Wn(e,t,n){return Math.max(t,Math.min(n,e))}function Xn(e,t){return(e%t+t)%t}function jn(e,t,n){return(1-n)*e+n*t}function qn(e){return 0==(e&e-1)&&0!==e}function Yn(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function $n(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function Zn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Kn={DEG2RAD:Gn,RAD2DEG:kn,generateUUID:Hn,clamp:Wn,euclideanModulo:Xn,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:jn,damp:function(e,t,n,i){return jn(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(Xn(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(zn=e);let t=zn+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*Gn},radToDeg:function(e){return e*kn},isPowerOfTwo:qn,ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:Yn,setQuaternionFromProperEuler:function(e,t,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((t+i)/2),u=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),m=a((i-t)/2);switch(r){case"XYX":e.set(o*u,l*h,l*d,o*c);break;case"YZY":e.set(l*d,o*u,l*h,o*c);break;case"ZXZ":e.set(l*h,l*d,o*u,o*c);break;case"XZX":e.set(o*u,l*m,l*p,o*c);break;case"YXY":e.set(l*p,o*u,l*m,o*c);break;case"ZYZ":e.set(l*m,l*p,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Zn,denormalize:$n};class Jn{constructor(e=0,t=0){Jn.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Wn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Qn{constructor(e,t,n,i,r,s,a,o,l){Qn.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const c=this.elements;return c[0]=e,c[1]=i,c[2]=a,c[3]=t,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],u=n[7],h=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],_=i[1],v=i[4],x=i[7],y=i[2],b=i[5],S=i[8];return r[0]=s*m+a*_+o*y,r[3]=s*f+a*v+o*b,r[6]=s*g+a*x+o*S,r[1]=l*m+c*_+u*y,r[4]=l*f+c*v+u*b,r[7]=l*g+c*x+u*S,r[2]=h*m+d*_+p*y,r[5]=h*f+d*v+p*b,r[8]=h*g+d*x+p*S,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8];return t*s*c-t*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=c*s-a*l,h=a*o-c*r,d=l*r-s*o,p=t*u+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(i*l-c*n)*m,e[2]=(a*n-i*s)*m,e[3]=h*m,e[4]=(c*t-i*o)*m,e[5]=(i*r-a*t)*m,e[6]=d*m,e[7]=(n*o-l*t)*m,e[8]=(s*t-n*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(ei.makeScale(e,t)),this}rotate(e){return this.premultiply(ei.makeRotation(-e)),this}translate(e,t){return this.premultiply(ei.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const ei=new Qn;function ti(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}const ni={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function ii(e,t){return new ni[e](t)}function ri(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function si(){const e=ri("canvas");return e.style.display="block",e}const ai={};function oi(e){e in ai||(ai[e]=!0,console.warn(e))}const li=(new Qn).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),ci=(new Qn).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ui={[jt]:{transfer:$t,primaries:Kt,toReference:e=>e,fromReference:e=>e},[Xt]:{transfer:Zt,primaries:Kt,toReference:e=>e.convertSRGBToLinear(),fromReference:e=>e.convertLinearToSRGB()},[Yt]:{transfer:$t,primaries:Jt,toReference:e=>e.applyMatrix3(ci),fromReference:e=>e.applyMatrix3(li)},[qt]:{transfer:Zt,primaries:Jt,toReference:e=>e.convertSRGBToLinear().applyMatrix3(ci),fromReference:e=>e.applyMatrix3(li).convertLinearToSRGB()}},hi=new Set([jt,Yt]),di={enabled:!0,_workingColorSpace:jt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(e){if(!hi.has(e))throw new Error(`Unsupported working color space, "${e}".`);this._workingColorSpace=e},convert:function(e,t,n){if(!1===this.enabled||t===n||!t||!n)return e;const i=ui[t].toReference;return(0,ui[n].fromReference)(i(e))},fromWorkingColorSpace:function(e,t){return this.convert(e,this._workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this._workingColorSpace)},getPrimaries:function(e){return ui[e].primaries},getTransfer:function(e){return e===Wt?$t:ui[e].transfer}};function pi(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function mi(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let fi;class gi{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===fi&&(fi=ri("canvas")),fi.width=e.width,fi.height=e.height;const n=fi.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=fi}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=ri("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==oe)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pe:e.x=e.x-Math.floor(e.x);break;case me:e.x=e.x<0?0:1;break;case fe:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case pe:e.y=e.y-Math.floor(e.y);break;case me:e.y=e.y<0?0:1;break;case fe:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}}bi.DEFAULT_IMAGE=null,bi.DEFAULT_MAPPING=oe,bi.DEFAULT_ANISOTROPY=1;class Si{constructor(e=0,t=0,n=0,i=1){Si.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const s=.01,a=.1,o=e.elements,l=o[0],c=o[4],u=o[8],h=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-h)o&&e>_?e_?o=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,t*n);e=Math.sin(e*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*e+h*r,l=l*e+d*r,c=c*e+p*r,u=u*e+m*r,e===1-a){const e=1/Math.sqrt(o*o+l*l+c*c+u*u);o*=e,l*=e,c*=e,u*=e}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],u=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+c*u+o*d-l*h,e[t+1]=o*p+c*h+l*u-a*d,e[t+2]=l*p+c*d+a*h-o*u,e[t+3]=c*p-a*u-o*h-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),u=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*c*u+l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u-h*d*p;break;case"YXZ":this._x=h*c*u+l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u+h*d*p;break;case"ZXY":this._x=h*c*u-l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u-h*d*p;break;case"ZYX":this._x=h*c*u-l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u+h*d*p;break;case"YZX":this._x=h*c*u+l*d*p,this._y=l*d*u+h*c*p,this._z=l*c*p-h*d*u,this._w=l*c*u-h*d*p;break;case"XZY":this._x=h*c*u-l*d*p,this._y=l*d*u-h*c*p,this._z=l*c*p+h*d*u,this._w=l*c*u+h*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],c=t[6],u=t[10],h=n+a+u;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(c-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>u){const e=2*Math.sqrt(1+n-a-u);this._w=(c-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>u){const e=2*Math.sqrt(1+a-n-u);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+c)/e}else{const e=2*Math.sqrt(1+u-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+c)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Wn(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*e._w+n*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*s+t*this._w,this._x=e*n+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),u=Math.sin((1-t)*c)/l,h=Math.sin(t*c)/l;return this._w=s*u+this._w*h,this._x=n*u+this._x*h,this._y=i*u+this._y*h,this._z=r*u+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ni{constructor(e=0,t=0,n=0){Ni.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Li.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Li.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),c=2*(a*t-r*i),u=2*(r*n-s*t);return this.x=t+o*l+s*u-a*c,this.y=n+o*c+a*l-r*u,this.z=i+o*u+r*c-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Pi.copy(this).projectOnVector(e),this.sub(Pi)}reflect(e){return this.sub(Pi.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Wn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Pi=new Ni,Li=new Ci;class Ii{constructor(e=new Ni(1/0,1/0,1/0),t=new Ni(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,Oi),Oi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Hi),Wi.subVectors(this.max,Hi),Fi.subVectors(e.a,Hi),Bi.subVectors(e.b,Hi),Vi.subVectors(e.c,Hi),zi.subVectors(Bi,Fi),Gi.subVectors(Vi,Bi),ki.subVectors(Fi,Vi);let t=[0,-zi.z,zi.y,0,-Gi.z,Gi.y,0,-ki.z,ki.y,zi.z,0,-zi.x,Gi.z,0,-Gi.x,ki.z,0,-ki.x,-zi.y,zi.x,0,-Gi.y,Gi.x,0,-ki.y,ki.x,0];return!!qi(t,Fi,Bi,Vi,Wi)&&(t=[1,0,0,0,1,0,0,0,1],!!qi(t,Fi,Bi,Vi,Wi)&&(Xi.crossVectors(zi,Gi),t=[Xi.x,Xi.y,Xi.z],qi(t,Fi,Bi,Vi,Wi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Oi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Oi).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Ui[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ui[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ui[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ui[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ui[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ui[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ui[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ui[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ui)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ui=[new Ni,new Ni,new Ni,new Ni,new Ni,new Ni,new Ni,new Ni],Oi=new Ni,Di=new Ii,Fi=new Ni,Bi=new Ni,Vi=new Ni,zi=new Ni,Gi=new Ni,ki=new Ni,Hi=new Ni,Wi=new Ni,Xi=new Ni,ji=new Ni;function qi(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){ji.fromArray(e,s);const a=r.x*Math.abs(ji.x)+r.y*Math.abs(ji.y)+r.z*Math.abs(ji.z),o=t.dot(ji),l=n.dot(ji),c=i.dot(ji);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Yi=new Ii,$i=new Ni,Zi=new Ni;class Ki{constructor(e=new Ni,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):Yi.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;$i.subVectors(e,this.center);const t=$i.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector($i,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Zi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint($i.copy(e.center).add(Zi)),this.expandByPoint($i.copy(e.center).sub(Zi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Ji=new Ni,Qi=new Ni,er=new Ni,tr=new Ni,nr=new Ni,ir=new Ni,rr=new Ni;class sr{constructor(e=new Ni,t=new Ni(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Ji)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ji.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ji.copy(this.origin).addScaledVector(this.direction,t),Ji.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Qi.copy(e).add(t).multiplyScalar(.5),er.copy(t).sub(e).normalize(),tr.copy(this.origin).sub(Qi);const r=.5*e.distanceTo(t),s=-this.direction.dot(er),a=tr.dot(this.direction),o=-tr.dot(er),l=tr.lengthSq(),c=Math.abs(1-s*s);let u,h,d,p;if(c>0)if(u=s*o-a,h=s*a-o,p=r*c,u>=0)if(h>=-p)if(h<=p){const e=1/c;u*=e,h*=e,d=u*(u+s*h+2*a)+h*(s*u+h+2*o)+l}else h=r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;else h=-r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;else h<=-p?(u=Math.max(0,-(-s*r+a)),h=u>0?-r:Math.min(Math.max(-r,-o),r),d=-u*u+h*(h+2*o)+l):h<=p?(u=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(u=Math.max(0,-(s*r+a)),h=u>0?r:Math.min(Math.max(-r,-o),r),d=-u*u+h*(h+2*o)+l);else h=s>0?-r:r,u=Math.max(0,-(s*h+a)),d=-u*u+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Qi).addScaledVector(er,h),d}intersectSphere(e,t){Ji.subVectors(e.center,this.origin);const n=Ji.dot(this.direction),i=Ji.dot(Ji)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),c>=0?(r=(e.min.y-h.y)*c,s=(e.max.y-h.y)*c):(r=(e.max.y-h.y)*c,s=(e.min.y-h.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(e.min.z-h.z)*u,o=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,o=(e.min.z-h.z)*u),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Ji)}intersectTriangle(e,t,n,i,r){nr.subVectors(t,e),ir.subVectors(n,e),rr.crossVectors(nr,ir);let s,a=this.direction.dot(rr);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}tr.subVectors(this.origin,e);const o=s*this.direction.dot(ir.crossVectors(tr,ir));if(o<0)return null;const l=s*this.direction.dot(nr.cross(tr));if(l<0)return null;if(o+l>a)return null;const c=-s*tr.dot(rr);return c<0?null:this.at(c/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class ar{constructor(e,t,n,i,r,s,a,o,l,c,u,h,d,p,m,f){ar.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l,c,u,h,d,p,m,f)}set(e,t,n,i,r,s,a,o,l,c,u,h,d,p,m,f){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=u,g[14]=h,g[3]=d,g[7]=p,g[11]=m,g[15]=f,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 ar).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,i=1/or.setFromMatrixColumn(e,0).length(),r=1/or.setFromMatrixColumn(e,1).length(),s=1/or.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=s*c,n=s*u,i=a*c,r=a*u;t[0]=o*c,t[4]=-o*u,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*c,n=o*u,i=l*c,r=l*u;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*u,t[5]=s*c,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*c,n=o*u,i=l*c,r=l*u;t[0]=e-r*a,t[4]=-s*u,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*c,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*c,n=s*u,i=a*c,r=a*u;t[0]=o*c,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*u,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*c,t[4]=r-e*u,t[8]=i*u+n,t[1]=u,t[5]=s*c,t[9]=-a*c,t[2]=-l*c,t[6]=n*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*c,t[4]=-u,t[8]=l*c,t[1]=e*u+r,t[5]=s*c,t[9]=n*u-i,t[2]=i*u-n,t[6]=a*c,t[10]=r*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(cr,e,ur)}lookAt(e,t,n){const i=this.elements;return pr.subVectors(e,t),0===pr.lengthSq()&&(pr.z=1),pr.normalize(),hr.crossVectors(n,pr),0===hr.lengthSq()&&(1===Math.abs(n.z)?pr.x+=1e-4:pr.z+=1e-4,pr.normalize(),hr.crossVectors(n,pr)),hr.normalize(),dr.crossVectors(pr,hr),i[0]=hr.x,i[4]=dr.x,i[8]=pr.x,i[1]=hr.y,i[5]=dr.y,i[9]=pr.y,i[2]=hr.z,i[6]=dr.z,i[10]=pr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],u=n[5],h=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],_=n[3],v=n[7],x=n[11],y=n[15],b=i[0],S=i[4],T=i[8],M=i[12],E=i[1],A=i[5],w=i[9],R=i[13],C=i[2],N=i[6],P=i[10],L=i[14],I=i[3],U=i[7],O=i[11],D=i[15];return r[0]=s*b+a*E+o*C+l*I,r[4]=s*S+a*A+o*N+l*U,r[8]=s*T+a*w+o*P+l*O,r[12]=s*M+a*R+o*L+l*D,r[1]=c*b+u*E+h*C+d*I,r[5]=c*S+u*A+h*N+d*U,r[9]=c*T+u*w+h*P+d*O,r[13]=c*M+u*R+h*L+d*D,r[2]=p*b+m*E+f*C+g*I,r[6]=p*S+m*A+f*N+g*U,r[10]=p*T+m*w+f*P+g*O,r[14]=p*M+m*R+f*L+g*D,r[3]=_*b+v*E+x*C+y*I,r[7]=_*S+v*A+x*N+y*U,r[11]=_*T+v*w+x*P+y*O,r[15]=_*M+v*R+x*L+y*D,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],c=e[2],u=e[6],h=e[10],d=e[14];return e[3]*(+r*o*u-i*l*u-r*a*h+n*l*h+i*a*d-n*o*d)+e[7]*(+t*o*d-t*l*h+r*s*h-i*s*d+i*l*c-r*o*c)+e[11]*(+t*l*u-t*a*d-r*s*u+n*s*d+r*a*c-n*l*c)+e[15]*(-i*a*c-t*o*u+t*a*h+i*s*u-n*s*h+n*o*c)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],u=e[9],h=e[10],d=e[11],p=e[12],m=e[13],f=e[14],g=e[15],_=u*f*l-m*h*l+m*o*d-a*f*d-u*o*g+a*h*g,v=p*h*l-c*f*l-p*o*d+s*f*d+c*o*g-s*h*g,x=c*m*l-p*u*l+p*a*d-s*m*d-c*a*g+s*u*g,y=p*u*o-c*m*o-p*a*h+s*m*h+c*a*f-s*u*f,b=t*_+n*v+i*x+r*y;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/b;return e[0]=_*S,e[1]=(m*h*r-u*f*r-m*i*d+n*f*d+u*i*g-n*h*g)*S,e[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,e[3]=(u*o*r-a*h*r-u*i*l+n*h*l+a*i*d-n*o*d)*S,e[4]=v*S,e[5]=(c*f*r-p*h*r+p*i*d-t*f*d-c*i*g+t*h*g)*S,e[6]=(p*o*r-s*f*r-p*i*l+t*f*l+s*i*g-t*o*g)*S,e[7]=(s*h*r-c*o*r+c*i*l-t*h*l-s*i*d+t*o*d)*S,e[8]=x*S,e[9]=(p*u*r-c*m*r-p*n*d+t*m*d+c*n*g-t*u*g)*S,e[10]=(s*m*r-p*a*r+p*n*l-t*m*l-s*n*g+t*a*g)*S,e[11]=(c*a*r-s*u*r-c*n*l+t*u*l+s*n*d-t*a*d)*S,e[12]=y*S,e[13]=(c*m*i-p*u*i+p*n*h-t*m*h-c*n*f+t*u*f)*S,e[14]=(p*a*i-s*m*i-p*n*o+t*m*o+s*n*f-t*a*f)*S,e[15]=(s*u*i-c*a*i+c*n*o-t*u*o-s*n*h+t*a*h)*S,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,c=s+s,u=a+a,h=r*l,d=r*c,p=r*u,m=s*c,f=s*u,g=a*u,_=o*l,v=o*c,x=o*u,y=n.x,b=n.y,S=n.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-v)*y,i[3]=0,i[4]=(d-x)*b,i[5]=(1-(h+g))*b,i[6]=(f+_)*b,i[7]=0,i[8]=(p+v)*S,i[9]=(f-_)*S,i[10]=(1-(h+m))*S,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=or.set(i[0],i[1],i[2]).length();const s=or.set(i[4],i[5],i[6]).length(),a=or.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],lr.copy(this);const o=1/r,l=1/s,c=1/a;return lr.elements[0]*=o,lr.elements[1]*=o,lr.elements[2]*=o,lr.elements[4]*=l,lr.elements[5]*=l,lr.elements[6]*=l,lr.elements[8]*=c,lr.elements[9]*=c,lr.elements[10]*=c,t.setFromRotationMatrix(lr),n.x=r,n.y=s,n.z=a,this}makePerspective(e,t,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(t-e),c=2*r/(n-i),u=(t+e)/(t-e),h=(n+i)/(n-i);let d,p;if(a===Dn)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Fn)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=u,o[12]=0,o[1]=0,o[5]=c,o[9]=h,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(e,t,n,i,r,s,a=2e3){const o=this.elements,l=1/(t-e),c=1/(n-i),u=1/(s-r),h=(t+e)*l,d=(n+i)*c;let p,m;if(a===Dn)p=(s+r)*u,m=-2*u;else{if(a!==Fn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*u,m=-1*u}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-h,o[1]=0,o[5]=2*c,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(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const or=new Ni,lr=new ar,cr=new Ni(0,0,0),ur=new Ni(1,1,1),hr=new Ni,dr=new Ni,pr=new Ni,mr=new ar,fr=new Ci;class gr{constructor(e=0,t=0,n=0,i=gr.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],u=i[2],h=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Wn(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Wn(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Wn(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Wn(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Wn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Wn(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return mr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(mr,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return fr.setFromEuler(this),this.setFromQuaternion(fr,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}gr.DEFAULT_ORDER="XYZ";class _r{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),u.length>0&&(n.nodes=u)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Ur.subVectors(i,t),Or.subVectors(n,t),Dr.subVectors(e,t);const s=Ur.dot(Ur),a=Ur.dot(Or),o=Ur.dot(Dr),l=Or.dot(Or),c=Or.dot(Dr),u=s*l-a*a;if(0===u)return r.set(0,0,0),null;const h=1/u,d=(l*o-a*c)*h,p=(s*c-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,Fr)&&(Fr.x>=0&&Fr.y>=0&&Fr.x+Fr.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,Fr)?(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,Fr.x),o.addScaledVector(s,Fr.y),o.addScaledVector(a,Fr.z),o)}static isFrontFacing(e,t,n,i){return Ur.subVectors(n,t),Or.subVectors(e,t),Ur.cross(Or).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ur.subVectors(this.c,this.b),Or.subVectors(this.a,this.b),.5*Ur.cross(Or).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return Wr.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;Br.subVectors(i,n),Vr.subVectors(r,n),Gr.subVectors(e,n);const o=Br.dot(Gr),l=Vr.dot(Gr);if(o<=0&&l<=0)return t.copy(n);kr.subVectors(e,i);const c=Br.dot(kr),u=Vr.dot(kr);if(c>=0&&u<=c)return t.copy(i);const h=o*u-c*l;if(h<=0&&o>=0&&c<=0)return s=o/(o-c),t.copy(n).addScaledVector(Br,s);Hr.subVectors(e,r);const d=Br.dot(Hr),p=Vr.dot(Hr);if(p>=0&&d<=p)return t.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(Vr,a);const f=c*p-d*u;if(f<=0&&u-c>=0&&d-p>=0)return zr.subVectors(r,i),a=(u-c)/(u-c+(d-p)),t.copy(i).addScaledVector(zr,a);const g=1/(f+m+h);return s=m*g,a=h*g,t.copy(n).addScaledVector(Br,s).addScaledVector(Vr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Xr={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},jr={h:0,s:0,l:0},qr={h:0,s:0,l:0};function Yr(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class $r{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Xt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,di.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=di.workingColorSpace){return this.r=e,this.g=t,this.b=n,di.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=di.workingColorSpace){if(e=Xn(e,1),t=Wn(t,0,1),n=Wn(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=Yr(r,i,e+1/3),this.g=Yr(r,i,e),this.b=Yr(r,i,e-1/3)}return di.toWorkingColorSpace(this,i),this}setStyle(e,t=Xt){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Xt){const n=Xr[e.toLowerCase()];return void 0!==n?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=pi(e.r),this.g=pi(e.g),this.b=pi(e.b),this}copyLinearToSRGB(e){return this.r=mi(e.r),this.g=mi(e.g),this.b=mi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Xt){return di.fromWorkingColorSpace(Zr.copy(this),e),65536*Math.round(Wn(255*Zr.r,0,255))+256*Math.round(Wn(255*Zr.g,0,255))+Math.round(Wn(255*Zr.b,0,255))}getHexString(e=Xt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=di.workingColorSpace){di.fromWorkingColorSpace(Zr.copy(this),t);const n=Zr.r,i=Zr.g,r=Zr.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=c<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),this.side!==h&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==C&&(n.blendSrc=this.blendSrc),this.blendDst!==N&&(n.blendDst=this.blendDst),this.blendEquation!==y&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==fn&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==en&&(n.stencilFail=this.stencilFail),this.stencilZFail!==en&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==en&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class Qr extends Jr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new $r(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 gr,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const es=ts();function ts(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;0==(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function ns(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Wn(e,-65504,65504),es.floatView[0]=e;const t=es.uint32View[0],n=t>>23&511;return es.baseTable[n]+((8388607&t)>>es.shiftTable[n])}function is(e){const t=e>>10;return es.uint32View[0]=es.mantissaTable[es.offsetTable[t]+(1023&e)]+es.exponentTable[t],es.floatView[0]}const rs={toHalfFloat:ns,fromHalfFloat:is},ss=new Ni,as=new Jn;class os{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=Mn,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=Le,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return oi("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;i0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone(t));const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}Es.copy(r).invert(),As.copy(e.ray).applyMatrix4(Es),null!==n.boundingBox&&!1===As.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,As)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,u=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;rn.far?null:{distance:c,point:Gs.clone(),object:e}}(e,t,n,i,Cs,Ns,Ps,zs);if(u){r&&(Us.fromBufferAttribute(r,o),Os.fromBufferAttribute(r,l),Ds.fromBufferAttribute(r,c),u.uv=Wr.getInterpolation(zs,Cs,Ns,Ps,Us,Os,Ds,new Jn)),s&&(Us.fromBufferAttribute(s,o),Os.fromBufferAttribute(s,l),Ds.fromBufferAttribute(s,c),u.uv1=Wr.getInterpolation(zs,Cs,Ns,Ps,Us,Os,Ds,new Jn)),a&&(Fs.fromBufferAttribute(a,o),Bs.fromBufferAttribute(a,l),Vs.fromBufferAttribute(a,c),u.normal=Wr.getInterpolation(zs,Cs,Ns,Ps,Fs,Bs,Vs,new Ni),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const e={a:o,b:l,c:c,normal:new Ni,materialIndex:0};Wr.getNormal(Cs,Ns,Ps,e.normal),u.face=e}return u}class Ws extends Ms{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],u=[];let h=0,d=0;function p(e,t,n,i,r,s,p,m,f,g,_){const v=s/f,x=p/g,y=s/2,b=p/2,S=m/2,T=f+1,M=g+1;let E=0,A=0;const w=new Ni;for(let s=0;s0?1:-1,c.push(w.x,w.y,w.z),u.push(o/f),u.push(1-s/g),E+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Zs extends Ir{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ar,this.projectionMatrix=new ar,this.projectionMatrixInverse=new ar,this.coordinateSystem=Dn}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Ks=new Ni,Js=new Jn,Qs=new Jn;class ea extends Zs{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*kn*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Gn*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*kn*Math.atan(Math.tan(.5*Gn*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Ks.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z),Ks.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z)}getViewSize(e,t){return this.getViewBounds(e,Js,Qs),t.subVectors(Qs,Js)}setViewOffset(e,t,n,i,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Gn*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const ta=-90;class na extends Ir{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new ea(ta,1,e,t);i.layers=this.layers,this.add(i);const r=new ea(ta,1,e,t);r.layers=this.layers,this.add(r);const s=new ea(ta,1,e,t);s.layers=this.layers,this.add(s);const a=new ea(ta,1,e,t);a.layers=this.layers,this.add(a);const o=new ea(ta,1,e,t);o.layers=this.layers,this.add(o);const l=new ea(ta,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===Dn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==Fn)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,s),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,o),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,i),e.render(t,c),e.setRenderTarget(u,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class ia extends bi{constructor(e,t,n,i,r,s,a,o,l,c){super(e=void 0!==e?e:[],t=void 0!==t?t:le,n,i,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class ra extends Mi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new ia(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:be}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ws(5,5,5),r=new $s({name:"CubemapFromEquirect",uniforms:Xs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:d,blending:0});r.uniforms.tEquirect.value=t;const s=new ks(i,r),a=t.minFilter;t.minFilter===Me&&(t.minFilter=be);return new na(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,n,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}const sa=new Ni,aa=new Ni,oa=new Qn;class la{constructor(e=new Ni(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=sa.subVectors(n,t).cross(aa.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(sa),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||oa.getNormalMatrix(e),i=this.coplanarPoint(sa).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const ca=new Ki,ua=new Ni;class ha{constructor(e=new la,t=new la,n=new la,i=new la,r=new la,s=new la){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3){const n=this.planes,i=e.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],u=i[6],h=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],_=i[13],v=i[14],x=i[15];if(n[0].setComponents(o-r,h-l,f-d,x-g).normalize(),n[1].setComponents(o+r,h+l,f+d,x+g).normalize(),n[2].setComponents(o+s,h+c,f+p,x+_).normalize(),n[3].setComponents(o-s,h-c,f-p,x-_).normalize(),n[4].setComponents(o-a,h-u,f-m,x-v).normalize(),t===Dn)n[5].setComponents(o+a,h+u,f+m,x+v).normalize();else{if(t!==Fn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(a,u,m,v).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),ca.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),ca.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ca)}intersectsSprite(e){return ca.center.set(0,0,0),ca.radius=.7071067811865476,ca.applyMatrix4(e.matrixWorld),this.intersectsSphere(ca)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,ua.y=i.normal.y>0?e.max.y:e.min.y,ua.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ua)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function da(){let e=null,t=!1,n=null,i=null;function r(t,s){n(t,s),i=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==n&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function pa(e,t){const n=t.isWebGL2,i=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),i.get(e)},remove:function(t){t.isInterleavedBufferAttribute&&(t=t.data);const n=i.get(t);n&&(e.deleteBuffer(n.buffer),i.delete(t))},update:function(t,r){if(t.isGLBufferAttribute){const e=i.get(t);return void((!e||e.version 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 )\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 )\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",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}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\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\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:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\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}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\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_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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_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\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.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.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.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 ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\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 ) && defined( MORPHTARGETS_TEXTURE )\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\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\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.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( 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( 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 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 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 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 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 shadow;\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 shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\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 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 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 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.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.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.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 OptimizedCineonToneMapping( 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\tfloat startCompression = 0.8 - 0.04;\n\tfloat 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(1, 1, 1), 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.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 ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\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#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_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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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}"},ga={common:{diffuse:{value:new $r(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Qn},alphaMap:{value:null},alphaMapTransform:{value:new Qn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Qn}},envmap:{envMap:{value:null},envMapRotation:{value:new Qn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Qn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Qn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Qn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Qn},normalScale:{value:new Jn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Qn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Qn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Qn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Qn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new $r(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{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 $r(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Qn},alphaTest:{value:0},uvTransform:{value:new Qn}},sprite:{diffuse:{value:new $r(16777215)},opacity:{value:1},center:{value:new Jn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Qn},alphaMap:{value:null},alphaMapTransform:{value:new Qn},alphaTest:{value:0}}},_a={basic:{uniforms:js([ga.common,ga.specularmap,ga.envmap,ga.aomap,ga.lightmap,ga.fog]),vertexShader:fa.meshbasic_vert,fragmentShader:fa.meshbasic_frag},lambert:{uniforms:js([ga.common,ga.specularmap,ga.envmap,ga.aomap,ga.lightmap,ga.emissivemap,ga.bumpmap,ga.normalmap,ga.displacementmap,ga.fog,ga.lights,{emissive:{value:new $r(0)}}]),vertexShader:fa.meshlambert_vert,fragmentShader:fa.meshlambert_frag},phong:{uniforms:js([ga.common,ga.specularmap,ga.envmap,ga.aomap,ga.lightmap,ga.emissivemap,ga.bumpmap,ga.normalmap,ga.displacementmap,ga.fog,ga.lights,{emissive:{value:new $r(0)},specular:{value:new $r(1118481)},shininess:{value:30}}]),vertexShader:fa.meshphong_vert,fragmentShader:fa.meshphong_frag},standard:{uniforms:js([ga.common,ga.envmap,ga.aomap,ga.lightmap,ga.emissivemap,ga.bumpmap,ga.normalmap,ga.displacementmap,ga.roughnessmap,ga.metalnessmap,ga.fog,ga.lights,{emissive:{value:new $r(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:fa.meshphysical_vert,fragmentShader:fa.meshphysical_frag},toon:{uniforms:js([ga.common,ga.aomap,ga.lightmap,ga.emissivemap,ga.bumpmap,ga.normalmap,ga.displacementmap,ga.gradientmap,ga.fog,ga.lights,{emissive:{value:new $r(0)}}]),vertexShader:fa.meshtoon_vert,fragmentShader:fa.meshtoon_frag},matcap:{uniforms:js([ga.common,ga.bumpmap,ga.normalmap,ga.displacementmap,ga.fog,{matcap:{value:null}}]),vertexShader:fa.meshmatcap_vert,fragmentShader:fa.meshmatcap_frag},points:{uniforms:js([ga.points,ga.fog]),vertexShader:fa.points_vert,fragmentShader:fa.points_frag},dashed:{uniforms:js([ga.common,ga.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:fa.linedashed_vert,fragmentShader:fa.linedashed_frag},depth:{uniforms:js([ga.common,ga.displacementmap]),vertexShader:fa.depth_vert,fragmentShader:fa.depth_frag},normal:{uniforms:js([ga.common,ga.bumpmap,ga.normalmap,ga.displacementmap,{opacity:{value:1}}]),vertexShader:fa.meshnormal_vert,fragmentShader:fa.meshnormal_frag},sprite:{uniforms:js([ga.sprite,ga.fog]),vertexShader:fa.sprite_vert,fragmentShader:fa.sprite_frag},background:{uniforms:{uvTransform:{value:new Qn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:fa.background_vert,fragmentShader:fa.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Qn}},vertexShader:fa.backgroundCube_vert,fragmentShader:fa.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:fa.cube_vert,fragmentShader:fa.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:fa.equirect_vert,fragmentShader:fa.equirect_frag},distanceRGBA:{uniforms:js([ga.common,ga.displacementmap,{referencePosition:{value:new Ni},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:fa.distanceRGBA_vert,fragmentShader:fa.distanceRGBA_frag},shadow:{uniforms:js([ga.lights,ga.fog,{color:{value:new $r(0)},opacity:{value:1}}]),vertexShader:fa.shadow_vert,fragmentShader:fa.shadow_frag}};_a.physical={uniforms:js([_a.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Qn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Qn},clearcoatNormalScale:{value:new Jn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Qn},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Qn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Qn},sheen:{value:0},sheenColor:{value:new $r(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Qn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Qn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Qn},transmissionSamplerSize:{value:new Jn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Qn},attenuationDistance:{value:0},attenuationColor:{value:new $r(0)},specularColor:{value:new $r(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Qn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Qn},anisotropyVector:{value:new Jn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Qn}}]),vertexShader:fa.meshphysical_vert,fragmentShader:fa.meshphysical_frag};const va={r:0,b:0,g:0},xa=new gr,ya=new ar;function ba(e,t,n,i,r,s,a){const o=new $r(0);let l,c,u=!0===s?0:1,p=null,m=0,f=null;function g(t,n){t.getRGB(va,qs(e)),i.buffers.color.setClear(va.r,va.g,va.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),u=t,g(o,u)},getClearAlpha:function(){return u},setClearAlpha:function(e){u=e,g(o,u)},render:function(s,_){let v=!1,x=!0===_.isScene?_.background:null;if(x&&x.isTexture){x=(_.backgroundBlurriness>0?n:t).get(x)}null===x?g(o,u):x&&x.isColor&&(g(x,1),v=!0);const y=e.xr.getEnvironmentBlendMode();"additive"===y?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===y&&i.buffers.color.setClear(0,0,0,0,a),(e.autoClear||v)&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),x&&(x.isCubeTexture||x.mapping===de)?(void 0===c&&(c=new ks(new Ws(1,1,1),new $s({name:"BackgroundCubeMaterial",uniforms:Xs(_a.backgroundCube.uniforms),vertexShader:_a.backgroundCube.vertexShader,fragmentShader:_a.backgroundCube.fragmentShader,side:d,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),xa.copy(_.backgroundRotation),xa.x*=-1,xa.y*=-1,xa.z*=-1,x.isCubeTexture&&!1===x.isRenderTargetTexture&&(xa.y*=-1,xa.z*=-1),c.material.uniforms.envMap.value=x,c.material.uniforms.flipEnvMap.value=x.isCubeTexture&&!1===x.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(ya.makeRotationFromEuler(xa)),c.material.toneMapped=di.getTransfer(x.colorSpace)!==Zt,p===x&&m===x.version&&f===e.toneMapping||(c.material.needsUpdate=!0,p=x,m=x.version,f=e.toneMapping),c.layers.enableAll(),s.unshift(c,c.geometry,c.material,0,0,null)):x&&x.isTexture&&(void 0===l&&(l=new ks(new ma(2,2),new $s({name:"BackgroundMaterial",uniforms:Xs(_a.background.uniforms),vertexShader:_a.background.vertexShader,fragmentShader:_a.background.fragmentShader,side:h,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=x,l.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,l.material.toneMapped=di.getTransfer(x.colorSpace)!==Zt,!0===x.matrixAutoUpdate&&x.updateMatrix(),l.material.uniforms.uvTransform.value.copy(x.matrix),p===x&&m===x.version&&f===e.toneMapping||(l.material.needsUpdate=!0,p=x,m=x.version,f=e.toneMapping),l.layers.enableAll(),s.unshift(l,l.geometry,l.material,0,0,null))}}}function Sa(e,t,n,i){const r=e.getParameter(e.MAX_VERTEX_ATTRIBS),s=i.isWebGL2?null:t.get("OES_vertex_array_object"),a=i.isWebGL2||null!==s,o={},l=p(null);let c=l,u=!1;function h(t){return i.isWebGL2?e.bindVertexArray(t):s.bindVertexArrayOES(t)}function d(t){return i.isWebGL2?e.deleteVertexArray(t):s.deleteVertexArrayOES(t)}function p(e){const t=[],n=[],i=[];for(let e=0;e=0){const n=r[t];let i=s[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;a++}}return c.attributesNum!==a||c.index!==i}(r,x,d,y),b&&function(e,t,n,i){const r={},s=t.attributes;let a=0;const o=n.getAttributes();for(const t in o){if(o[t].location>=0){let n=s[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,a++}}c.attributes=r,c.attributesNum=a,c.index=i}(r,x,d,y)}else{const e=!0===l.wireframe;c.geometry===x.id&&c.program===d.id&&c.wireframe===e||(c.geometry=x.id,c.program=d.id,c.wireframe=e,b=!0)}null!==y&&n.update(y,e.ELEMENT_ARRAY_BUFFER),(b||u)&&(u=!1,function(r,s,a,o){if(!1===i.isWebGL2&&(r.isInstancedMesh||o.isInstancedBufferGeometry)&&null===t.get("ANGLE_instanced_arrays"))return;m();const l=o.attributes,c=a.getAttributes(),u=s.defaultAttributeValues;for(const t in c){const s=c[t];if(s.location>=0){let a=l[t];if(void 0===a&&("instanceMatrix"===t&&r.instanceMatrix&&(a=r.instanceMatrix),"instanceColor"===t&&r.instanceColor&&(a=r.instanceColor)),void 0!==a){const t=a.normalized,l=a.itemSize,c=n.get(a);if(void 0===c)continue;const u=c.buffer,h=c.type,d=c.bytesPerElement,p=!0===i.isWebGL2&&(h===e.INT||h===e.UNSIGNED_INT||a.gpuType===Ne);if(a.isInterleavedBufferAttribute){const n=a.data,i=n.stride,c=a.offset;if(n.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"}const s="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=s||t.has("WEBGL_draw_buffers"),c=!0===n.logarithmicDepthBuffer,u=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),f=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),g=e.getParameter(e.MAX_VARYING_VECTORS),_=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),v=h>0,x=s||t.has("OES_texture_float");return{isWebGL2:s,drawBuffers:l,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:r,precision:a,logarithmicDepthBuffer:c,maxTextures:u,maxVertexTextures:h,maxTextureSize:d,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:f,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:v,floatFragmentTextures:x,floatVertexTextures:v&&x,maxSamples:s?e.getParameter(e.MAX_SAMPLES):0}}function Ea(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new la,o=new Qn,l={value:null,needsUpdate:!1};function c(e,n,i,r){const s=null!==e?e.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=m.clippingState||null;l.value=r,r=c(h,o,t,u);for(let e=0;e!==t;++e)r[e]=n[e];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function Aa(e){let t=new WeakMap;function n(e,t){return t===ue?e.mapping=le:t===he&&(e.mapping=ce),e}function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===ue||s===he){if(t.has(r)){return n(t.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new ra(s.height);return a.fromEquirectangularTexture(e,r),t.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){t=new WeakMap}}}class wa extends Zs{constructor(e=-1,t=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-e,s=n+e,a=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,s=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}const Ra=[.125,.215,.35,.446,.526,.582],Ca=20,Na=new wa,Pa=new $r;let La=null,Ia=0,Ua=0;const Oa=(1+Math.sqrt(5))/2,Da=1/Oa,Fa=[new Ni(1,1,1),new Ni(-1,1,1),new Ni(1,1,-1),new Ni(-1,1,-1),new Ni(0,Oa,Da),new Ni(0,Oa,-Da),new Ni(Da,0,Oa),new Ni(-Da,0,Oa),new Ni(Oa,Da,0),new Ni(-Oa,Da,0)];class Ba{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,i=100){La=this._renderer.getRenderTarget(),Ia=this._renderer.getActiveCubeFace(),Ua=this._renderer.getActiveMipmapLevel(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,n,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=ka(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Ga(),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?o=Ra[a-e+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),c=-l,u=1+l,h=[c,c,u,c,u,u,c,c,u,u,c,u],d=6,p=6,m=3,f=2,g=1,_=new Float32Array(m*p*d),v=new Float32Array(f*p*d),x=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(i,m*p*e),v.set(h,f*p*e);const r=[e,e,e,e,e,e];x.set(r,g*p*e)}const y=new Ms;y.setAttribute("position",new os(_,m)),y.setAttribute("uv",new os(v,f)),y.setAttribute("faceIndex",new os(x,g)),t.push(y),r>4&&r--}return{lodPlanes:t,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(Ca),r=new Ni(0,1,0),s=new $s({name:"SphericalGaussianBlur",defines:{n:Ca,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Ha(),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:0,depthTest:!1,depthWrite:!1});return s}(i,e,t)}return i}_compileMaterial(e){const t=new ks(this._lodPlanes[0],e);this._renderer.compile(t,Na)}_sceneToCubeUV(e,t,n,i){const r=new ea(90,1,t,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Pa),o.toneMapping=K,o.autoClear=!1;const u=new Qr({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1}),h=new ks(new Ws,u);let p=!1;const m=e.background;m?m.isColor&&(u.color.copy(m),e.background=null,p=!0):(u.color.copy(Pa),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(r.up.set(0,s[t],0),r.lookAt(a[t],0,0)):1===n?(r.up.set(0,0,s[t]),r.lookAt(0,a[t],0)):(r.up.set(0,s[t],0),r.lookAt(0,0,a[t]));const l=this._cubeSize;za(i,n*l,t>2?l:0,l,l),o.setRenderTarget(i),p&&o.render(h,r),o.render(e,r)}h.geometry.dispose(),h.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=m}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===le||e.mapping===ce;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=ka()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Ga());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new ks(this._lodPlanes[0],r);r.uniforms.envMap.value=e;const a=this._cubeSize;za(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Na)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;for(let t=1;tCa&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(c,Na)}}function Va(e,t,n){const i=new Mi(e,t,n);return i.texture.mapping=de,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function za(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function Ga(){return new $s({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ha(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function ka(){return new $s({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ha(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Ha(){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 Wa(e){let t=new WeakMap,n=null;function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===ue||s===he,o=s===le||s===ce;if(a||o){if(r.isRenderTargetTexture&&!0===r.needsPMREMUpdate){r.needsPMREMUpdate=!1;let i=t.get(r);return null===n&&(n=new Ba(e)),i=a?n.fromEquirectangular(r,i):n.fromCubemap(r,i),t.set(r,i),i.texture}if(t.has(r))return t.get(r).texture;{const s=r.image;if(a&&s&&s.height>0||o&&s&&function(e){let t=0;const n=6;for(let i=0;it.maxTextureSize&&(T=Math.ceil(S/t.maxTextureSize),S=t.maxTextureSize);const M=new Float32Array(S*T*4*p),E=new Ei(M,S,T,p);E.type=Le,E.needsUpdate=!0;const A=4*b;for(let R=0;R0)return e;const r=t*n;let s=so[r];if(void 0===s&&(s=new Float32Array(r),so[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function ho(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function ul(e,t){const n=function(e){const t=di.getPrimaries(di.workingColorSpace),n=di.getPrimaries(e);let i;switch(t===n?i="":t===Jt&&n===Kt?i="LinearDisplayP3ToLinearSRGB":t===Kt&&n===Jt&&(i="LinearSRGBToLinearDisplayP3"),e){case jt:case Yt:return[i,"LinearTransferOETF"];case Xt:case qt:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",e),[i,"LinearTransferOETF"]}}(t);return`vec4 ${e}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function hl(e,t){let n;switch(t){case J:n="Linear";break;case Q:n="Reinhard";break;case ee:n="OptimizedCineon";break;case te:n="ACESFilmic";break;case ie:n="AgX";break;case re:n="Neutral";break;case ne:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function dl(e){return""!==e}function pl(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 ml(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const fl=/^[ \t]*#include +<([\w\d./]+)>/gm;function gl(e){return e.replace(fl,vl)}const _l=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function vl(e,t){let n=fa[t];if(void 0===n){const e=_l.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=fa[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return gl(n)}const xl=/#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 yl(e){return e.replace(xl,bl)}function bl(e,t,n,i){let r="";for(let e=parseInt(t);e0&&(y+="\n"),b=[g,"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v].filter(dl).join("\n"),b.length>0&&(b+="\n")):(y=[Sl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",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 "+p:"",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&&n.isWebGL2?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+h:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.useLegacyLights?"#define LEGACY_LIGHTS":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","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","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(dl).join("\n"),b=[g,Sl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,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 "+p:"",n.envMap?"#define "+m:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.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.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas?"#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 "+h:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.useLegacyLights?"#define LEGACY_LIGHTS":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==K?"#define TONE_MAPPING":"",n.toneMapping!==K?fa.tonemapping_pars_fragment:"",n.toneMapping!==K?hl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",fa.colorspace_pars_fragment,ul("linearToOutputTexel",n.outputColorSpace),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(dl).join("\n")),a=gl(a),a=pl(a,n),a=ml(a,n),o=gl(o),o=pl(o,n),o=ml(o,n),a=yl(a),o=yl(o),n.isWebGL2&&!0!==n.isRawShaderMaterial&&(S="#version 300 es\n",y=[_,"precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+y,b=["precision mediump sampler2DArray;","#define varying in",n.glslVersion===Un?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Un?"":"#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"+b);const T=S+y+a,M=S+b+o,E=al(r,r.VERTEX_SHADER,T),A=al(r,r.FRAGMENT_SHADER,M);function w(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(x).trim(),i=r.getShaderInfoLog(E).trim(),s=r.getShaderInfoLog(A).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(x,r.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,x,E,A);else{const e=cl(r,E,"vertex"),i=cl(r,A,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(x,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(t.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:y},fragmentShader:{log:s,prefix:b}})}r.deleteShader(E),r.deleteShader(A),R=new sl(r,x),C=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r0,Y=s.clearcoat>0,$=s.iridescence>0,Z=s.sheen>0,J=s.transmission>0,Q=q&&!!s.anisotropyMap,ee=Y&&!!s.clearcoatMap,te=Y&&!!s.clearcoatNormalMap,ne=Y&&!!s.clearcoatRoughnessMap,ie=$&&!!s.iridescenceMap,re=$&&!!s.iridescenceThicknessMap,se=Z&&!!s.sheenColorMap,ae=Z&&!!s.sheenRoughnessMap,oe=!!s.specularMap,le=!!s.specularColorMap,ce=!!s.specularIntensityMap,ue=J&&!!s.transmissionMap,he=J&&!!s.thicknessMap,pe=!!s.gradientMap,me=!!s.alphaMap,fe=s.alphaTest>0,ge=!!s.alphaHash,_e=!!s.extensions;let ve=K;s.toneMapped&&(null!==I&&!0!==I.isXRRenderTarget||(ve=e.toneMapping));const xe={isWebGL2:h,shaderID:E,shaderType:s.type,shaderName:s.name,vertexShader:R,fragmentShader:C,defines:s.defines,customVertexShaderID:N,customFragmentShaderID:P,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:f,batching:O,instancing:U,instancingColor:U&&null!==x.instanceColor,instancingMorph:U&&null!==x.morphTexture,supportsVertexTextures:m,outputColorSpace:null===I?e.outputColorSpace:!0===I.isXRRenderTarget?I.texture.colorSpace:jt,alphaToCoverage:!!s.alphaToCoverage,map:D,matcap:F,envMap:B,envMapMode:B&&T.mapping,envMapCubeUVHeight:M,aoMap:V,lightMap:z,bumpMap:G,normalMap:k,displacementMap:m&&H,emissiveMap:W,normalMapObjectSpace:k&&1===s.normalMapType,normalMapTangentSpace:k&&0===s.normalMapType,metalnessMap:X,roughnessMap:j,anisotropy:q,anisotropyMap:Q,clearcoat:Y,clearcoatMap:ee,clearcoatNormalMap:te,clearcoatRoughnessMap:ne,iridescence:$,iridescenceMap:ie,iridescenceThicknessMap:re,sheen:Z,sheenColorMap:se,sheenRoughnessMap:ae,specularMap:oe,specularColorMap:le,specularIntensityMap:ce,transmission:J,transmissionMap:ue,thicknessMap:he,gradientMap:pe,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:me,alphaTest:fe,alphaHash:ge,combine:s.combine,mapUv:D&&_(s.map.channel),aoMapUv:V&&_(s.aoMap.channel),lightMapUv:z&&_(s.lightMap.channel),bumpMapUv:G&&_(s.bumpMap.channel),normalMapUv:k&&_(s.normalMap.channel),displacementMapUv:H&&_(s.displacementMap.channel),emissiveMapUv:W&&_(s.emissiveMap.channel),metalnessMapUv:X&&_(s.metalnessMap.channel),roughnessMapUv:j&&_(s.roughnessMap.channel),anisotropyMapUv:Q&&_(s.anisotropyMap.channel),clearcoatMapUv:ee&&_(s.clearcoatMap.channel),clearcoatNormalMapUv:te&&_(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ne&&_(s.clearcoatRoughnessMap.channel),iridescenceMapUv:ie&&_(s.iridescenceMap.channel),iridescenceThicknessMapUv:re&&_(s.iridescenceThicknessMap.channel),sheenColorMapUv:se&&_(s.sheenColorMap.channel),sheenRoughnessMapUv:ae&&_(s.sheenRoughnessMap.channel),specularMapUv:oe&&_(s.specularMap.channel),specularColorMapUv:le&&_(s.specularColorMap.channel),specularIntensityMapUv:ce&&_(s.specularIntensityMap.channel),transmissionMapUv:ue&&_(s.transmissionMap.channel),thicknessMapUv:he&&_(s.thicknessMap.channel),alphaMapUv:me&&_(s.alphaMap.channel),vertexTangents:!!b.attributes.tangent&&(k||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!b.attributes.color&&4===b.attributes.color.itemSize,pointsUvs:!0===x.isPoints&&!!b.attributes.uv&&(D||me),fog:!!y,useFog:!0===s.fog,fogExp2:!!y&&y.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:p,skinning:!0===x.isSkinnedMesh,morphTargets:void 0!==b.morphAttributes.position,morphNormals:void 0!==b.morphAttributes.normal,morphColors:void 0!==b.morphAttributes.color,morphTargetsCount:w,morphTextureStride:L,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:ve,useLegacyLights:e._useLegacyLights,decodeVideoTexture:D&&!0===s.map.isVideoTexture&&di.getTransfer(s.map.colorSpace)===Zt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:s.side===d,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionDerivatives:_e&&!0===s.extensions.derivatives,extensionFragDepth:_e&&!0===s.extensions.fragDepth,extensionDrawBuffers:_e&&!0===s.extensions.drawBuffers,extensionShaderTextureLOD:_e&&!0===s.extensions.shaderTextureLOD,extensionClipCullDistance:_e&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:_e&&!0===s.extensions.multiDraw&&i.has("WEBGL_multi_draw"),rendererExtensionFragDepth:h||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||i.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return xe.vertexUv1s=c.has(1),xe.vertexUv2s=c.has(2),xe.vertexUv3s=c.has(3),c.clear(),xe},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){o.disableAll(),t.isWebGL2&&o.enable(0);t.supportsVertexTextures&&o.enable(1);t.instancing&&o.enable(2);t.instancingColor&&o.enable(3);t.instancingMorph&&o.enable(4);t.matcap&&o.enable(5);t.envMap&&o.enable(6);t.normalMapObjectSpace&&o.enable(7);t.normalMapTangentSpace&&o.enable(8);t.clearcoat&&o.enable(9);t.iridescence&&o.enable(10);t.alphaTest&&o.enable(11);t.vertexColors&&o.enable(12);t.vertexAlphas&&o.enable(13);t.vertexUv1s&&o.enable(14);t.vertexUv2s&&o.enable(15);t.vertexUv3s&&o.enable(16);t.vertexTangents&&o.enable(17);t.anisotropy&&o.enable(18);t.alphaHash&&o.enable(19);t.batching&&o.enable(20);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.skinning&&o.enable(4);t.morphTargets&&o.enable(5);t.morphNormals&&o.enable(6);t.morphColors&&o.enable(7);t.premultipliedAlpha&&o.enable(8);t.shadowMapEnabled&&o.enable(9);t.useLegacyLights&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.transmission&&o.enable(15);t.sheen&&o.enable(16);t.opaque&&o.enable(17);t.pointsUvs&&o.enable(18);t.decodeVideoTexture&&o.enable(19);t.alphaToCoverage&&o.enable(20);e.push(o.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=g[e.type];let n;if(t){const e=_a[t];n=Ys.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i;for(let e=0,t=u.length;e0?i.push(u):!0===a.transparent?r.push(u):n.push(u)},unshift:function(e,t,a,o,l,c){const u=s(e,t,a,o,l,c);a.transmission>0?i.unshift(u):!0===a.transparent?r.unshift(u):n.unshift(u)},finish:function(){for(let n=t,i=e.length;n1&&n.sort(e||Cl),i.length>1&&i.sort(t||Nl),r.length>1&&r.sort(t||Nl)}}}function Ll(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new Pl,e.set(t,[r])):n>=i.length?(r=new Pl,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function Il(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new Ni,color:new $r};break;case"SpotLight":n={position:new Ni,direction:new Ni,color:new $r,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Ni,color:new $r,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Ni,skyColor:new $r,groundColor:new $r};break;case"RectAreaLight":n={color:new $r,position:new Ni,halfWidth:new Ni,halfHeight:new Ni}}return e[t.id]=n,n}}}let Ul=0;function Ol(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Dl(e,t){const n=new Il,i=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Jn};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Jn,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),r={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++)r.probe.push(new Ni);const s=new Ni,a=new ar,o=new ar;return{setup:function(s,a){let o=0,l=0,c=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let u=0,h=0,d=0,p=0,m=0,f=0,g=0,_=0,v=0,x=0,y=0;s.sort(Ol);const b=!0===a?Math.PI:1;for(let e=0,t=s.length;e0&&(t.isWebGL2?!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=ga.LTC_FLOAT_1,r.rectAreaLTC2=ga.LTC_FLOAT_2):(r.rectAreaLTC1=ga.LTC_HALF_1,r.rectAreaLTC2=ga.LTC_HALF_2):!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=ga.LTC_FLOAT_1,r.rectAreaLTC2=ga.LTC_FLOAT_2):!0===e.has("OES_texture_half_float_linear")?(r.rectAreaLTC1=ga.LTC_HALF_1,r.rectAreaLTC2=ga.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),r.ambient[0]=o,r.ambient[1]=l,r.ambient[2]=c;const S=r.hash;S.directionalLength===u&&S.pointLength===h&&S.spotLength===d&&S.rectAreaLength===p&&S.hemiLength===m&&S.numDirectionalShadows===f&&S.numPointShadows===g&&S.numSpotShadows===_&&S.numSpotMaps===v&&S.numLightProbes===y||(r.directional.length=u,r.spot.length=d,r.rectArea.length=p,r.point.length=h,r.hemi.length=m,r.directionalShadow.length=f,r.directionalShadowMap.length=f,r.pointShadow.length=g,r.pointShadowMap.length=g,r.spotShadow.length=_,r.spotShadowMap.length=_,r.directionalShadowMatrix.length=f,r.pointShadowMatrix.length=g,r.spotLightMatrix.length=_+v-x,r.spotLightMap.length=v,r.numSpotLightShadowsWithMaps=x,r.numLightProbes=y,S.directionalLength=u,S.pointLength=h,S.spotLength=d,S.rectAreaLength=p,S.hemiLength=m,S.numDirectionalShadows=f,S.numPointShadows=g,S.numSpotShadows=_,S.numSpotMaps=v,S.numLightProbes=y,r.version=Ul++)},setupView:function(e,t){let n=0,i=0,l=0,c=0,u=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t=s.length?(a=new Fl(e,t),s.push(a)):a=s[r],a},dispose:function(){n=new WeakMap}}}class Vl extends Jr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class zl extends Jr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}function Gl(e,t,n){let i=new ha;const r=new Jn,s=new Jn,a=new Si,o=new Vl({depthPacking:3201}),c=new zl,p={},m=n.maxTextureSize,f={[h]:d,[d]:h,2:2},g=new $s({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Jn},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}"}),_=g.clone();_.defines.HORIZONTAL_PASS=1;const v=new Ms;v.setAttribute("position",new os(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new ks(v,g),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=l;let b=this.type;function S(n,i){const s=t.update(x);g.defines.VSM_SAMPLES!==n.blurSamples&&(g.defines.VSM_SAMPLES=n.blurSamples,_.defines.VSM_SAMPLES=n.blurSamples,g.needsUpdate=!0,_.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Mi(r.x,r.y)),g.uniforms.shadow_pass.value=n.map.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,g,x,null),_.uniforms.shadow_pass.value=n.mapPass.texture,_.uniforms.resolution.value=n.mapSize,_.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,_,x,null)}function T(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?c:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const e=s.uuid,t=n.uuid;let i=p[e];void 0===i&&(i={},p[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",E)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=r===u?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:f[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function M(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&o===u)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let c=0,u=t.length;cm||r.y>m)&&(r.x>m&&(s.x=Math.floor(m/g.x),r.x=s.x*g.x,h.mapSize.x=s.x),r.y>m&&(s.y=Math.floor(m/g.y),r.y=s.y*g.y,h.mapSize.y=s.y)),null===h.map||!0===p||!0===f){const e=this.type!==u?{minFilter:ge,magFilter:ge}:{};null!==h.map&&h.map.dispose(),h.map=new Mi(r.x,r.y,e),h.map.texture.name=c.name+".shadowMap",h.camera.updateProjectionMatrix()}e.setRenderTarget(h.map),e.clear();const _=h.getViewportCount();for(let e=0;e<_;e++){const t=h.getViewport(e);a.set(s.x*t.x,s.y*t.y,s.x*t.z,s.y*t.w),d.viewport(a),h.updateMatrices(c,e),i=h.getFrustum(),M(n,o,h.camera,c,this.type)}!0!==h.isPointLightShadow&&this.type===u&&S(h,o),h.needsUpdate=!1}b=this.type,y.needsUpdate=!1,e.setRenderTarget(l,c,h)}}function kl(e,t,n){const i=n.isWebGL2;const r=new function(){let t=!1;const n=new Si;let i=null;const r=new Si(0,0,0,0);return{setMask:function(n){i===n||t||(e.colorMask(n,n,n,n),i=n)},setLocked:function(e){t=e},setClear:function(t,i,s,a,o){!0===o&&(t*=a,i*=a,s*=a),n.set(t,i,s,a),!1===r.equals(n)&&(e.clearColor(t,i,s,a),r.copy(n))},reset:function(){t=!1,i=null,r.set(-1,0,0,0)}}},s=new function(){let t=!1,n=null,i=null,r=null;return{setTest:function(t){t?ie(e.DEPTH_TEST):re(e.DEPTH_TEST)},setMask:function(i){n===i||t||(e.depthMask(i),n=i)},setFunc:function(t){if(i!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:default:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL)}i=t}},setLocked:function(e){t=e},setClear:function(t){r!==t&&(e.clearDepth(t),r=t)},reset:function(){t=!1,n=null,i=null,r=null}}},a=new function(){let t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(n){t||(n?ie(e.STENCIL_TEST):re(e.STENCIL_TEST))},setMask:function(i){n===i||t||(e.stencilMask(i),n=i)},setFunc:function(t,n,a){i===t&&r===n&&s===a||(e.stencilFunc(t,n,a),i=t,r=n,s=a)},setOp:function(t,n,i){a===t&&o===n&&l===i||(e.stencilOp(t,n,i),a=t,o=n,l=i)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null}}},o=new WeakMap,l=new WeakMap;let c={},u={},h=new WeakMap,p=[],m=null,f=!1,g=null,_=null,v=null,x=null,T=null,M=null,D=null,F=new $r(0,0,0),B=0,V=!1,z=null,G=null,k=null,H=null,W=null;const X=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let j=!1,q=0;const Y=e.getParameter(e.VERSION);-1!==Y.indexOf("WebGL")?(q=parseFloat(/^WebGL (\d)/.exec(Y)[1]),j=q>=1):-1!==Y.indexOf("OpenGL ES")&&(q=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),j=q>=2);let $=null,Z={};const K=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),Q=(new Si).fromArray(K),ee=(new Si).fromArray(J);function te(t,n,r,s){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;oi||s.height>i)&&(r=i/Math.max(s.width,s.height)),r<1||!0===t){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 i=t?Yn:Math.floor,a=i(r*s.width),o=i(r*s.height);void 0===d&&(d=f(a,o));const l=n?f(a,o):d;l.width=a,l.height=o;return l.getContext("2d").drawImage(e,0,0,a,o),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+s.width+"x"+s.height+") to ("+a+"x"+o+")."),l}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+s.width+"x"+s.height+")."),e}return e}function _(e){const t=z(e);return qn(t.width)&&qn(t.height)}function v(e,t){return e.generateMipmaps&&t&&e.minFilter!==ge&&e.minFilter!==be}function x(t){e.generateMipmap(t)}function y(n,i,r,s,a=!1){if(!1===o)return i;if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let l=i;if(i===e.RED&&(r===e.FLOAT&&(l=e.R32F),r===e.HALF_FLOAT&&(l=e.R16F),r===e.UNSIGNED_BYTE&&(l=e.R8)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(l=e.R8UI),r===e.UNSIGNED_SHORT&&(l=e.R16UI),r===e.UNSIGNED_INT&&(l=e.R32UI),r===e.BYTE&&(l=e.R8I),r===e.SHORT&&(l=e.R16I),r===e.INT&&(l=e.R32I)),i===e.RG&&(r===e.FLOAT&&(l=e.RG32F),r===e.HALF_FLOAT&&(l=e.RG16F),r===e.UNSIGNED_BYTE&&(l=e.RG8)),i===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(l=e.RG8UI),r===e.UNSIGNED_SHORT&&(l=e.RG16UI),r===e.UNSIGNED_INT&&(l=e.RG32UI),r===e.BYTE&&(l=e.RG8I),r===e.SHORT&&(l=e.RG16I),r===e.INT&&(l=e.RG32I)),i===e.RGBA){const t=a?$t:di.getTransfer(s);r===e.FLOAT&&(l=e.RGBA32F),r===e.HALF_FLOAT&&(l=e.RGBA16F),r===e.UNSIGNED_BYTE&&(l=t===Zt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return l!==e.R16F&&l!==e.R32F&&l!==e.RG16F&&l!==e.RG32F&&l!==e.RGBA16F&&l!==e.RGBA32F||t.get("EXT_color_buffer_float"),l}function b(e,t,n){return!0===v(e,n)||e.isFramebufferTexture&&e.minFilter!==ge&&e.minFilter!==be?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 S(t){return t===ge||t===_e||t===xe?e.NEAREST:e.LINEAR}function T(e){const t=e.target;t.removeEventListener("dispose",T),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=p.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&E(e),0===Object.keys(r).length&&p.delete(n)}i.remove(e)}(t),t.isVideoTexture&&h.delete(t)}function M(t){const n=t.target;n.removeEventListener("dispose",M),function(t){const n=i.get(t);t.depthTexture&&t.depthTexture.dispose();if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let i=0;i0&&s.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void I(s,t,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const R={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[fe]:e.MIRRORED_REPEAT},C={[ge]:e.NEAREST,[_e]:e.NEAREST_MIPMAP_NEAREST,[xe]:e.NEAREST_MIPMAP_LINEAR,[be]:e.LINEAR,[Se]:e.LINEAR_MIPMAP_NEAREST,[Me]:e.LINEAR_MIPMAP_LINEAR},N={[gn]:e.NEVER,[Tn]:e.ALWAYS,[_n]:e.LESS,[xn]:e.LEQUAL,[vn]:e.EQUAL,[Sn]:e.GEQUAL,[yn]:e.GREATER,[bn]:e.NOTEQUAL};function P(n,s,a){if(s.type!==Le||!1!==t.has("OES_texture_float_linear")||s.magFilter!==be&&s.magFilter!==Se&&s.magFilter!==xe&&s.magFilter!==Me&&s.minFilter!==be&&s.minFilter!==Se&&s.minFilter!==xe&&s.minFilter!==Me||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),a?(e.texParameteri(n,e.TEXTURE_WRAP_S,R[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,R[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,R[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,C[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,C[s.minFilter])):(e.texParameteri(n,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(n,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,e.CLAMP_TO_EDGE),s.wrapS===me&&s.wrapT===me||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),e.texParameteri(n,e.TEXTURE_MAG_FILTER,S(s.magFilter)),e.texParameteri(n,e.TEXTURE_MIN_FILTER,S(s.minFilter)),s.minFilter!==ge&&s.minFilter!==be&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,N[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===ge)return;if(s.minFilter!==xe&&s.minFilter!==Me)return;if(s.type===Le&&!1===t.has("OES_texture_float_linear"))return;if(!1===o&&s.type===Ie&&!1===t.has("OES_texture_half_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function L(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",T));const r=n.source;let s=p.get(r);void 0===s&&(s={},p.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&E(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function I(t,a,l){let c=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(c=e.TEXTURE_3D);const u=L(t,a),h=a.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+l);const d=i.get(h);if(h.version!==d.__version||!0===u){n.activeTexture(e.TEXTURE0+l);const t=di.getPrimaries(di.workingColorSpace),i=a.colorSpace===Wt?null:di.getPrimaries(a.colorSpace),p=a.colorSpace===Wt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,p);const m=function(e){return!o&&(e.wrapS!==me||e.wrapT!==me||e.minFilter!==ge&&e.minFilter!==be)}(a)&&!1===_(a.image);let f=g(a.image,m,!1,r.maxTextureSize);f=V(a,f);const S=_(f)||o,T=s.convert(a.format,a.colorSpace);let M,E=s.convert(a.type),A=y(a.internalFormat,T,E,a.colorSpace,a.isVideoTexture);P(c,a,S);const w=a.mipmaps,R=o&&!0!==a.isVideoTexture&&A!==nt,C=void 0===d.__version||!0===u,N=h.dataReady,L=b(a,f,S);if(a.isDepthTexture)A=e.DEPTH_COMPONENT,o?A=a.type===Le?e.DEPTH_COMPONENT32F:a.type===Pe?e.DEPTH_COMPONENT24:a.type===De?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT16:a.type===Le&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),a.format===Ge&&A===e.DEPTH_COMPONENT&&a.type!==Ce&&a.type!==Pe&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),a.type=Pe,E=s.convert(a.type)),a.format===ke&&A===e.DEPTH_COMPONENT&&(A=e.DEPTH_STENCIL,a.type!==De&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),a.type=De,E=s.convert(a.type))),C&&(R?n.texStorage2D(e.TEXTURE_2D,1,A,f.width,f.height):n.texImage2D(e.TEXTURE_2D,0,A,f.width,f.height,0,T,E,null));else if(a.isDataTexture)if(w.length>0&&S){R&&C&&n.texStorage2D(e.TEXTURE_2D,L,A,w[0].width,w[0].height);for(let t=0,i=w.length;t>=1,i>>=1}}else if(w.length>0&&S){if(R&&C){const t=z(w[0]);n.texStorage2D(e.TEXTURE_2D,L,A,t.width,t.height)}for(let t=0,i=w.length;t>u),i=Math.max(1,r.height>>u);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?n.texImage3D(c,u,p,t,i,r.depth,0,h,d,null):n.texImage2D(c,u,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),B(r)?l.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,o,c,i.get(a).__webglTexture,0,F(r)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,o,c,i.get(a).__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function O(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer&&!n.stencilBuffer){let r=!0===o?e.DEPTH_COMPONENT24:e.DEPTH_COMPONENT16;if(i||B(n)){const t=n.depthTexture;t&&t.isDepthTexture&&(t.type===Le?r=e.DEPTH_COMPONENT32F:t.type===Pe&&(r=e.DEPTH_COMPONENT24));const i=F(n);B(n)?l.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,i,r,n.width,n.height):e.renderbufferStorageMultisample(e.RENDERBUFFER,i,r,n.width,n.height)}else e.renderbufferStorage(e.RENDERBUFFER,r,n.width,n.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)}else if(n.depthBuffer&&n.stencilBuffer){const r=F(n);i&&!1===B(n)?e.renderbufferStorageMultisample(e.RENDERBUFFER,r,e.DEPTH24_STENCIL8,n.width,n.height):B(n)?l.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,r,e.DEPTH24_STENCIL8,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function V(e,n){const i=e.colorSpace,r=e.format,s=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||e.format===On||i!==jt&&i!==Wt&&(di.getTransfer(i)===Zt?!1===o?!0===t.has("EXT_sRGB")&&r===Be?(e.format=On,e.minFilter=be,e.generateMipmaps=!1):n=gi.sRGBToLinear(n):r===Be&&s===Ae||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",i)),n}function z(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=A;return e>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),A+=1,e},this.resetTextureUnits=function(){A=0},this.setTexture2D=w,this.setTexture2DArray=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?I(s,t,r):n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r)},this.setTexture3D=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?I(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const l=i.get(t);t.version>0&&l.__version!==t.version?function(t,a,l){if(6!==a.image.length)return;const c=L(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+l);const h=i.get(u);if(u.version!==h.__version||!0===c){n.activeTexture(e.TEXTURE0+l);const t=di.getPrimaries(di.workingColorSpace),i=a.colorSpace===Wt?null:di.getPrimaries(a.colorSpace),d=a.colorSpace===Wt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);const p=a.isCompressedTexture||a.image[0].isCompressedTexture,m=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=p||m?m?a.image[e].image:a.image[e]:g(a.image[e],!1,!0,r.maxCubemapSize),f[e]=V(a,f[e]);const S=f[0],T=_(S)||o,M=s.convert(a.format,a.colorSpace),E=s.convert(a.type),A=y(a.internalFormat,M,E,a.colorSpace),w=o&&!0!==a.isVideoTexture,R=void 0===h.__version||!0===c,C=u.dataReady;let N,L=b(a,S,T);if(P(e.TEXTURE_CUBE_MAP,a,T),p){w&&R&&n.texStorage2D(e.TEXTURE_CUBE_MAP,L,A,S.width,S.height);for(let t=0;t<6;t++){N=f[t].mipmaps;for(let i=0;i0&&L++;const t=z(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,L,A,t.width,t.height)}for(let t=0;t<6;t++)if(m){w?C&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,M,E,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,A,f[t].width,f[t].height,0,M,E,f[t].data);for(let i=0;i1,m=_(t)||o;if(p||(void 0===u.__webglTexture&&(u.__webglTexture=e.createTexture()),u.__version=l.version,a.memory.textures++),d){c.__webglFramebuffer=[];for(let t=0;t<6;t++)if(o&&l.mipmaps&&l.mipmaps.length>0){c.__webglFramebuffer[t]=[];for(let n=0;n0){c.__webglFramebuffer=[];for(let t=0;t0&&!1===B(t)){c.__webglMultisampledFramebuffer=e.createFramebuffer(),c.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0&&!1===B(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const l=[],u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,h=i.get(t),d=r.length>1;if(d)for(let t=0;to+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(ql)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new jl;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class $l{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(null===this.texture){const i=new bi;e.properties.get(i).__webglTexture=t.texture,t.depthNear==n.depthNear&&t.depthFar==n.depthFar||(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}render(e,t){if(null!==this.texture){if(null===this.mesh){const e=t.cameras[0].viewport,n=new $s({extensions:{fragDepth:!0},vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepthEXT = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepthEXT = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new ks(new ma(20,20),n)}e.render(this.mesh,t)}}reset(){this.texture=null,this.mesh=null}}class Zl extends Bn{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,u=null,h=null,d=null,p=null;const m=new $l,f=t.getContextAttributes();let g=null,_=null;const v=[],x=[],y=new Jn;let b=null;const S=new ea;S.layers.enable(1),S.viewport=new Si;const T=new ea;T.layers.enable(2),T.viewport=new Si;const M=[S,T],E=new Xl;E.layers.enable(1),E.layers.enable(2);let A=null,w=null;function R(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=v[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function C(){i.removeEventListener("select",R),i.removeEventListener("selectstart",R),i.removeEventListener("selectend",R),i.removeEventListener("squeeze",R),i.removeEventListener("squeezestart",R),i.removeEventListener("squeezeend",R),i.removeEventListener("end",C),i.removeEventListener("inputsourceschange",N);for(let e=0;e=0&&(x[i]=null,v[i].disconnect(n))}for(let t=0;t=x.length){x.push(n),i=e;break}if(null===x[e]){x[e]=n,i=e;break}}if(-1===i)break}const r=v[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=v[e];return void 0===t&&(t=new Yl,v[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=v[e];return void 0===t&&(t=new Yl,v[e]=t),t.getGripSpace()},this.getHand=function(e){let t=v[e];return void 0===t&&(t=new Yl,v[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){if(g=e.getRenderTarget(),i.addEventListener("select",R),i.addEventListener("selectstart",R),i.addEventListener("selectend",R),i.addEventListener("squeeze",R),i.addEventListener("squeezestart",R),i.addEventListener("squeezeend",R),i.addEventListener("end",C),i.addEventListener("inputsourceschange",N),!0!==f.xrCompatible&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(y),void 0===i.renderState.layers||!1===e.capabilities.isWebGL2){const n={antialias:void 0!==i.renderState.layers||f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),_=new Mi(d.framebufferWidth,d.framebufferHeight,{format:Be,type:Ae,colorSpace:e.outputColorSpace,stencilBuffer:f.stencil})}else{let n=null,s=null,a=null;f.depth&&(a=f.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=f.stencil?ke:Ge,s=f.stencil?De:Pe);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};u=new XRWebGLBinding(i,t),h=u.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),_=new Mi(h.textureWidth,h.textureHeight,{format:Be,type:Ae,depthTexture:new Qa(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:f.stencil,colorSpace:e.outputColorSpace,samples:f.antialias?4:0});e.properties.get(_).__ignoreDepthValues=h.ignoreDepthValues}_.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),O.setContext(i),O.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode};const P=new Ni,L=new Ni;function I(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;null!==m.texture&&(e.near=m.depthNear,e.far=m.depthFar),E.near=T.near=S.near=e.near,E.far=T.far=S.far=e.far,A===E.near&&w===E.far||(i.updateRenderState({depthNear:E.near,depthFar:E.far}),A=E.near,w=E.far,S.near=A,S.far=w,T.near=A,T.far=w,S.updateProjectionMatrix(),T.updateProjectionMatrix(),e.updateProjectionMatrix());const t=e.parent,n=E.cameras;I(E,t);for(let e=0;e0&&(i.alphaTest.value=r.alphaTest);const s=t.get(r),a=s.envMap,o=s.envMapRotation;if(a&&(i.envMap.value=a,Kl.copy(o),Kl.x*=-1,Kl.y*=-1,Kl.z*=-1,a.isCubeTexture&&!1===a.isRenderTargetTexture&&(Kl.y*=-1,Kl.z*=-1),i.envMapRotation.value.setFromMatrix4(Jl.makeRotationFromEuler(Kl)),i.flipEnvMap.value=a.isCubeTexture&&!1===a.isRenderTargetTexture?-1:1,i.reflectivity.value=r.reflectivity,i.ior.value=r.ior,i.refractionRatio.value=r.refractionRatio),r.lightMap){i.lightMap.value=r.lightMap;const t=!0===e._useLegacyLights?Math.PI:1;i.lightMapIntensity.value=r.lightMapIntensity*t,n(r.lightMap,i.lightMapTransform)}r.aoMap&&(i.aoMap.value=r.aoMap,i.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,i.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,qs(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(e,r):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r)):r.isMeshStandardMaterial?(i(e,r),function(e,i){e.metalness.value=i.metalness,i.metalnessMap&&(e.metalnessMap.value=i.metalnessMap,n(i.metalnessMap,e.metalnessMapTransform));e.roughness.value=i.roughness,i.roughnessMap&&(e.roughnessMap.value=i.roughnessMap,n(i.roughnessMap,e.roughnessMapTransform));const r=t.get(i).envMap;r&&(e.envMapIntensity.value=i.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===d&&e.clearcoatNormalScale.value.negate()));t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function ec(e,t,n,i){let r={},s={},a=[];const o=n.isWebGL2?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!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 u(t){const n=t.target;n.removeEventListener("dispose",u);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,h){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let e=0,r=t.length;e0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=K;i.toneMapped&&(null!==E&&!0!==E.isXRRenderTarget||(m=b.toneMapping));const f=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==f?f.length:0,_=te.get(i),x=v.state.lights;if(!0===k&&(!0===H||e!==w)){const t=e===w&&i.id===A;de.setState(i,e,t)}let y=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==x.state.version||_.outputColorSpace!==o||r.isBatchedMesh&&!1===_.batching?y=!0:r.isBatchedMesh||!0!==_.batching?r.isInstancedMesh&&!1===_.instancing?y=!0:r.isInstancedMesh||!0!==_.instancing?r.isSkinnedMesh&&!1===_.skinning?y=!0:r.isSkinnedMesh||!0!==_.skinning?r.isInstancedMesh&&!0===_.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===_.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===_.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===_.instancingMorph&&null!==r.morphTexture||_.envMap!==l||!0===i.fog&&_.fog!==s?y=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===de.numPlanes&&_.numIntersection===de.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==u||_.morphTargets!==h||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==m||!0===J.isWebGL2&&_.morphTargetsCount!==g)&&(y=!0):y=!0:y=!0:y=!0:y=!0:(y=!0,_.__version=i.version);let S=_.currentProgram;!0===y&&(S=Ke(i,t,r));let T=!1,M=!1,R=!1;const C=S.getUniforms(),N=_.uniforms;Q.useProgram(S.program)&&(T=!0,M=!0,R=!0);i.id!==A&&(A=i.id,M=!0);if(T||w!==e){C.setValue(be,"projectionMatrix",e.projectionMatrix),C.setValue(be,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(be,q.setFromMatrixPosition(e.matrixWorld)),J.logarithmicDepthBuffer&&C.setValue(be,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(be,"isOrthographic",!0===e.isOrthographicCamera),w!==e&&(w=e,M=!0,R=!0)}if(r.isSkinnedMesh){C.setOptional(be,r,"bindMatrix"),C.setOptional(be,r,"bindMatrixInverse");const e=r.skeleton;e&&(J.floatVertexTextures?(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(be,"boneTexture",e.boneTexture,ne)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}r.isBatchedMesh&&(C.setOptional(be,r,"batchingTexture"),C.setValue(be,"batchingTexture",r._matricesTexture,ne));const P=n.morphAttributes;(void 0!==P.position||void 0!==P.normal||void 0!==P.color&&!0===J.isWebGL2)&&fe.update(r,n,S);(M||_.receiveShadow!==r.receiveShadow)&&(_.receiveShadow=r.receiveShadow,C.setValue(be,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(N.envMap.value=l,N.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);M&&(C.setValue(be,"toneMappingExposure",b.toneMappingExposure),_.needsLights&&function(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}(N,R),s&&!0===i.fog&&ce.refreshFogUniforms(N,s),ce.refreshMaterialUniforms(N,i,O,U,W),sl.upload(be,Je(_),N,ne));i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(sl.upload(be,Je(_),N,ne),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(be,"center",r.center);if(C.setValue(be,"modelViewMatrix",r.modelViewMatrix),C.setValue(be,"normalMatrix",r.normalMatrix),C.setValue(be,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t{function n(){i.forEach((function(e){te.get(e).currentProgram.isReady()&&i.delete(e)})),0!==i.size?setTimeout(n,10):t(e)}null!==Z.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let ze=null;function Ge(){He.stop()}function ke(){He.start()}const He=new da;function Xe(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)v.pushLight(e),e.castShadow&&v.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||G.intersectsSprite(e)){i&&q.setFromMatrixPosition(e.matrixWorld).applyMatrix4(X);const t=oe.update(e),r=e.material;r.visible&&_.push(e,t,r,n,q.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||G.intersectsObject(e))){const t=oe.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),q.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),q.copy(t.boundingSphere.center)),q.applyMatrix4(e.matrixWorld).applyMatrix4(X)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s0&&function(e,t,n,i){const r=!0===n.isScene?n.overrideMaterial:null;if(null!==r)return;const s=J.isWebGL2;null===W&&(W=new Mi(1,1,{generateMipmaps:!0,type:Z.has("EXT_color_buffer_half_float")?Ie:Ae,minFilter:Me,samples:s?4:0}));b.getDrawingBufferSize(j),s?W.setSize(j.x,j.y):W.setSize(Yn(j.x),Yn(j.y));const a=b.getRenderTarget();b.setRenderTarget(W),b.getClearColor(P),L=b.getClearAlpha(),L<1&&b.setClearColor(16777215,.5);b.clear();const o=b.toneMapping;b.toneMapping=K,$e(e,n,i),ne.updateMultisampleRenderTarget(W),ne.updateRenderTargetMipmap(W);let l=!1;for(let e=0,r=t.length;e0&&$e(r,t,n),s.length>0&&$e(s,t,n),a.length>0&&$e(a,t,n),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function $e(e,t,n){const i=!0===t.isScene?t.overrideMaterial:null;for(let r=0,s=e.length;r0?y[y.length-1]:null,x.pop(),_=x.length>0?x[x.length-1]:null},this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return M},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(e,t,n){te.get(e.texture).__webglTexture=t,te.get(e.depthTexture).__webglTexture=n;const i=te.get(e);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===Z.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(e,t){const n=te.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t},this.setRenderTarget=function(e,t=0,n=0){E=e,T=t,M=n;let i=!0,r=null,s=!1,a=!1;if(e){const o=te.get(e);void 0!==o.__useDefaultFramebuffer?(Q.bindFramebuffer(be.FRAMEBUFFER,null),i=!1):void 0===o.__webglFramebuffer?ne.setupRenderTarget(e):o.__hasExternalTextures&&ne.rebindTextures(e,te.get(e.texture).__webglTexture,te.get(e.depthTexture).__webglTexture);const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=te.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],s=!0):r=J.isWebGL2&&e.samples>0&&!1===ne.useMultisampledRTT(e)?te.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,R.copy(e.viewport),C.copy(e.scissor),N=e.scissorTest}else R.copy(B).multiplyScalar(O).floor(),C.copy(V).multiplyScalar(O).floor(),N=z;if(Q.bindFramebuffer(be.FRAMEBUFFER,r)&&J.drawBuffers&&i&&Q.drawBuffers(e,r),Q.viewport(R),Q.scissor(C),Q.setScissorTest(N),s){const i=te.get(e.texture);be.framebufferTexture2D(be.FRAMEBUFFER,be.COLOR_ATTACHMENT0,be.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(a){const i=te.get(e.texture),r=t||0;be.framebufferTextureLayer(be.FRAMEBUFFER,be.COLOR_ATTACHMENT0,i.__webglTexture,n||0,r)}A=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=te.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Q.bindFramebuffer(be.FRAMEBUFFER,o);try{const a=e.texture,o=a.format,l=a.type;if(o!==Be&&ve.convert(o)!==be.getParameter(be.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const c=l===Ie&&(Z.has("EXT_color_buffer_half_float")||J.isWebGL2&&Z.has("EXT_color_buffer_float"));if(!(l===Ae||ve.convert(l)===be.getParameter(be.IMPLEMENTATION_COLOR_READ_TYPE)||l===Le&&(J.isWebGL2||Z.has("OES_texture_float")||Z.has("WEBGL_color_buffer_float"))||c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&be.readPixels(t,n,i,r,ve.convert(o),ve.convert(l),s)}finally{const e=null!==E?te.get(E).__webglFramebuffer:null;Q.bindFramebuffer(be.FRAMEBUFFER,e)}}},this.copyFramebufferToTexture=function(e,t,n=0){const i=Math.pow(2,-n),r=Math.floor(t.image.width*i),s=Math.floor(t.image.height*i);ne.setTexture2D(t,0),be.copyTexSubImage2D(be.TEXTURE_2D,n,0,0,e.x,e.y,r,s),Q.unbindTexture()},this.copyTextureToTexture=function(e,t,n,i=0){const r=t.image.width,s=t.image.height,a=ve.convert(n.format),o=ve.convert(n.type);ne.setTexture2D(n,0),be.pixelStorei(be.UNPACK_FLIP_Y_WEBGL,n.flipY),be.pixelStorei(be.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),be.pixelStorei(be.UNPACK_ALIGNMENT,n.unpackAlignment),t.isDataTexture?be.texSubImage2D(be.TEXTURE_2D,i,e.x,e.y,r,s,a,o,t.image.data):t.isCompressedTexture?be.compressedTexSubImage2D(be.TEXTURE_2D,i,e.x,e.y,t.mipmaps[0].width,t.mipmaps[0].height,a,t.mipmaps[0].data):be.texSubImage2D(be.TEXTURE_2D,i,e.x,e.y,a,o,t.image),0===i&&n.generateMipmaps&&be.generateMipmap(be.TEXTURE_2D),Q.unbindTexture()},this.copyTextureToTexture3D=function(e,t,n,i,r=0){if(b.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const s=Math.round(e.max.x-e.min.x),a=Math.round(e.max.y-e.min.y),o=e.max.z-e.min.z+1,l=ve.convert(i.format),c=ve.convert(i.type);let u;if(i.isData3DTexture)ne.setTexture3D(i,0),u=be.TEXTURE_3D;else{if(!i.isDataArrayTexture&&!i.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");ne.setTexture2DArray(i,0),u=be.TEXTURE_2D_ARRAY}be.pixelStorei(be.UNPACK_FLIP_Y_WEBGL,i.flipY),be.pixelStorei(be.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),be.pixelStorei(be.UNPACK_ALIGNMENT,i.unpackAlignment);const h=be.getParameter(be.UNPACK_ROW_LENGTH),d=be.getParameter(be.UNPACK_IMAGE_HEIGHT),p=be.getParameter(be.UNPACK_SKIP_PIXELS),m=be.getParameter(be.UNPACK_SKIP_ROWS),f=be.getParameter(be.UNPACK_SKIP_IMAGES),g=n.isCompressedTexture?n.mipmaps[r]:n.image;be.pixelStorei(be.UNPACK_ROW_LENGTH,g.width),be.pixelStorei(be.UNPACK_IMAGE_HEIGHT,g.height),be.pixelStorei(be.UNPACK_SKIP_PIXELS,e.min.x),be.pixelStorei(be.UNPACK_SKIP_ROWS,e.min.y),be.pixelStorei(be.UNPACK_SKIP_IMAGES,e.min.z),n.isDataTexture||n.isData3DTexture?be.texSubImage3D(u,r,t.x,t.y,t.z,s,a,o,l,c,g.data):i.isCompressedArrayTexture?be.compressedTexSubImage3D(u,r,t.x,t.y,t.z,s,a,o,l,g.data):be.texSubImage3D(u,r,t.x,t.y,t.z,s,a,o,l,c,g),be.pixelStorei(be.UNPACK_ROW_LENGTH,h),be.pixelStorei(be.UNPACK_IMAGE_HEIGHT,d),be.pixelStorei(be.UNPACK_SKIP_PIXELS,p),be.pixelStorei(be.UNPACK_SKIP_ROWS,m),be.pixelStorei(be.UNPACK_SKIP_IMAGES,f),0===r&&i.generateMipmaps&&be.generateMipmap(u),Q.unbindTexture()},this.initTexture=function(e){e.isCubeTexture?ne.setTextureCube(e,0):e.isData3DTexture?ne.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?ne.setTexture2DArray(e,0):ne.setTexture2D(e,0),Q.unbindTexture()},this.resetState=function(){T=0,M=0,E=null,Q.reset(),xe.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Dn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===qt?"display-p3":"srgb",t.unpackColorSpace=di.workingColorSpace===Yt?"display-p3":"srgb"}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class nc extends tc{}nc.prototype.isWebGL1Renderer=!0;class ic{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new $r(e),this.density=t}clone(){return new ic(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class rc{constructor(e,t=1,n=1e3){this.isFog=!0,this.name="",this.color=new $r(e),this.near=t,this.far=n}clone(){return new rc(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class sc extends Ir{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 gr,this.environmentRotation=new gr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class ac{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Mn,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Hn()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return oi("THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:o,point:hc.clone(),uv:Wr.getInterpolation(hc,_c,vc,xc,yc,bc,Sc,new Jn),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function Mc(e,t,n,i,r,s){mc.subVectors(e,n).addScalar(.5).multiply(i),void 0!==r?(fc.x=s*mc.x-r*mc.y,fc.y=r*mc.x+s*mc.y):fc.copy(mc),e.copy(t),e.x+=fc.x,e.y+=fc.y,e.applyMatrix4(gc)}const Ec=new Ni,Ac=new Ni;class wc extends Ir{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,n=t.length;e0){let n,i;for(n=1,i=t.length;n0){Ec.setFromMatrixPosition(this.matrixWorld);const n=e.ray.origin.distanceTo(Ec);this.getObjectForDistance(n).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){Ec.setFromMatrixPosition(e.matrixWorld),Ac.setFromMatrixPosition(this.matrixWorld);const n=Ec.distanceTo(Ac)/e.zoom;let i,r;for(t[0].object.visible=!0,i=1,r=t.length;i=e))break;t[i-1].object.visible=!1,t[i].object.visible=!0}for(this._currentLevel=i-1;i=n.length&&n.push({start:-1,count:-1,z:-1});const r=n[this.index];i.push(r),this.index++,r.start=e.start,r.count=e.count,r.z=t}reset(){this.list.length=0,this.index=0}}const tu="batchId",nu=new ar,iu=new ar,ru=new ar,su=new ar,au=new ha,ou=new Ii,lu=new Ki,cu=new Ni,uu=new eu,hu=new ks,du=[];function pu(e,t,n=0){const i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let s=0;s65536?new Uint32Array(r):new Uint16Array(r);t.setIndex(new os(e,1))}const s=i>65536?new Uint32Array(n):new Uint16Array(n);t.setAttribute(tu,new os(s,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(tu))throw new Error(`BatchedMesh: Geometry cannot use attribute "${tu}"`);const t=this.geometry;if(Boolean(e.getIndex())!==Boolean(t.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const n in t.attributes){if(n===tu)continue;if(!e.hasAttribute(n))throw new Error(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=e.getAttribute(n),r=t.getAttribute(n);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ii);const e=this._geometryCount,t=this.boundingBox,n=this._active;t.makeEmpty();for(let i=0;i=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const s=this._reservedRanges,a=this._drawRanges,o=this._bounds;0!==this._geometryCount&&(r=s[s.length-1]),i.vertexCount=-1===t?e.getAttribute("position").count:t,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const l=e.getIndex(),c=null!==l;if(c&&(i.indexCount=-1===n?l.count:n,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const u=this._visibility,h=this._active,d=this._matricesTexture,p=this._matricesTexture.image.data;u.push(!0),h.push(!0);const m=this._geometryCount;this._geometryCount++,ru.toArray(p,16*m),d.needsUpdate=!0,s.push(i),a.push({start:c?i.indexStart:i.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Ii,sphereInitialized:!1,sphere:new Ki});const f=this.geometry.getAttribute(tu);for(let e=0;e=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const n=this.geometry,i=null!==n.getIndex(),r=n.getIndex(),s=t.getIndex(),a=this._reservedRanges[e];if(i&&s.count>a.indexCount||t.attributes.position.count>a.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.vertexCount;for(const e in n.attributes){if(e===tu)continue;const i=t.getAttribute(e),r=n.getAttribute(e);pu(i,r,o);const s=i.itemSize;for(let e=i.count,t=l;e=t.length||!1===t[e]||(t[e]=!1,this._visibilityChanged=!0),this}getBoundingBoxAt(e,t){if(!1===this._active[e])return null;const n=this._bounds[e],i=n.box,r=this.geometry;if(!1===n.boxInitialized){i.makeEmpty();const t=r.index,s=r.attributes.position,a=this._drawRanges[e];for(let e=a.start,n=a.start+a.count;e=this._geometryCount||!1===n[e]||(t.toArray(r,16*e),i.needsUpdate=!0),this}getMatrixAt(e,t){const n=this._active,i=this._matricesTexture.image.data;return e>=this._geometryCount||!1===n[e]?null:t.fromArray(i,16*e)}setVisibleAt(e,t){const n=this._visibility,i=this._active;return e>=this._geometryCount||!1===i[e]||n[e]===t||(n[e]=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._visibility,n=this._active;return!(e>=this._geometryCount||!1===n[e])&&t[e]}raycast(e,t){const n=this._visibility,i=this._active,r=this._drawRanges,s=this._geometryCount,a=this.matrixWorld,o=this.geometry;hu.material=this.material,hu.geometry.index=o.index,hu.geometry.attributes=o.attributes,null===hu.geometry.boundingBox&&(hu.geometry.boundingBox=new Ii),null===hu.geometry.boundingSphere&&(hu.geometry.boundingSphere=new Ki);for(let o=0;o({...e}))),this._reservedRanges=e._reservedRanges.map((e=>({...e}))),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,t,n,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=i.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._active,l=this._visibility,c=this._multiDrawStarts,u=this._multiDrawCounts,h=this._drawRanges,d=this.perObjectFrustumCulled;d&&(su.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),au.setFromProjectionMatrix(su,e.coordinateSystem));let p=0;if(this.sortObjects){iu.copy(this.matrixWorld).invert(),cu.setFromMatrixPosition(n.matrixWorld).applyMatrix4(iu);for(let e=0,t=l.length;eo)continue;h.applyMatrix4(this.matrixWorld);const s=e.ray.origin.distanceTo(h);se.far||t.push({distance:s,point:u.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}else{for(let n=Math.max(0,s.start),i=Math.min(m.count,s.start+s.count)-1;no)continue;h.applyMatrix4(this.matrixWorld);const i=e.ray.origin.distanceTo(h);ie.far||t.push({distance:i,point:u.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;er.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:t,face:null,object:a})}}class Iu extends bi{constructor(e,t,n,i,r,s,a,o,l){super(e,t,n,i,r,s,a,o,l),this.isVideoTexture=!0,this.minFilter=void 0!==s?s:be,this.magFilter=void 0!==r?r:be,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){c.needsUpdate=!0,e.requestVideoFrameCallback(t)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Uu extends bi{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=ge,this.minFilter=ge,this.generateMipmaps=!1,this.needsUpdate=!0}}class Ou extends bi{constructor(e,t,n,i,r,s,a,o,l,c,u,h){super(null,s,a,o,l,c,i,r,u,h),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Du extends Ou{constructor(e,t,n,i,r,s){super(e,t,n,r,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=me}}class Fu extends Ou{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,le),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class Bu extends bi{constructor(e,t,n,i,r,s,a,o,l){super(e,t,n,i,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Vu{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new Jn:new Ni);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t){const n=new Ni,i=[],r=[],s=[],a=new Ni,o=new ar;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new Ni)}r[0]=new Ni,s[0]=new Ni;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),u=Math.abs(i[0].y),h=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),u<=l&&(l=u,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(Wn(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Wn(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class zu extends Vu{constructor(e=0,t=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new Jn){const n=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Hu.subVectors(i[0],i[1]).add(i[0]),a=Hu);const u=i[l%r],h=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],u=i[s>i.length-3?i.length-1:s+2];return n.set(Yu(a,o.x,l.x,c.x,u.x),Yu(a,o.y,l.y,c.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){const e=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-e/a;return s.getPointAt(o,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.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 e=[];let t=0;for(let n=0,i=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){const e=l.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class oh extends Ms{constructor(e=[new Jn(0,-.5),new Jn(.5,0),new Jn(0,.5)],t=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:n,phiLength:i},t=Math.floor(t),i=Wn(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/t,u=new Ni,h=new Jn,d=new Ni,p=new Ni,m=new Ni;let f=0,g=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:f=e[t+1].x-e[t].x,g=e[t+1].y-e[t].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case e.length-1:o.push(m.x,m.y,m.z);break;default:f=e[t+1].x-e[t].x,g=e[t+1].y-e[t].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=t;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=e.length-1;n++){u.x=e[n].x*p,u.y=e[n].y,u.z=e[n].x*m,s.push(u.x,u.y,u.z),h.x=r/t,h.y=n/(e.length-1),a.push(h.x,h.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n0&&_(!0),t>0&&_(!1)),this.setIndex(c),this.setAttribute("position",new gs(u,3)),this.setAttribute("normal",new gs(h,3)),this.setAttribute("uv",new gs(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new uh(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class hh extends uh{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new hh(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class dh extends Ms{constructor(e=[],t=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:i};const r=[],s=[];function a(e,t,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=e.clone().lerp(n,i/r),o=t.clone().lerp(n,i/r),l=r-i;for(let e=0;e<=l;e++)s[i][e]=0===e&&i===r?a:a.clone().lerp(o,e/l)}for(let e=0;e.9&&a<.1&&(t<.2&&(s[e+0]+=1),n<.2&&(s[e+2]+=1),i<.2&&(s[e+4]+=1))}}()}(),this.setAttribute("position",new gs(r,3)),this.setAttribute("normal",new gs(r.slice(),3)),this.setAttribute("uv",new gs(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new dh(e.vertices,e.indices,e.radius,e.details)}}class ph extends dh{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,i=1/n;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,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[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],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new ph(e.radius,e.detail)}}const mh=new Ni,fh=new Ni,gh=new Ni,_h=new Wr;class vh extends Ms{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const n=4,i=Math.pow(10,n),r=Math.cos(Gn*t),s=e.getIndex(),a=e.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],u=new Array(3),h={},d=[];for(let e=0;e80*n){o=c=e[0],l=u=e[1];for(let t=n;tc&&(c=h),d>u&&(u=d);p=Math.max(c-o,u-l),p=0!==p?32767/p:0}return Th(s,a,n,o,l,p,0),a};function bh(e,t,n,i,r){let s,a;if(r===function(e,t,n,i){let r=0;for(let s=t,a=n-i;s0)for(s=t;s=t;s-=i)a=kh(s,e[s],e[s+1],a);return a&&Dh(a,a.next)&&(Hh(a),a=a.next),a}function Sh(e,t){if(!e)return e;t||(t=e);let n,i=e;do{if(n=!1,i.steiner||!Dh(i,i.next)&&0!==Oh(i.prev,i,i.next))i=i.next;else{if(Hh(i),i=t=i.prev,i===i.next)break;n=!0}}while(n||i!==t);return t}function Th(e,t,n,i,r,s,a){if(!e)return;!a&&s&&function(e,t,n,i){let r=e;do{0===r.z&&(r.z=Ph(r.x,r.y,t,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,n,i,r,s,a,o,l,c=1;do{for(n=e,e=null,s=null,a=0;n;){for(a++,i=n,o=0,t=0;t0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:e=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(e,i,r,s);let o,l,c=e;for(;e.prev!==e.next;)if(o=e.prev,l=e.next,s?Eh(e,i,r,s):Mh(e))t.push(o.i/n|0),t.push(e.i/n|0),t.push(l.i/n|0),Hh(e),e=l.next,c=l.next;else if((e=l)===c){a?1===a?Th(e=Ah(Sh(e),t,n),t,n,i,r,s,2):2===a&&wh(e,t,n,i,r,s):Th(Sh(e),t,n,i,r,s,1);break}}function Mh(e){const t=e.prev,n=e,i=e.next;if(Oh(t,n,i)>=0)return!1;const r=t.x,s=n.x,a=i.x,o=t.y,l=n.y,c=i.y,u=rs?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==t;){if(m.x>=u&&m.x<=d&&m.y>=h&&m.y<=p&&Ih(r,o,s,l,a,c,m.x,m.y)&&Oh(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Eh(e,t,n,i){const r=e.prev,s=e,a=e.next;if(Oh(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,u=r.y,h=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,g=u>h?u>d?u:d:h>d?h:d,_=Ph(p,m,t,n,i),v=Ph(f,g,t,n,i);let x=e.prevZ,y=e.nextZ;for(;x&&x.z>=_&&y&&y.z<=v;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ih(o,u,l,h,c,d,x.x,x.y)&&Oh(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ih(o,u,l,h,c,d,y.x,y.y)&&Oh(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;x&&x.z>=_;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ih(o,u,l,h,c,d,x.x,x.y)&&Oh(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;y&&y.z<=v;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ih(o,u,l,h,c,d,y.x,y.y)&&Oh(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Ah(e,t,n){let i=e;do{const r=i.prev,s=i.next.next;!Dh(r,s)&&Fh(r,i,i.next,s)&&zh(r,s)&&zh(s,r)&&(t.push(r.i/n|0),t.push(i.i/n|0),t.push(s.i/n|0),Hh(i),Hh(i.next),i=e=s),i=i.next}while(i!==e);return Sh(i)}function wh(e,t,n,i,r,s){let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&Uh(a,e)){let o=Gh(a,e);return a=Sh(a,a.next),o=Sh(o,o.next),Th(a,t,n,i,r,s,0),void Th(o,t,n,i,r,s,0)}e=e.next}a=a.next}while(a!==e)}function Rh(e,t){return e.x-t.x}function Ch(e,t){const n=function(e,t){let n,i=t,r=-1/0;const s=e.x,a=e.y;do{if(a<=i.y&&a>=i.next.y&&i.next.y!==i.y){const e=i.x+(a-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>r&&(r=e,n=i.x=i.x&&i.x>=l&&s!==i.x&&Ih(an.x||i.x===n.x&&Nh(n,i)))&&(n=i,h=u)),i=i.next}while(i!==o);return n}(e,t);if(!n)return t;const i=Gh(n,e);return Sh(i,i.next),Sh(n,n.next)}function Nh(e,t){return Oh(e.prev,e,t.prev)<0&&Oh(t.next,e,e.next)<0}function Ph(e,t,n,i,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Lh(e){let t=e,n=e;do{(t.x=(e-a)*(s-o)&&(e-a)*(i-o)>=(n-a)*(t-o)&&(n-a)*(s-o)>=(r-a)*(i-o)}function Uh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&Fh(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}(e,t)&&(zh(e,t)&&zh(t,e)&&function(e,t){let n=e,i=!1;const r=(e.x+t.x)/2,s=(e.y+t.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==e);return i}(e,t)&&(Oh(e.prev,e,t.prev)||Oh(e,t.prev,t))||Dh(e,t)&&Oh(e.prev,e,e.next)>0&&Oh(t.prev,t,t.next)>0)}function Oh(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function Dh(e,t){return e.x===t.x&&e.y===t.y}function Fh(e,t,n,i){const r=Vh(Oh(e,t,n)),s=Vh(Oh(e,t,i)),a=Vh(Oh(n,i,e)),o=Vh(Oh(n,i,t));return r!==s&&a!==o||(!(0!==r||!Bh(e,n,t))||(!(0!==s||!Bh(e,i,t))||(!(0!==a||!Bh(n,e,i))||!(0!==o||!Bh(n,t,i)))))}function Bh(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Vh(e){return e>0?1:e<0?-1:0}function zh(e,t){return Oh(e.prev,e,e.next)<0?Oh(e,t,e.next)>=0&&Oh(e,e.prev,t)>=0:Oh(e,t,e.prev)<0||Oh(e,e.next,t)<0}function Gh(e,t){const n=new Wh(e.i,e.x,e.y),i=new Wh(t.i,t.x,t.y),r=e.next,s=t.prev;return e.next=t,t.prev=e,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function kh(e,t,n,i){const r=new Wh(e,t,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Hh(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function Wh(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class Xh{static area(e){const t=e.length;let n=0;for(let i=t-1,r=0;r2&&e[t-1].equals(e[0])&&e.pop()}function qh(e,t){for(let n=0;nNumber.EPSILON){const h=Math.sqrt(u),d=Math.sqrt(l*l+c*c),p=t.x-o/h,m=t.y+a/h,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-e.x,r=m+o*f-e.y;const g=i*i+r*r;if(g<=2)return new Jn(i,r);s=Math.sqrt(g/2)}else{let e=!1;a>Number.EPSILON?l>Number.EPSILON&&(e=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(e=!0):Math.sign(o)===Math.sign(c)&&(e=!0),e?(i=-o,r=a,s=Math.sqrt(u)):(i=a,r=o,s=Math.sqrt(u/2))}return new Jn(i/s,r/s)}const P=[];for(let e=0,t=A.length,n=t-1,i=e+1;e=0;e--){const t=e/p,n=u*Math.cos(t*Math.PI/2),i=h*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=n;let r=n-1;r<0&&(r=e.length-1);for(let e=0,n=o+2*p;e0)&&d.push(t,r,l),(e!==n-1||o0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class dd extends Jr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new $r(16777215),this.specular=new $r(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gr,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class pd extends Jr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new $r(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class md extends Jr{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class fd extends Jr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new $r(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gr,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class gd extends Jr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new $r(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class _d extends fu{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function vd(e,t,n){return!e||!n&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function xd(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function yd(e){const t=e.length,n=new Array(t);for(let e=0;e!==t;++e)n[e]=e;return n.sort((function(t,n){return e[t]-e[n]})),n}function bd(e,t,n){const i=e.length,r=new e.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*t;for(let n=0;n!==t;++n)r[a++]=e[i+n]}return r}function Sd(e,t,n,i){let r=1,s=e[0];for(;void 0!==s&&void 0===s[i];)s=e[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(t.push(s.time),n.push.apply(n,a)),s=e[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(t.push(s.time),a.toArray(n,n.length)),s=e[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(t.push(s.time),n.push(a)),s=e[r++]}while(void 0!==s)}const Td={convertArray:vd,isTypedArray:xd,getKeyframeOrder:yd,sortedArray:bd,flattenJSON:Sd,subclip:function(e,t,n,i,r=30){const s=e.clone();s.name=t;const a=[];for(let e=0;e=i)){l.push(t.times[e]);for(let n=0;ns.tracks[e].times[0]&&(o=s.tracks[e].times[0]);for(let e=0;e=i.times[h]){const e=h*l+o,t=e+l-o;d=i.values.slice(e,t)}else{const e=i.createInterpolant(),t=o,n=l-o;e.evaluate(s),d=e.resultBuffer.slice(t,n)}if("quaternion"===r){(new Ci).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let e=0;e=r)break e;{const a=t[1];e=r)break t}s=n,n=0}}for(;n>>1;et;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const e=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*e,s*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let t=0;t!==r;t++){const i=n[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,s),e=!1;break}s=i}if(void 0!==i&&xd(i))for(let t=0,n=i.length;t!==n;++t){const n=i[t];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,n),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Pt,r=e.length-1;let s=1;for(let a=1;a0){e[s]=e[r];for(let e=r*n,i=s*n,a=0;a!==n;++a)t[i+a]=t[e+a];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*n)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),n=new(0,this.constructor)(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}Rd.prototype.TimeBufferType=Float32Array,Rd.prototype.ValueBufferType=Float32Array,Rd.prototype.DefaultInterpolation=Nt;class Cd extends Rd{}Cd.prototype.ValueTypeName="bool",Cd.prototype.ValueBufferType=Array,Cd.prototype.DefaultInterpolation=Ct,Cd.prototype.InterpolantFactoryMethodLinear=void 0,Cd.prototype.InterpolantFactoryMethodSmooth=void 0;class Nd extends Rd{}Nd.prototype.ValueTypeName="color";class Pd extends Rd{}Pd.prototype.ValueTypeName="number";class Ld extends Md{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-t)/(i-t);let l=e*a;for(let e=l+a;l!==e;l+=4)Ci.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Id extends Rd{InterpolantFactoryMethodLinear(e){return new Ld(this.times,this.values,this.getValueSize(),e)}}Id.prototype.ValueTypeName="quaternion",Id.prototype.DefaultInterpolation=Nt,Id.prototype.InterpolantFactoryMethodSmooth=void 0;class Ud extends Rd{}Ud.prototype.ValueTypeName="string",Ud.prototype.ValueBufferType=Array,Ud.prototype.DefaultInterpolation=Ct,Ud.prototype.InterpolantFactoryMethodLinear=void 0,Ud.prototype.InterpolantFactoryMethodSmooth=void 0;class Od extends Rd{}Od.prototype.ValueTypeName="vector";class Dd{constructor(e,t=-1,n,i=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Hn(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,i=1/(e.fps||1);for(let e=0,r=n.length;e!==r;++e)t.push(Fd(n[e]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=n.length;e!==i;++e)t.push(Rd.toJSON(n[e]));return i}static CreateFromMorphTargetSequence(e,t,n,i){const r=t.length,s=[];for(let e=0;e1){const e=s[1];let t=i[e];t||(i[e]=t=[]),t.push(n)}}const s=[];for(const e in i)s.push(this.CreateFromMorphTargetSequence(e,i[e],t,n));return s}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(e,t,n,i,r){if(0!==n.length){const s=[],a=[];Sd(n,s,a,i),0!==s.length&&r.push(new e(t,s,a))}},i=[],r=e.name||"default",s=e.fps||30,a=e.blendMode;let o=e.length||-1;const l=e.hierarchy||[];for(let e=0;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==kd[e])return void kd[e].push({onLoad:t,onProgress:n,onError:i});kd[e]=[],kd[e].push({onLoad:t,onProgress:n,onError:i});const s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const n=kd[e],i=t.body.getReader(),r=t.headers.get("Content-Length")||t.headers.get("X-File-Size"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(e){!function t(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let e=0,t=n.length;e{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,a)));case"json":return e.json();default:if(void 0===a)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(a),n=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(n);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Bd.add(e,t);const n=kd[e];delete kd[e];for(let e=0,i=n.length;e{const n=kd[e];if(void 0===n)throw this.manager.itemError(e),t;delete kd[e];for(let e=0,i=n.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Xd extends Gd{constructor(e){super(e)}load(e,t,n,i){const r=this,s=new Wd(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,(function(n){try{t(r.parse(JSON.parse(n)))}catch(t){i?i(t):console.error(t),r.manager.itemError(e)}}),n,i)}parse(e){const t=[];for(let n=0;n0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const r=e.uniforms[t];switch(i.uniforms[t]={},r.type){case"t":i.uniforms[t].value=n(r.value);break;case"c":i.uniforms[t].value=(new $r).setHex(r.value);break;case"v2":i.uniforms[t].value=(new Jn).fromArray(r.value);break;case"v3":i.uniforms[t].value=(new Ni).fromArray(r.value);break;case"v4":i.uniforms[t].value=(new Si).fromArray(r.value);break;case"m3":i.uniforms[t].value=(new Qn).fromArray(r.value);break;case"m4":i.uniforms[t].value=(new ar).fromArray(r.value);break;default:i.uniforms[t].value=r.value}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(i.lights=e.lights),void 0!==e.clipping&&(i.clipping=e.clipping),void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=n(e.map)),void 0!==e.matcap&&(i.matcap=n(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=n(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=n(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=n(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Jn).fromArray(t)}return void 0!==e.displacementMap&&(i.displacementMap=n(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=n(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=n(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=n(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=n(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=n(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=n(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=n(e.envMap)),void 0!==e.envMapRotation&&i.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=n(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=n(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=n(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=n(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=n(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Jn).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=n(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=n(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=n(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=n(e.thicknessMap)),void 0!==e.anisotropyMap&&(i.anisotropyMap=n(e.anisotropyMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=n(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=n(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}static createMaterialFromType(e){return new{ShadowMaterial:ld,SpriteMaterial:cc,RawShaderMaterial:cd,ShaderMaterial:$s,PointsMaterial:Au,MeshPhysicalMaterial:hd,MeshStandardMaterial:ud,MeshPhongMaterial:dd,MeshToonMaterial:pd,MeshNormalMaterial:md,MeshLambertMaterial:fd,MeshDepthMaterial:Vl,MeshDistanceMaterial:zl,MeshBasicMaterial:Qr,MeshMatcapMaterial:gd,LineDashedMaterial:_d,LineBasicMaterial:fu,Material:Jr}[e]}}class _p{static decodeText(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let n=0,i=e.length;n0){const n=new Vd(t);r=new qd(n),r.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t0){i=new qd(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t{const t=new Ii;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const n=new Ki;return n.radius=e.sphereRadius,n.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:n}})),s._maxGeometryCount=e.maxGeometryCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._geometryCount=e.geometryCount,s._matricesTexture=u(e.matricesTexture.uuid);break;case"LOD":s=new wc;break;case"Line":s=new bu(l(e.geometry),c(e.material));break;case"LineLoop":s=new Eu(l(e.geometry),c(e.material));break;case"LineSegments":s=new Mu(l(e.geometry),c(e.material));break;case"PointCloud":case"Points":s=new Pu(l(e.geometry),c(e.material));break;case"Sprite":s=new Tc(c(e.material));break;case"Group":s=new jl;break;case"Bone":s=new Bc;break;default:s=new Ir}if(s.uuid=e.uuid,void 0!==e.name&&(s.name=e.name),void 0!==e.matrix?(s.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(s.matrixAutoUpdate=e.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==e.position&&s.position.fromArray(e.position),void 0!==e.rotation&&s.rotation.fromArray(e.rotation),void 0!==e.quaternion&&s.quaternion.fromArray(e.quaternion),void 0!==e.scale&&s.scale.fromArray(e.scale)),void 0!==e.up&&s.up.fromArray(e.up),void 0!==e.castShadow&&(s.castShadow=e.castShadow),void 0!==e.receiveShadow&&(s.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.bias&&(s.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(s.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(s.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&s.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(s.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(s.visible=e.visible),void 0!==e.frustumCulled&&(s.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(s.renderOrder=e.renderOrder),void 0!==e.userData&&(s.userData=e.userData),void 0!==e.layers&&(s.layers.mask=e.layers),void 0!==e.children){const a=e.children;for(let e=0;e{t&&t(n),r.manager.itemEnd(e)})).catch((e=>{i&&i(e)})):(setTimeout((function(){t&&t(s),r.manager.itemEnd(e)}),0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(e,a).then((function(e){return e.blob()})).then((function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){return Bd.add(e,n),t&&t(n),r.manager.itemEnd(e),n})).catch((function(t){i&&i(t),Bd.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));Bd.add(e,o),r.manager.itemStart(e)}}let Ep;class Ap{static getContext(){return void 0===Ep&&(Ep=new(window.AudioContext||window.webkitAudioContext)),Ep}static setContext(e){Ep=e}}class wp extends Gd{constructor(e){super(e)}load(e,t,n,i){const r=this,s=new Wd(this.manager);function a(t){i?i(t):console.error(t),r.manager.itemError(e)}s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,(function(e){try{const n=e.slice(0);Ap.getContext().decodeAudioData(n,(function(e){t(e)})).catch(a)}catch(e){a(e)}}),n,i)}}const Rp=new ar,Cp=new ar,Np=new ar;class Pp{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new ea,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ea,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(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Np.copy(e.projectionMatrix);const n=t.eyeSep/2,i=n*t.near/t.focus,r=t.near*Math.tan(Gn*t.fov*.5)/t.zoom;let s,a;Cp.elements[12]=-n,Rp.elements[12]=n,s=-r*t.aspect+i,a=r*t.aspect+i,Np.elements[0]=2*t.near/(a-s),Np.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(Np),s=-r*t.aspect-i,a=r*t.aspect-i,Np.elements[0]=2*t.near/(a-s),Np.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(Np)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Cp),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Rp)}}class Lp{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Ip(),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 e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=Ip();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Ip(){return("undefined"==typeof performance?Date:performance).now()}const Up=new Ni,Op=new Ci,Dp=new Ni,Fp=new Ni;class Bp extends Ir{constructor(){super(),this.type="AudioListener",this.context=Ap.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Lp}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(e){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,n=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Up,Op,Dp),Fp.set(0,0,-1).applyQuaternion(Op),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Up.x,e),t.positionY.linearRampToValueAtTime(Up.y,e),t.positionZ.linearRampToValueAtTime(Up.z,e),t.forwardX.linearRampToValueAtTime(Fp.x,e),t.forwardY.linearRampToValueAtTime(Fp.y,e),t.forwardZ.linearRampToValueAtTime(Fp.z,e),t.upX.linearRampToValueAtTime(n.x,e),t.upY.linearRampToValueAtTime(n.y,e),t.upZ.linearRampToValueAtTime(n.z,e)}else t.setPosition(Up.x,Up.y,Up.z),t.setOrientation(Fp.x,Fp.y,Fp.z,n.x,n.y,n.z)}}class Vp extends Ir{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.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(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=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+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,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(){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(),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 e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(n[e]!==n[e+t]){a.setValue(n,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let e=n,r=i;e!==r;++e)t[e]=t[i+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let i=0;i!==r;++i)e[t+i]=e[n+i]}_slerp(e,t,n,i){Ci.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){const s=this._workIndex*r;Ci.multiplyQuaternionsFlat(e,s,e,t,e,n),Ci.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=t+a;e[r]=e[r]*s+e[n+a]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){const r=t+s;e[r]=e[r]+e[n+s]*i}}}const qp="\\[\\]\\.:\\/",Yp=new RegExp("["+qp+"]","g"),$p="[^"+qp+"]",Zp="[^"+qp.replace("\\.","")+"]",Kp=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",$p)+/(WCOD+)?/.source.replace("WCOD",Zp)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",$p)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",$p)+"$"),Jp=["material","materials","bones","map"];class Qp{constructor(e,t,n){this.path=t,this.parsedPath=n||Qp.parseTrackName(t),this.node=Qp.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new Qp.Composite(e,t,n):new Qp(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Yp,"")}static parseTrackName(e){const t=Kp.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=n.nodeName.substring(i+1);-1!==Jp.indexOf(e)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=e)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(void 0!==n)return n}if(e.children){const n=function(e){for(let i=0;i=r){const s=r++,c=e[s];t[c.uuid]=l,e[l]=c,t[o]=s,e[s]=a;for(let e=0,t=i;e!==t;++e){const t=n[e],i=t[s],r=t[l];t[l]=i,t[s]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=e.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=t[o];if(void 0!==l)if(delete t[o],l0&&(t[a.uuid]=l),e[l]=a,e.pop();for(let e=0,t=i;e!==t;++e){const t=n[e];t[l]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const n=this._bindingsIndicesByPath;let i=n[e];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,u=new Array(l);i=r.length,n[e]=i,s.push(e),a.push(t),r.push(u);for(let n=c,i=o.length;n!==i;++n){const i=o[n];u[n]=new Qp(i,e,t)}return u}unsubscribe_(e){const t=this._bindingsIndicesByPath,n=t[e];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];t[e[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}}class tm{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;const r=t.tracks,s=r.length,a=new Array(s),o={endingStart:Lt,endingEnd:Lt};for(let e=0;e!==s;++e){const t=r[e].createInterpolant(null);a[e]=t,t.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),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(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n){if(e.fadeOut(t),this.fadeIn(t),n){const n=this._clip.duration,i=e._clip.duration,r=i/n,s=n/i;e.warp(1,r,t),this.warp(s,1,t)}return this}crossFadeTo(e,t,n){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const i=this._mixer,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=e/s,l[1]=t/s,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*n;i<0||0===n?t=0:(this._startTime=null,t=n*i)}t*=this._updateTimeScale(e);const s=this._updateTime(t),a=this._updateWeight(e);if(a>0){const e=this._interpolants,t=this._propertyBindings;if(this.blendMode===Dt)for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(s),t[n].accumulateAdditive(a);else for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(s),t[n].accumulate(i,a)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){t*=n.evaluate(e)[0],e>n.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let i=this.time+e,r=this._loopCount;const s=2202===n;if(0===e)return-1===r?i:s&&1==(1&r)?t-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=t||i<0){const n=Math.floor(i/t);i-=t*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===a){const t=e<0;this._setEndings(t,!t,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return t-i}return i}_setEndings(e,t,n){const i=this._interpolantSettings;n?(i.endingStart=It,i.endingEnd=It):(i.endingStart=e?this.zeroSlopeAtStart?It:Lt:Ut,i.endingEnd=t?this.zeroSlopeAtEnd?It:Lt:Ut)}_scheduleFading(e,t,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=t,a[1]=r+e,o[1]=n,this}}const nm=new Float32Array(1);class im extends Bn{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const n=e._localRoot||this._root,i=e._clip.tracks,r=i.length,s=e._propertyBindings,a=e._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let e=0;e!==r;++e){const r=i[e],l=r.name;let u=c[l];if(void 0!==u)++u.referenceCount,s[e]=u;else{if(u=s[e],void 0!==u){null===u._cacheIndex&&(++u.referenceCount,this._addInactiveBinding(u,o,l));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;u=new jp(Qp.create(n,l,i),r.ValueTypeName,r.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,o,l),s[e]=u}a[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,n=e._clip.uuid,i=this._actionsByClip[n];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,n,t)}const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,i=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let a=0;a!==n;++a){t[a]._update(i,e,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let e=0;e!==o;++e)a[e].apply(s);return this}setTime(e){this.time=0;for(let e=0;ethis.max.x||e.ythis.max.y)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,fm).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const _m=new Ni,vm=new Ni;class xm{constructor(e=new Ni,t=new Ni){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){_m.subVectors(e,this.start),vm.subVectors(this.end,this.start);const n=vm.dot(vm);let i=vm.dot(_m)/n;return t&&(i=Wn(i,0,1)),i}closestPointToPoint(e,t,n){const i=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const ym=new Ni;class bm extends Ir{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const n=new Ms,i=[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 e=0,t=1,n=32;e1)for(let n=0;n.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{jm.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(jm,t)}}setLength(e,t=.2*e,n=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class Zm extends Mu{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=new Ms;n.setAttribute("position",new gs(t,3)),n.setAttribute("color",new gs([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new fu({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,n){const i=new $r,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class Km{constructor(){this.type="ShapePath",this.color=new $r,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new ah,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,i){return this.currentPath.quadraticCurveTo(e,t,n,i),this}bezierCurveTo(e,t,n,i,r,s){return this.currentPath.bezierCurveTo(e,t,n,i,r,s),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const n=t.length;let i=!1;for(let r=n-1,s=0;sNumber.EPSILON){if(l<0&&(n=t[s],o=-o,a=t[r],l=-l),e.ya.y)continue;if(e.y===n.y){if(e.x===n.x)return!0}else{const t=l*(e.x-n.x)-o*(e.y-n.y);if(0===t)return!0;if(t<0)continue;i=!i}}else{if(e.y!==n.y)continue;if(a.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=a.x)return!0}}return i}const n=Xh.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,s,a;const o=[];if(1===i.length)return s=i[0],a=new xh,a.curves=s.curves,o.push(a),o;let l=!n(i[0].getPoints());l=e?!l:l;const c=[],u=[];let h,d,p=[],m=0;u[m]=void 0,p[m]=[];for(let t=0,a=i.length;t1){let e=!1,n=0;for(let e=0,t=u.length;e0&&!1===e&&(p=c)}for(let e=0,t=u.length;e{this.requestId=self.requestAnimationFrame(e),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this.animationLoop&&this.animationLoop(t,n)};e()}dispose(){self.cancelAnimationFrame(this.requestId)}setAnimationLoop(e){this.animationLoop=e}}class nf{constructor(){this.weakMap=new WeakMap}get(e){if(Array.isArray(e)){let t=this.weakMap;for(let n=0;n{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){const t=this.material;let n=this.clippingContext;Array.isArray(t.clippingPlanes)?(n!==e&&n||(n=new of,this.clippingContext=n),n.update(e,t)):this.clippingContext!==e&&(this.clippingContext=e)}clippingNeedsUpdate(){return this.clippingContext.version!==this.clippingContextVersion&&(this.clippingContextVersion=this.clippingContext.version,!0)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;n.push(e);const s=e.isInterleavedBufferAttribute?e.data:e;i.add(s)}return this.attributes=n,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getMaterialCacheKey(){const{object:e,material:t}=this;let n=t.customProgramCacheKey();for(const e in t){if(/^(is[A-Z])|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;let i=t[e];if(null!==i){const e=typeof i;"number"===e?i=0!==i?"1":"0":"object"===e&&(i="{}")}n+=i+","}return n+=this.clippingContextVersion+",",e.skeleton&&(n+=e.skeleton.bones.length+","),e.morphTargetInfluences&&(n+=e.morphTargetInfluences.length+","),n}get needsUpdate(){return this.initialNodesCacheKey!==this.getNodesCacheKey()}getNodesCacheKey(){return this._nodes.getCacheKey(this.scene,this.lightsNode)}getCacheKey(){return this.getMaterialCacheKey()+","+this.getNodesCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}class uf{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this.chainMaps={}}get(e,t,n,i,r,s,a){const o=this.getChainMap(a),l=[e,t,s,r];let c=o.get(l);return void 0===c?(c=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a),o.set(l,c)):(c.updateClipping(s.clippingContext),(c.version!==t.version||c.needsUpdate||c.clippingNeedsUpdate())&&(c.initialCacheKey!==c.getCacheKey()?(c.dispose(),c=this.get(e,t,n,i,r,s,a)):c.version=t.version)),c}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new nf)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,c){const u=this.getChainMap(c),h=new cf(e,t,n,i,r,s,a,o,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),u.delete(h.getChainArray())},h}}class hf{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const df=1,pf=2,mf=4,ff=16;class gf extends hf{constructor(e){super(),this.backend=e}delete(e){void 0!==super.delete(e)&&this.backend.destroyAttribute(e)}update(e,t){const n=this.get(e);if(void 0===n.version)t===df?this.backend.createAttribute(e):t===pf?this.backend.createIndexAttribute(e):t===mf&&this.backend.createStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?ms:ds)(t,1);return r.version=_f(e),r}class xf extends hf{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const n=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n)};t.addEventListener("dispose",n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)this.updateAttribute(e,df);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,pf)}updateAttribute(e,t){const n=this.info.render.calls;this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=vf(t),e.set(t,n)):n.version!==_f(t)&&(this.attributes.delete(n),n=vf(t),e.set(t,n)),i=n}return i}}class yf{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,drawCalls:0,triangles:0,points:0,lines:0},this.compute={calls:0,computeCalls:0},this.memory={geometries:0,textures:0},this.timestamp={compute:0,render:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine&&(this.render.lines+=n*(t-1))}updateTimestamp(e,t){this.timestamp[e]+=t}resetCompute(){this.compute.computeCalls=0,this.timestamp.compute=0}reset(){this.render.drawCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0,this.timestamp.render=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.timestamp.compute=0,this.timestamp.render=0,this.memory.geometries=0,this.memory.textures=0}}class bf{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Sf extends bf{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class Tf extends bf{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Mf=0;class Ef{constructor(e,t,n=null,i=null){this.id=Mf++,this.code=e,this.stage=t,this.transforms=n,this.attributes=i,this.usedTimes=0}}class Af extends hf{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:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new Ef(s.computeShader,"compute",s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(e),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState();let a=this.programs.vertex.get(s.vertexShader);void 0===a&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),a=new Ef(s.vertexShader,"vertex"),this.programs.vertex.set(s.vertexShader,a),n.createProgram(a));let o=this.programs.fragment.get(s.fragmentShader);void 0===o&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),o=new Ef(s.fragmentShader,"fragment"),this.programs.fragment.set(s.fragmentShader,o),n.createProgram(o));const l=this._getRenderCacheKey(e,a,o);let c=this.caches.get(l);void 0===c?(r&&0===r.usedTimes&&this._releasePipeline(r),c=this._getRenderPipeline(e,a,o,l,t)):e.pipeline=c,c.usedTimes++,a.usedTimes++,o.usedTimes++,i.pipeline=c}return i.pipeline}delete(e){const t=this.get(e).pipeline;t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return void 0===r&&(r=new Tf(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,n,i,r){i=i||this._getRenderCacheKey(e,t,n);let s=this.caches.get(i);return void 0===s&&(s=new Sf(i,t,n),this.caches.set(i,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_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 wf extends hf{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),n=this.get(e);return n.bindings!==t&&(n.bindings=t,this._init(t),this.backend.createBindings(t)),n.bindings}getForCompute(e){const t=this.get(e);if(void 0===t.bindings){const n=this.nodes.getForCompute(e).bindings;t.bindings=n,this._init(n),this.backend.createBindings(n)}return t.bindings}updateForCompute(e){this._update(e,this.getForCompute(e))}updateForRender(e){this._update(e,this.getForRender(e))}_init(e){for(const t of e)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute;this.attributes.update(e,mf)}}_update(e,t){const{backend:n}=this;let i=!1;for(const e of t){if(e.isNodeUniformsGroup){if(!this.nodes.updateGroup(e))continue}if(e.isUniformBuffer){e.update()&&n.updateBinding(e)}else if(e.isSampledTexture){const t=e.texture;e.needsBindingsUpdate&&(i=!0);if(e.update()&&this.textures.updateTexture(e.texture),!0===t.isStorageTexture){const n=this.get(t);!0===e.store?n.needsMipmap=!0:!0===t.generateMipmaps&&this.textures.needsMipmaps(t)&&!0===n.needsMipmap&&(this.backend.generateMipmaps(t),n.needsMipmap=!1)}}}if(!0===i){const n=this.pipelines.getForRender(e);this.backend.updateBindings(t,n)}}}const Rf={VERTEX:"vertex",FRAGMENT:"fragment"},Cf={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Nf={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Pf=["fragment","vertex"],Lf=["setup","analyze","generate"],If=[...Pf,"compute"],Uf=["x","y","z","w"];function Of(e){let t="{";!0===e.isNode&&(t+=e.id);for(const{property:n,childNode:i}of Df(e))t+=","+n.slice(0,-4)+":"+i.getCacheKey();return t+="}",t}function*Df(e,t=!1){for(const n in e){if(!0===n.startsWith("_"))continue;const i=e[n];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer}var Gf=Object.freeze({__proto__:null,getCacheKey:Of,getNodeChildren:Df,getValueType:Ff,getValueFromType:Bf,arrayBufferToBase64:Vf,base64ToArrayBuffer:zf});const kf=new Map;let Hf=0;class Wf extends Bn{constructor(e=null){super(),this.nodeType=e,this.updateType=Cf.NONE,this.updateBeforeType=Cf.NONE,this.uuid=Kn.generateUUID(),this.isNode=!0,Object.defineProperty(this,"id",{value:Hf++})}get type(){return this.constructor.type}getSelf(){return this.self||this}setReference(){return this}isGlobal(){return!1}*getChildren(){for(const{childNode:e}of Df(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(){return Of(this)}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}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);for(const e of this.getChildren())t["_node"+e.id]=e;return null}construct(e){return this.setup(e)}increaseUsage(e){const t=e.getDataFromNode(this);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}analyze(e){if(1===this.increaseUsage(e)){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){}update(){}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.setReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized||!1===e.context.tempRead){const n=e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length!==n&&(t.outputNode=e.stack);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e)}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const n=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i&&(i=this.generate(e)||"",r.snippet=i),i=e.format(i,n,t)}else i=this.generate(e,t)||""}return e.removeChain(this),i}getSerializeChildren(){return Df(this)}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:r,childNode:s}of t)void 0!==r?(void 0===n[i]&&(n[i]=Number.isInteger(r)?[]:{}),n[i][r]=s.toJSON(e.meta).uuid):n[i]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}function Xf(e,t){if("function"!=typeof t||!e)throw new Error(`Node class ${e} is not a class`);kf.has(e)||(kf.set(e,t),t.type=e)}function jf(e){const t=kf.get(e);if(void 0!==t)return new t}class qf extends Wf{constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(!1!==e.context.tempRead&&void 0!==i.propertyName)return e.format(i.propertyName,n,t);if(!1!==e.context.tempWrite&&"void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}Xf("TempNode",qf);class Yf extends Wf{constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getNodeType(e)}generate(e){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}Xf("ArrayElementNode",Yf);class $f extends Wf{constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}Xf("ConvertNode",$f);class Zf extends qf{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,n)=>t+e.getTypeLength(n.getNodeType(e))),0))}generate(e,t){const n=this.getNodeType(e),i=this.nodes,r=e.getComponentType(n),s=[];for(const t of i){let n=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(n=e.format(n,i,r)),s.push(n)}const a=`${e.getType(n)}( ${s.join(", ")} )`;return e.format(a,n,t)}}Xf("JoinNode",Zf);const Kf=Uf.join("");class Jf extends Wf{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(Uf.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 n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===Kf.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}Xf("SplitNode",Jf);class Qf extends qf{constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getTypeFromLength(n.length),a=i.build(e,s),o=t.build(e,r),l=e.getTypeLength(r),c=[];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"),ag={setup(e,t){const n=t.shift();return e(Ng(n),...t)},get(e,t,n){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(ng.assign(n,...e),n);if(ig.has(t)){const i=ig.get(t);return e.isStackNode?(...e)=>n.add(i(...e)):(...e)=>i(n,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&ig.has(t.slice(0,t.length-6))){const i=ig.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>n.assign(e[0],i(...e)):(...e)=>n.assign(i(n,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=sg(t),Cg(new Jf(n,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=(t=sg(t.slice(3).toLowerCase())).split("").sort().join(""),n=>Cg(new Qf(e,t,n));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Cg(new Jf(e,t));if(!0===/^\d+$/.test(t))return Cg(new Yf(n,new tg(Number(t),"uint")))}return Reflect.get(e,t,n)},set:(e,t,n,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,n,i):(i[t].assign(n),!0)},og=new WeakMap,lg=new WeakMap,cg=function(e,t=null){for(const n in e)e[n]=Cg(e[n],t);return e},ug=function(e,t=null){const n=e.length;for(let i=0;iCg(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...Pg(t))):null!==n?(n=Cg(n),(...i)=>r(new e(t,...Pg(i),n))):(...n)=>r(new e(t,...Pg(n)))},dg=function(e,...t){return Cg(new e(...Pg(t)))};class pg extends Wf{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){const{outputNode:t}=e.getNodeProperties(this);return t?t.getNodeType(e):super.getNodeType(e)}call(e){const{shaderNode:t,inputNodes:n}=this;if(t.layout){let i=lg.get(e.constructor);void 0===i&&(i=new WeakMap,lg.set(e.constructor,i));let r=i.get(t);return void 0===r&&(r=Cg(e.buildFunctionNode(t)),i.set(t,r)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(r),Cg(r.call(n))}const i=t.jsFunc,r=null!==n?i(n,e.stack,e):i(e.stack,e);return Cg(r)}setup(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);return null===n?this.call(e).build(e,t):super.generate(e,t)}}class mg extends Wf{constructor(e){super(),this.jsFunc=e,this.layout=null}get isArrayInput(){return/^\((\s+)?\[/.test(this.jsFunc.toString())}setLayout(e){return this.layout=e,this}call(e=null){return Ng(e),Cg(new pg(this,e))}setup(){return this.call()}}const fg=[!1,!0],gg=[0,1,2,3],_g=[-1,-2],vg=[.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],xg=new Map;for(const e of fg)xg.set(e,new tg(e));const yg=new Map;for(const e of gg)yg.set(e,new tg(e,"uint"));const bg=new Map([...yg].map((e=>new tg(e.value,"int"))));for(const e of _g)bg.set(e,new tg(e,"int"));const Sg=new Map([...bg].map((e=>new tg(e.value))));for(const e of vg)Sg.set(e,new tg(e));for(const e of vg)Sg.set(-e,new tg(-e));const Tg={bool:xg,uint:yg,ints:bg,float:Sg},Mg=new Map([...xg,...Sg]),Eg=(e,t)=>Mg.has(e)?Mg.get(e):!0===e.isNode?e:new tg(e,t),Ag=function(e,t=null){return(...n)=>{if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every((e=>"object"!=typeof e)))&&(n=[Bf(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Cg(t.get(n[0]));if(1===n.length){const t=Eg(n[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Cg(t):Cg(new $f(t,e))}const i=n.map((e=>Eg(e)));return Cg(new Zf(i,e))}},wg=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Rg(e){return new Proxy(new mg(e),ag)}const Cg=(e,t=null)=>function(e,t=null){const n=Ff(e);if("node"===n){let t=og.get(e);return void 0===t&&(t=new Proxy(e,ag),og.set(e,t),og.set(t,t)),t}return null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Cg(Eg(e,t)):"shader"===n?Og(e):e}(e,t),Ng=(e,t=null)=>new cg(e,t),Pg=(e,t=null)=>new ug(e,t),Lg=(...e)=>new hg(...e),Ig=(...e)=>new dg(...e),Ug=e=>new Rg(e),Og=e=>{const t=new Rg(e),n=(...e)=>{let n;return Ng(e),n=e[0]&&e[0].isNode?[...e]:e[0],t.call(n)};return n.shaderNode=t,n.setLayout=e=>(t.setLayout(e),n),n};Xf("ShaderNode",Rg);const Dg=e=>{ng=e},Fg=()=>ng,Bg=(...e)=>ng.if(...e);function Vg(e){return ng&&ng.add(e),e}rg("append",Vg);const zg=new Ag("color"),Gg=new Ag("float",Tg.float),kg=new Ag("int",Tg.int),Hg=new Ag("uint",Tg.uint),Wg=new Ag("bool",Tg.bool),Xg=new Ag("vec2"),jg=new Ag("ivec2"),qg=new Ag("uvec2"),Yg=new Ag("bvec2"),$g=new Ag("vec3"),Zg=new Ag("ivec3"),Kg=new Ag("uvec3"),Jg=new Ag("bvec3"),Qg=new Ag("vec4"),e_=new Ag("ivec4"),t_=new Ag("uvec4"),n_=new Ag("bvec4"),i_=new Ag("mat2"),r_=new Ag("imat2"),s_=new Ag("umat2"),a_=new Ag("bmat2"),o_=new Ag("mat3"),l_=new Ag("imat3"),c_=new Ag("umat3"),u_=new Ag("bmat3"),h_=new Ag("mat4"),d_=new Ag("imat4"),p_=new Ag("umat4"),m_=new Ag("bmat4"),f_=(e="")=>Cg(new tg(e,"string")),g_=e=>Cg(new tg(e,"ArrayBuffer"));rg("color",zg),rg("float",Gg),rg("int",kg),rg("uint",Hg),rg("bool",Wg),rg("vec2",Xg),rg("ivec2",jg),rg("uvec2",qg),rg("bvec2",Yg),rg("vec3",$g),rg("ivec3",Zg),rg("uvec3",Kg),rg("bvec3",Jg),rg("vec4",Qg),rg("ivec4",e_),rg("uvec4",t_),rg("bvec4",n_),rg("mat2",i_),rg("imat2",r_),rg("umat2",s_),rg("bmat2",a_),rg("mat3",o_),rg("imat3",l_),rg("umat3",c_),rg("bmat3",u_),rg("mat4",h_),rg("imat4",d_),rg("umat4",p_),rg("bmat4",m_),rg("string",f_),rg("arrayBuffer",g_);const __=Lg(Yf),v_=(e,t)=>Cg(new $f(Cg(e),t)),x_=(e,t)=>Cg(new Jf(Cg(e),t));rg("element",__),rg("convert",v_);class y_ extends qf{constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return Uf.join("").slice(0,n)!==t.components}return!1}generate(e,t){const{targetNode:n,sourceNode:i}=this,r=this.needsSplitAssign(e),s=n.getNodeType(e),a=n.context({assign:!0}).build(e),o=i.build(e,s),l=i.getNodeType(e),c=e.getDataFromNode(this);let u;if(!0===c.initialized)"void"!==t&&(u=a);else if(r){const i=e.getVarFromNode(this,null,s),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`);const l=n.node.context({assign:!0}).build(e);for(let t=0;tCg(new M_(e,t));Xf("AttributeNode",M_);class A_ extends Wf{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.outputNode.build(e)}}const w_=Lg(A_);rg("bypass",w_),Xf("BypassNode",A_);let R_=0;class C_{constructor(){this.id=R_++,this.nodesData=new WeakMap}getNodeData(e){return this.nodesData.get(e)}setNodeData(e,t){this.nodesData.set(e,t)}}class N_ extends Wf{constructor(e,t=new C_){super(),this.isCacheNode=!0,this.node=e,this.cache=t}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const n=e.getCache(),i=this.cache||e.globalCache;e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}}const P_=Lg(N_);rg("cache",P_),rg("globalCache",(e=>P_(e,null))),Xf("CacheNode",N_);class L_ extends Wf{constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.context=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.context});const n=this.node.build(e);return e.setContext(t),n}generate(e,t){const n=e.getContext();e.setContext({...e.context,...this.context});const i=this.node.build(e,t);return e.setContext(n),i}}const I_=Lg(L_),U_=(e,t)=>I_(e,{label:t});rg("context",I_),rg("label",U_),Xf("ContextNode",L_);class O_ extends Wf{constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===O_.VERTEX)i=e.getVertexIndex();else{if(n!==O_.INSTANCE)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getInstanceIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=T_(this).build(e,t)}return r}}O_.VERTEX="vertex",O_.INSTANCE="instance";const D_=Ig(O_,O_.VERTEX),F_=Ig(O_,O_.INSTANCE);Xf("IndexNode",O_);class B_{start(){}finish(){}direct(){}indirectDiffuse(){}indirectSpecular(){}ambientOcclusion(){}}class V_ extends Wf{constructor(e,t=null){super(),this.node=e,this.name=t,this.isVarNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:n}=this,i=e.getVarFromNode(this,n,e.getVectorType(this.getNodeType(e))),r=e.getPropertyName(i),s=t.build(e,i.type);return e.addLineFlowCode(`${r} = ${s}`),r}}const z_=Lg(V_);rg("temp",z_),rg("toVar",((...e)=>z_(...e).append())),Xf("VarNode",V_);class G_{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class k_{constructor(e,t,n,i=void 0){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n.getSelf(),this.needsUpdate=i}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 H_{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class W_ extends H_{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class X_{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}class j_{constructor(){this.keywords=[],this.nodes=[],this.keywordsCallback={}}getNode(e){let t=this.nodes[e];return void 0===t&&void 0!==this.keywordsCallback[e]&&(t=this.keywordsCallback[e](e),this.nodes[e]=t),t}addKeyword(e,t){return this.keywords.push(e),this.keywordsCallback[e]=t,this}parse(e){const t=this.keywords,n=new RegExp(`\\b${t.join("\\b|\\b")}\\b`,"g"),i=e.match(n),r=[];if(null!==i)for(const e of i){const t=this.getNode(e);void 0!==t&&-1===r.indexOf(t)&&r.push(t)}return r}include(e,t){const n=this.parse(t);for(const t of n)t.build(e)}}class q_ extends Wf{constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Y_=(e,t)=>Cg(new q_(e,t)),$_=(e,t)=>Cg(new q_(e,t,!0)),Z_=Ig(q_,"vec4","DiffuseColor"),K_=Ig(q_,"float","Roughness"),J_=Ig(q_,"float","Metalness"),Q_=Ig(q_,"float","Clearcoat"),ev=Ig(q_,"float","ClearcoatRoughness"),tv=Ig(q_,"vec3","Sheen"),nv=Ig(q_,"float","SheenRoughness"),iv=Ig(q_,"float","Iridescence"),rv=Ig(q_,"float","IridescenceIOR"),sv=Ig(q_,"float","IridescenceThickness"),av=Ig(q_,"color","SpecularColor"),ov=Ig(q_,"float","Shininess"),lv=Ig(q_,"vec4","Output"),cv=Ig(q_,"float","dashSize"),uv=Ig(q_,"float","gapSize"),hv=Ig(q_,"float","pointWidth");Xf("PropertyNode",q_);class dv extends q_{constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const pv=(e,t)=>Cg(new dv(e,t));Xf("ParameterNode",dv);class mv extends Wf{constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=n,this.includes=t}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const fv=Lg(mv),gv=(e,t)=>fv(e,t,"js"),_v=(e,t)=>fv(e,t,"wgsl"),vv=(e,t)=>fv(e,t,"glsl");Xf("CodeNode",mv);class xv extends mv{constructor(e="",t=[],n=""){super(e,t,n),this.keywords={}}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);""!==i&&(s.name=i);const a=e.getPropertyName(s);let o=this.getNodeFunction(e).getCode(a);const l=this.keywords,c=Object.keys(l);if(c.length>0)for(const t of c){const n=new RegExp(`\\b${t}\\b`,"g"),i=l[t].build(e,"property");o=o.replace(n,i)}return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}const yv=(e,t=[],n="")=>{for(let e=0;ei.call(...e);return r.functionNode=i,r},bv=(e,t)=>yv(e,t,"glsl"),Sv=(e,t)=>yv(e,t,"wgsl");Xf("FunctionNode",xv);class Tv extends Wf{constructor(e,t=!1){super("string"),this.name=e,this.version=0,this.shared=t,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}}const Mv=e=>new Tv(e),Ev=e=>new Tv(e,!0),Av=Ev("frame"),wv=Ev("render"),Rv=Mv("object");Xf("UniformGroupNode",Tv);class Cv extends eg{constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.groupNode=Rv}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const s=r.getInputType(e),a=e.getUniformFromNode(r,s,e.shaderStage,e.context.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,n,t)}}const Nv=(e,t)=>{const n=wg(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Cg(new Cv(i,n))};Xf("UniformNode",Cv);class Pv extends M_{constructor(e=0){super(null,"vec2"),this.isUVNode=!0,this.index=e}getAttributeName(){const e=this.index;return"uv"+(e>0?e:"")}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Lv=(...e)=>Cg(new Pv(...e));Xf("UVNode",Pv);class Iv extends Wf{constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),i=this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const Uv=Lg(Iv);rg("textureSize",Uv),Xf("TextureSizeNode",Iv);class Ov extends qf{constructor(e,t,n,...i){if(super(),this.op=e,i.length>0){let t=n;for(let n=0;n>"===n||"<<"===n)return e.getIntegerType(s);if("!"===n||"=="===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("<"===n||">"===n||"<="===n||">="===n){const n=t?e.getTypeLength(t):Math.max(e.getTypeLength(s),e.getTypeLength(a));return n>1?`bvec${n}`:"bool"}return"float"===s&&e.isMatrix(a)?a:e.isMatrix(s)&&e.isVector(a)?e.getVectorFromMatrix(s):e.isVector(s)&&e.isMatrix(a)?e.getVectorFromMatrix(a):e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,i=this.aNode,r=this.bNode,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=void 0!==r?r.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n?e.isVector(a)?o=a:a=o="float":">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):e.isMatrix(a)&&e.isVector(o)?o=e.getVectorFromMatrix(a):a=e.isVector(a)&&e.isMatrix(o)?e.getVectorFromMatrix(o):o=s):a=o=s;const l=i.build(e,a),c=void 0!==r?r.build(e,o):null,u=e.getTypeLength(t),h=e.getFunctionOperator(n);return"void"!==t?"<"===n&&u>1?e.format(`${e.getMethod("lessThan")}( ${l}, ${c} )`,s,t):"<="===n&&u>1?e.format(`${e.getMethod("lessThanEqual")}( ${l}, ${c} )`,s,t):">"===n&&u>1?e.format(`${e.getMethod("greaterThan")}( ${l}, ${c} )`,s,t):">="===n&&u>1?e.format(`${e.getMethod("greaterThanEqual")}( ${l}, ${c} )`,s,t):"!"===n||"~"===n?e.format(`(${n}${l})`,a,t):h?e.format(`${h}( ${l}, ${c} )`,s,t):e.format(`( ${l} ${n} ${c} )`,s,t):"void"!==a?h?e.format(`${h}( ${l}, ${c} )`,s,t):e.format(`${l} ${n} ${c}`,s,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Dv=Lg(Ov,"+"),Fv=Lg(Ov,"-"),Bv=Lg(Ov,"*"),Vv=Lg(Ov,"/"),zv=Lg(Ov,"%"),Gv=Lg(Ov,"=="),kv=Lg(Ov,"!="),Hv=Lg(Ov,"<"),Wv=Lg(Ov,">"),Xv=Lg(Ov,"<="),jv=Lg(Ov,">="),qv=Lg(Ov,"&&"),Yv=Lg(Ov,"||"),$v=Lg(Ov,"!"),Zv=Lg(Ov,"^^"),Kv=Lg(Ov,"&"),Jv=Lg(Ov,"~"),Qv=Lg(Ov,"|"),ex=Lg(Ov,"^"),tx=Lg(Ov,"<<"),nx=Lg(Ov,">>");rg("add",Dv),rg("sub",Fv),rg("mul",Bv),rg("div",Vv),rg("remainder",zv),rg("equal",Gv),rg("notEqual",kv),rg("lessThan",Hv),rg("greaterThan",Wv),rg("lessThanEqual",Xv),rg("greaterThanEqual",jv),rg("and",qv),rg("or",Yv),rg("not",$v),rg("xor",Zv),rg("bitAnd",Kv),rg("bitNot",Jv),rg("bitOr",Qv),rg("bitXor",ex),rg("shiftLeft",tx),rg("shiftRight",nx),Xf("OperatorNode",Ov);class ix extends qf{constructor(e,t,n=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=n,this.cNode=i}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>s&&r>a?t:s>a?n:a>r?i:t}getNodeType(e){const t=this.method;return t===ix.LENGTH||t===ix.DISTANCE||t===ix.DOT?"float":t===ix.CROSS?"vec3":t===ix.ALL?"bool":t===ix.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===ix.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const n=this.method,i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=!0===e.renderer.isWebGLRenderer;if(n===ix.TRANSFORM_DIRECTION){let n=s,i=a;e.isMatrix(n.getNodeType(e))?i=Qg($g(i),0):n=Qg($g(n),0);const r=Bv(n,i).xyz;return bx(r).build(e,t)}if(n===ix.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);if(n===ix.ONE_MINUS)return Fv(1,s).build(e,t);if(n===ix.RECIPROCAL)return Vv(1,s).build(e,t);if(n===ix.DIFFERENCE)return Cx(Fv(s,a)).build(e,t);{const c=[];return n===ix.CROSS||n===ix.MOD?c.push(s.build(e,i),a.build(e,i)):n===ix.STEP?c.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l&&(n===ix.MIN||n===ix.MAX)||n===ix.MOD?c.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):n===ix.REFRACT?c.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===ix.MIX?c.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(c.push(s.build(e,r)),null!==a&&c.push(a.build(e,r)),null!==o&&c.push(o.build(e,r))),e.format(`${e.getMethod(n,i)}( ${c.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}ix.ALL="all",ix.ANY="any",ix.EQUALS="equals",ix.RADIANS="radians",ix.DEGREES="degrees",ix.EXP="exp",ix.EXP2="exp2",ix.LOG="log",ix.LOG2="log2",ix.SQRT="sqrt",ix.INVERSE_SQRT="inversesqrt",ix.FLOOR="floor",ix.CEIL="ceil",ix.NORMALIZE="normalize",ix.FRACT="fract",ix.SIN="sin",ix.COS="cos",ix.TAN="tan",ix.ASIN="asin",ix.ACOS="acos",ix.ATAN="atan",ix.ABS="abs",ix.SIGN="sign",ix.LENGTH="length",ix.NEGATE="negate",ix.ONE_MINUS="oneMinus",ix.DFDX="dFdx",ix.DFDY="dFdy",ix.ROUND="round",ix.RECIPROCAL="reciprocal",ix.TRUNC="trunc",ix.FWIDTH="fwidth",ix.BITCAST="bitcast",ix.ATAN2="atan2",ix.MIN="min",ix.MAX="max",ix.MOD="mod",ix.STEP="step",ix.REFLECT="reflect",ix.DISTANCE="distance",ix.DIFFERENCE="difference",ix.DOT="dot",ix.CROSS="cross",ix.POW="pow",ix.TRANSFORM_DIRECTION="transformDirection",ix.MIX="mix",ix.CLAMP="clamp",ix.REFRACT="refract",ix.SMOOTHSTEP="smoothstep",ix.FACEFORWARD="faceforward";const rx=Gg(1e-6),sx=Gg(1e6),ax=Gg(Math.PI),ox=Gg(2*Math.PI),lx=Lg(ix,ix.ALL),cx=Lg(ix,ix.ANY),ux=Lg(ix,ix.EQUALS),hx=Lg(ix,ix.RADIANS),dx=Lg(ix,ix.DEGREES),px=Lg(ix,ix.EXP),mx=Lg(ix,ix.EXP2),fx=Lg(ix,ix.LOG),gx=Lg(ix,ix.LOG2),_x=Lg(ix,ix.SQRT),vx=Lg(ix,ix.INVERSE_SQRT),xx=Lg(ix,ix.FLOOR),yx=Lg(ix,ix.CEIL),bx=Lg(ix,ix.NORMALIZE),Sx=Lg(ix,ix.FRACT),Tx=Lg(ix,ix.SIN),Mx=Lg(ix,ix.COS),Ex=Lg(ix,ix.TAN),Ax=Lg(ix,ix.ASIN),wx=Lg(ix,ix.ACOS),Rx=Lg(ix,ix.ATAN),Cx=Lg(ix,ix.ABS),Nx=Lg(ix,ix.SIGN),Px=Lg(ix,ix.LENGTH),Lx=Lg(ix,ix.NEGATE),Ix=Lg(ix,ix.ONE_MINUS),Ux=Lg(ix,ix.DFDX),Ox=Lg(ix,ix.DFDY),Dx=Lg(ix,ix.ROUND),Fx=Lg(ix,ix.RECIPROCAL),Bx=Lg(ix,ix.TRUNC),Vx=Lg(ix,ix.FWIDTH),zx=Lg(ix,ix.BITCAST),Gx=Lg(ix,ix.ATAN2),kx=Lg(ix,ix.MIN),Hx=Lg(ix,ix.MAX),Wx=Lg(ix,ix.MOD),Xx=Lg(ix,ix.STEP),jx=Lg(ix,ix.REFLECT),qx=Lg(ix,ix.DISTANCE),Yx=Lg(ix,ix.DIFFERENCE),$x=Lg(ix,ix.DOT),Zx=Lg(ix,ix.CROSS),Kx=Lg(ix,ix.POW),Jx=Lg(ix,ix.POW,2),Qx=Lg(ix,ix.POW,3),ey=Lg(ix,ix.POW,4),ty=Lg(ix,ix.TRANSFORM_DIRECTION),ny=e=>Bv(Nx(e),Kx(Cx(e),1/3)),iy=e=>$x(e,e),ry=Lg(ix,ix.MIX),sy=(e,t=0,n=1)=>Cg(new ix(ix.CLAMP,Cg(e),Cg(t),Cg(n))),ay=e=>sy(e),oy=Lg(ix,ix.REFRACT),ly=Lg(ix,ix.SMOOTHSTEP),cy=Lg(ix,ix.FACEFORWARD);rg("all",lx),rg("any",cx),rg("equals",ux),rg("radians",hx),rg("degrees",dx),rg("exp",px),rg("exp2",mx),rg("log",fx),rg("log2",gx),rg("sqrt",_x),rg("inverseSqrt",vx),rg("floor",xx),rg("ceil",yx),rg("normalize",bx),rg("fract",Sx),rg("sin",Tx),rg("cos",Mx),rg("tan",Ex),rg("asin",Ax),rg("acos",wx),rg("atan",Rx),rg("abs",Cx),rg("sign",Nx),rg("length",Px),rg("lengthSq",iy),rg("negate",Lx),rg("oneMinus",Ix),rg("dFdx",Ux),rg("dFdy",Ox),rg("round",Dx),rg("reciprocal",Fx),rg("trunc",Bx),rg("fwidth",Vx),rg("atan2",Gx),rg("min",kx),rg("max",Hx),rg("mod",Wx),rg("step",Xx),rg("reflect",jx),rg("distance",qx),rg("dot",$x),rg("cross",Zx),rg("pow",Kx),rg("pow2",Jx),rg("pow3",Qx),rg("pow4",ey),rg("transformDirection",ty),rg("mix",((e,t,n)=>ry(t,n,e))),rg("clamp",sy),rg("refract",oy),rg("smoothstep",((e,t,n)=>ly(t,n,e))),rg("faceForward",cy),rg("difference",Yx),rg("saturate",ay),rg("cbrt",ny),Xf("MathNode",ix);const uy=Og((e=>{const{value:t}=e,{rgb:n}=t,i=n.mul(.9478672986).add(.0521327014).pow(2.4),r=n.mul(.0773993808),s=n.lessThanEqual(.04045),a=ry(i,r,s);return Qg(a,t.a)})),hy=Og((e=>{const{value:t}=e,{rgb:n}=t,i=n.pow(.41666).mul(1.055).sub(.055),r=n.mul(12.92),s=n.lessThanEqual(.0031308),a=ry(i,r,s);return Qg(a,t.a)})),dy=e=>{let t=null;return e===jt?t="Linear":e===Xt&&(t="sRGB"),t},py=(e,t)=>dy(e)+"To"+dy(t);class my extends qf{constructor(e,t){super("vec4"),this.method=e,this.node=t}setup(){const{method:e,node:t}=this;return e===my.LINEAR_TO_LINEAR?t:fy[e]({value:t})}}my.LINEAR_TO_LINEAR="LinearToLinear",my.LINEAR_TO_sRGB="LinearTosRGB",my.sRGB_TO_LINEAR="sRGBToLinear";const fy={[my.LINEAR_TO_sRGB]:hy,[my.sRGB_TO_LINEAR]:uy},gy=(e,t)=>Cg(new my(py(jt,t),Cg(e))),_y=(e,t)=>Cg(new my(py(t,jt),Cg(e))),vy=Lg(my,my.LINEAR_TO_sRGB),xy=Lg(my,my.sRGB_TO_LINEAR);rg("linearTosRGB",vy),rg("sRGBToLinear",xy),rg("linearToColorSpace",gy),rg("colorSpaceToLinear",_y),Xf("ColorSpaceNode",my);class yy extends Wf{constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(`( ${i} )`,n,t);e.addLineFlowCode(i)}}const by=Lg(yy);Xf("ExpressionNode",yy);class Sy extends Cv{constructor(e){super(0),this.textureNode=e,this.updateType=Cf.FRAME}get texture(){return this.textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Ty=Lg(Sy);Xf("MaxMipLevelNode",Sy);class My extends Cv{constructor(e,t=null,n=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.compareNode=null,this.depthNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Cf.NONE,this.setUpdateMatrix(null===t)}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Lv(this.value.channel)}setReference(){return this.value}getTransformedUV(e){const t=this.value;return Nv(t.matrix).mul($g(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Cf.FRAME:Cf.NONE,this}setupUV(e,t){const n=this.value;return!e.isFlipY()||!0!==n.isRenderTargetTexture&&!0!==n.isFramebufferTexture&&!0!==n.isDepthTexture||(t=t.setY(t.y.oneMinus())),t}setup(e){const t=e.getNodeProperties(this);let n=this.uvNode;null!==n&&!0!==e.context.forceUVContext||!e.context.getUV||(n=e.context.getUV(this)),n||(n=this.getDefaultUV()),!0===this.updateMatrix&&(n=this.getTransformedUV(n)),n=this.setupUV(e,n);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),null!==i&&void 0!==e.context.getTextureLevelAlgorithm&&(i=e.context.getTextureLevelAlgorithm(this,i)),t.uvNode=n,t.levelNode=i,t.compareNode=this.compareNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,n,i,r,s){const a=this.value;let o;return o=i?e.generateTextureLevel(a,t,n,i,r):s?e.generateTextureCompare(a,t,n,s,r):!1===this.sampler?e.generateTextureLoad(a,t,n,r):e.generateTexture(a,t,n,r),o}generate(e,t){const n=e.getNodeProperties(this),i=this.value;if(!i||!0!==i.isTexture)throw new Error("TextureNode: Need a three.js texture.");const r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this);let a=s.propertyName;if(void 0===a){const{uvNode:t,levelNode:i,compareNode:o,depthNode:l}=n,c=this.generateUV(e,t),u=i?i.build(e,"float"):null,h=l?l.build(e,"int"):null,d=o?o.build(e,"float"):null,p=e.getVarFromNode(this);a=e.getPropertyName(p);const m=this.generateSnippet(e,r,c,u,h,d);e.addLineFlowCode(`${a} = ${m}`),!1!==e.context.tempWrite&&(s.snippet=m,s.propertyName=a)}let o=a;const l=this.getNodeType(e);return e.needsColorSpaceToLinear(i)&&(o=_y(by(o,l),i.colorSpace).setup(e).build(e,l)),e.format(o,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=e,Cg(t)}blur(e){const t=this.clone();return t.levelNode=e.mul(Ty(t)),Cg(t)}level(e){const t=this.clone();return t.levelNode=e,t}size(e){return Uv(this,e)}compare(e){const t=this.clone();return t.compareNode=Cg(e),Cg(t)}depth(e){const t=this.clone();return t.depthNode=Cg(e),Cg(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value]}update(){const e=this.value;!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e}}const Ey=Lg(My),Ay=(...e)=>Ey(...e).setSampler(!1),wy=e=>(!0===e.isNode?e:Ey(e)).convert("sampler");rg("texture",Ey),Xf("TextureNode",My);class Ry extends Cv{constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n}getInputType(){return"buffer"}}const Cy=(e,t,n)=>Cg(new Ry(e,t,n));Xf("BufferNode",Ry);class Ny extends Yf{constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=super.generate(e),n=this.getNodeType();return e.format(t,"vec4",n)}}class Py extends Ry{constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=Cf.RENDER,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,n=this.getElementLength(),i=this.getElementType();if(1===n)for(let n=0;nCg(new Py(e,t));Xf("UniformsNode",Py);class Iy extends Yf{constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}}class Uy extends Wf{constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=null,this.node=null,this.updateType=Cf.OBJECT}element(e){return Cg(new Iy(this,Cg(e)))}setNodeType(e){let t=null;t=null!==this.count?Cy(null,e,this.count):Array.isArray(this.getValueFromReference())?Ly(null,e):"texture"===e?Ey(null):Nv(null,e),this.node=t}getNodeType(e){return this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;eCg(new Uy(e,t,n)),Dy=(e,t,n,i)=>Cg(new Uy(e,t,i,n));Xf("ReferenceNode",Uy);class Fy extends Uy{constructor(e,t,n=null){super(e,t,n),this.material=n}setReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const By=(e,t,n)=>Cg(new Fy(e,t,n));Xf("MaterialReferenceNode",Fy);class Vy extends Wf{constructor(e=Vy.VIEW_MATRIX,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Cf.OBJECT,this._uniformNode=new Cv(null)}getNodeType(){const e=this.scope;return e===Vy.WORLD_MATRIX||e===Vy.VIEW_MATRIX?"mat4":e===Vy.NORMAL_MATRIX?"mat3":e===Vy.POSITION||e===Vy.VIEW_POSITION||e===Vy.DIRECTION||e===Vy.SCALE?"vec3":void 0}update(e){const t=this.object3d,n=this._uniformNode,i=this.scope;if(i===Vy.VIEW_MATRIX)n.value=t.modelViewMatrix;else if(i===Vy.NORMAL_MATRIX)n.value=t.normalMatrix;else if(i===Vy.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===Vy.POSITION)n.value=n.value||new Ni,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===Vy.SCALE)n.value=n.value||new Ni,n.value.setFromMatrixScale(t.matrixWorld);else if(i===Vy.DIRECTION)n.value=n.value||new Ni,t.getWorldDirection(n.value);else if(i===Vy.VIEW_POSITION){const i=e.camera;n.value=n.value||new Ni,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}}generate(e){const t=this.scope;return t===Vy.WORLD_MATRIX||t===Vy.VIEW_MATRIX?this._uniformNode.nodeType="mat4":t===Vy.NORMAL_MATRIX?this._uniformNode.nodeType="mat3":t!==Vy.POSITION&&t!==Vy.VIEW_POSITION&&t!==Vy.DIRECTION&&t!==Vy.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Vy.VIEW_MATRIX="viewMatrix",Vy.NORMAL_MATRIX="normalMatrix",Vy.WORLD_MATRIX="worldMatrix",Vy.POSITION="position",Vy.SCALE="scale",Vy.VIEW_POSITION="viewPosition",Vy.DIRECTION="direction";const zy=Lg(Vy,Vy.DIRECTION),Gy=Lg(Vy,Vy.VIEW_MATRIX),ky=Lg(Vy,Vy.NORMAL_MATRIX),Hy=Lg(Vy,Vy.WORLD_MATRIX),Wy=Lg(Vy,Vy.POSITION),Xy=Lg(Vy,Vy.SCALE),jy=Lg(Vy,Vy.VIEW_POSITION);Xf("Object3DNode",Vy);class qy extends Vy{constructor(e=qy.POSITION){super(e),this.updateType=Cf.RENDER}getNodeType(e){const t=this.scope;return t===qy.PROJECTION_MATRIX||t===qy.PROJECTION_MATRIX_INVERSE?"mat4":t===qy.NEAR||t===qy.FAR||t===qy.LOG_DEPTH?"float":super.getNodeType(e)}update(e){const t=e.camera,n=this._uniformNode,i=this.scope;i===qy.VIEW_MATRIX?n.value=t.matrixWorldInverse:i===qy.PROJECTION_MATRIX?n.value=t.projectionMatrix:i===qy.PROJECTION_MATRIX_INVERSE?n.value=t.projectionMatrixInverse:i===qy.NEAR?n.value=t.near:i===qy.FAR?n.value=t.far:i===qy.LOG_DEPTH?n.value=2/(Math.log(t.far+1)/Math.LN2):(this.object3d=t,super.update(e))}generate(e){const t=this.scope;return t===qy.PROJECTION_MATRIX||t===qy.PROJECTION_MATRIX_INVERSE?this._uniformNode.nodeType="mat4":t!==qy.NEAR&&t!==qy.FAR&&t!==qy.LOG_DEPTH||(this._uniformNode.nodeType="float"),super.generate(e)}}qy.PROJECTION_MATRIX="projectionMatrix",qy.PROJECTION_MATRIX_INVERSE="projectionMatrixInverse",qy.NEAR="near",qy.FAR="far",qy.LOG_DEPTH="logDepth";const Yy=Ig(qy,qy.PROJECTION_MATRIX),$y=Ig(qy,qy.PROJECTION_MATRIX_INVERSE),Zy=Ig(qy,qy.NEAR),Ky=Ig(qy,qy.FAR),Jy=Ig(qy,qy.LOG_DEPTH),Qy=Ig(qy,qy.VIEW_MATRIX),eb=Ig(qy,qy.NORMAL_MATRIX),tb=Ig(qy,qy.WORLD_MATRIX),nb=Ig(qy,qy.POSITION);Xf("CameraNode",qy);class ib extends Vy{constructor(e=ib.VIEW_MATRIX){super(e)}update(e){this.object3d=e.object,super.update(e)}}const rb=Ig(ib,ib.DIRECTION),sb=Ig(ib,ib.VIEW_MATRIX).label("modelViewMatrix").temp("ModelViewMatrix"),ab=Ig(ib,ib.NORMAL_MATRIX),ob=Ig(ib,ib.WORLD_MATRIX),lb=Ig(ib,ib.POSITION),cb=Ig(ib,ib.SCALE),ub=Ig(ib,ib.VIEW_POSITION);Xf("ModelNode",ib);class hb extends Wf{constructor(e=hb.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`normal-${this.scope}`}generate(e){const t=this.scope;let n=null;if(t===hb.GEOMETRY)n=E_("normal","vec3");else if(t===hb.LOCAL)n=T_(db);else if(t===hb.VIEW){const e=ab.mul(pb);n=bx(T_(e))}else if(t===hb.WORLD){const e=mb.transformDirection(Qy);n=bx(T_(e))}return n.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}hb.GEOMETRY="geometry",hb.LOCAL="local",hb.VIEW="view",hb.WORLD="world";const db=Ig(hb,hb.GEOMETRY),pb=Ig(hb,hb.LOCAL).temp("Normal"),mb=Ig(hb,hb.VIEW),fb=Ig(hb,hb.WORLD),gb=Y_("vec3","TransformedNormalView"),_b=gb.transformDirection(Qy).normalize(),vb=Y_("vec3","TransformedClearcoatNormalView");Xf("NormalNode",hb);const xb=new Map;class yb extends Wf{constructor(e){super(),this.scope=e}getCache(e,t){let n=xb.get(e);return void 0===n&&(n=By(e,t),xb.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===yb.COLOR){const e=this.getColor(n);i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===yb.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===yb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture(n).r:Gg(1);else if(n===yb.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===yb.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===yb.EMISSIVE){const e=this.getColor(n);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?e.mul(this.getTexture(n)):e}else if(n===yb.NORMAL)i=t.normalMap?this.getTexture("normal").normalMap(this.getCache("normalScale","vec2")):t.bumpMap?this.getTexture("bump").r.bumpMap(this.getFloat("bumpScale")):mb;else if(n===yb.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===yb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===yb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?this.getTexture(n).normalMap(this.getCache(n+"Scale","vec2")):mb;else if(n===yb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===yb.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(.07,1)}else if(n===yb.IRIDESCENCE_THICKNESS){const e=Oy("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Oy("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}yb.ALPHA_TEST="alphaTest",yb.COLOR="color",yb.OPACITY="opacity",yb.SHININESS="shininess",yb.SPECULAR_COLOR="specular",yb.SPECULAR_STRENGTH="specularStrength",yb.REFLECTIVITY="reflectivity",yb.ROUGHNESS="roughness",yb.METALNESS="metalness",yb.NORMAL="normal",yb.CLEARCOAT="clearcoat",yb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",yb.CLEARCOAT_NORMAL="clearcoatNormal",yb.EMISSIVE="emissive",yb.ROTATION="rotation",yb.SHEEN="sheen",yb.SHEEN_ROUGHNESS="sheenRoughness",yb.IRIDESCENCE="iridescence",yb.IRIDESCENCE_IOR="iridescenceIOR",yb.IRIDESCENCE_THICKNESS="iridescenceThickness",yb.LINE_SCALE="scale",yb.LINE_DASH_SIZE="dashSize",yb.LINE_GAP_SIZE="gapSize",yb.LINE_WIDTH="linewidth",yb.LINE_DASH_OFFSET="dashOffset",yb.POINT_WIDTH="pointWidth";const bb=Ig(yb,yb.ALPHA_TEST),Sb=Ig(yb,yb.COLOR),Tb=Ig(yb,yb.SHININESS),Mb=Ig(yb,yb.EMISSIVE),Eb=Ig(yb,yb.OPACITY),Ab=Ig(yb,yb.SPECULAR_COLOR),wb=Ig(yb,yb.SPECULAR_STRENGTH),Rb=Ig(yb,yb.REFLECTIVITY),Cb=Ig(yb,yb.ROUGHNESS),Nb=Ig(yb,yb.METALNESS),Pb=Ig(yb,yb.NORMAL),Lb=Ig(yb,yb.CLEARCOAT),Ib=Ig(yb,yb.CLEARCOAT_ROUGHNESS),Ub=Ig(yb,yb.CLEARCOAT_NORMAL),Ob=Ig(yb,yb.ROTATION),Db=Ig(yb,yb.SHEEN),Fb=Ig(yb,yb.SHEEN_ROUGHNESS),Bb=Ig(yb,yb.IRIDESCENCE),Vb=Ig(yb,yb.IRIDESCENCE_IOR),zb=Ig(yb,yb.IRIDESCENCE_THICKNESS),Gb=Ig(yb,yb.LINE_SCALE),kb=Ig(yb,yb.LINE_DASH_SIZE),Hb=Ig(yb,yb.LINE_GAP_SIZE),Wb=Ig(yb,yb.LINE_WIDTH),Xb=Ig(yb,yb.LINE_DASH_OFFSET),jb=Ig(yb,yb.POINT_WIDTH);Xf("MaterialNode",yb);class qb extends Wf{constructor(e=qb.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`position-${this.scope}`}generate(e){const t=this.scope;let n=null;if(t===qb.GEOMETRY)n=E_("position","vec3");else if(t===qb.LOCAL)n=T_(Yb);else if(t===qb.WORLD){const e=ob.mul($b);n=T_(e)}else if(t===qb.VIEW){const e=sb.mul($b);n=T_(e)}else if(t===qb.VIEW_DIRECTION){const e=Jb.negate();n=bx(T_(e))}else if(t===qb.WORLD_DIRECTION){const e=$b.transformDirection(ob);n=bx(T_(e))}return n.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}qb.GEOMETRY="geometry",qb.LOCAL="local",qb.WORLD="world",qb.WORLD_DIRECTION="worldDirection",qb.VIEW="view",qb.VIEW_DIRECTION="viewDirection";const Yb=Ig(qb,qb.GEOMETRY),$b=Ig(qb,qb.LOCAL).temp("Position"),Zb=Ig(qb,qb.WORLD),Kb=Ig(qb,qb.WORLD_DIRECTION),Jb=Ig(qb,qb.VIEW),Qb=Ig(qb,qb.VIEW_DIRECTION);Xf("PositionNode",qb);class eS extends qf{constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return T_(e.context.mvp);const t=this.positionNode||$b;return Yy.mul(sb).mul(t)}}const tS=Lg(eS);Xf("ModelViewProjectionNode",eS);class nS extends eg{constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=Mn,this.instanced=!1,this.attribute=null,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}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),n=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,s=this.bufferOffset,a=!0===n.isInterleavedBuffer?n:new ac(n,r),o=new lc(a,i,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=T_(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this}setInstanced(e){return this.instanced=e,this}}const iS=(e,t,n,i)=>Cg(new nS(e,t,n,i)),rS=(e,t,n,i)=>iS(e,t,n,i).setUsage(En),sS=(e,t,n,i)=>iS(e,t,n,i).setInstanced(!0),aS=(e,t,n,i)=>rS(e,t,n,i).setInstanced(!0);rg("toAttribute",(e=>iS(e.value))),Xf("BufferAttributeNode",nS);class oS extends Wf{constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null}setup(){let e=this.instanceMatrixNode;if(null===e){const t=this.instanceMesh.instanceMatrix,n=new om(t.array,16,1),i=t.usage===En?aS:sS,r=[i(n,"vec4",16,0),i(n,"vec4",16,4),i(n,"vec4",16,8),i(n,"vec4",16,12)];e=h_(...r),this.instanceMatrixNode=e}const t=e.mul($b).xyz,n=o_(e[0].xyz,e[1].xyz,e[2].xyz),i=pb.div($g(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2]))),r=n.mul(i).xyz;$b.assign(t),pb.assign(r)}}const lS=Lg(oS);Xf("InstanceNode",oS);class cS extends Wf{constructor(e=cS.LOCAL){super(),this.scope=e}getHash(){return`tangent-${this.scope}`}getNodeType(){return this.scope===cS.GEOMETRY?"vec4":"vec3"}generate(e){const t=this.scope;let n=null;if(t===cS.GEOMETRY)n=E_("tangent","vec4"),!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents();else if(t===cS.LOCAL)n=T_(uS.xyz);else if(t===cS.VIEW){const e=sb.mul(Qg(hS,0)).xyz;n=bx(T_(e))}else if(t===cS.WORLD){const e=dS.transformDirection(Qy);n=bx(T_(e))}return n.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}cS.GEOMETRY="geometry",cS.LOCAL="local",cS.VIEW="view",cS.WORLD="world";const uS=Ig(cS,cS.GEOMETRY),hS=Ig(cS,cS.LOCAL),dS=Ig(cS,cS.VIEW),pS=Ig(cS,cS.WORLD),mS=z_(dS,"TransformedTangentView"),fS=bx(mS.transformDirection(Qy));Xf("TangentNode",cS);class gS extends Wf{constructor(e,t=!1){let n,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Cf.OBJECT,this.skinIndexNode=E_("skinIndex","uvec4"),this.skinWeightNode=E_("skinWeight","vec4"),t?(n=Oy("bindMatrix","mat4"),i=Oy("bindMatrixInverse","mat4"),r=Dy("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(n=Nv(e.bindMatrix,"mat4"),i=Nv(e.bindMatrixInverse,"mat4"),r=Cy(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=n,this.bindMatrixInverseNode=i,this.boneMatricesNode=r}setup(e){const{skinIndexNode:t,skinWeightNode:n,bindMatrixNode:i,bindMatrixInverseNode:r,boneMatricesNode:s}=this,a=s.element(t.x),o=s.element(t.y),l=s.element(t.z),c=s.element(t.w),u=i.mul($b),h=Dv(a.mul(n.x).mul(u),o.mul(n.y).mul(u),l.mul(n.z).mul(u),c.mul(n.w).mul(u)),d=r.mul(h).xyz;let p=Dv(n.x.mul(a),n.y.mul(o),n.z.mul(l),n.w.mul(c));p=r.mul(p).mul(i);const m=p.transformDirection(pb).xyz;$b.assign(d),pb.assign(m),e.hasGeometryAttribute("tangent")&&hS.assign(m)}generate(e,t){if("void"!==t)return $b.build(e,t)}update(e){(this.useReference?e.object:this.skinnedMesh).skeleton.update()}}const _S=e=>Cg(new gS(e));Xf("SkinningNode",gS);class vS extends Wf{constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;eNumber(s)?">=":"<"));const u={start:r,end:s,condition:l},h=u.start,d=u.end;let p="",m="",f="";c||(c="int"===o||"uint"===o?l.includes("<")?"++":"--":l.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(o,a)+" = "+h,m+=a+" "+l+" "+d,f+=a+" "+c;const g=`for ( ${p}; ${m}; ${f} )`;e.addFlowCode((0===t?"\n":"")+e.tab+g+" {\n\n").addFlowTab()}const r=I_(i,{tempWrite:!1}).build(e,"void"),s=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,n=this.params.length-1;tCg(new vS(Pg(e,"int"))).append(),yS=()=>by("continue").append(),bS=()=>by("break").append();rg("loop",((e,...t)=>w_(e,xS(...t)))),Xf("LoopNode",vS);const SS=new WeakMap,TS=new Si,MS=Og((({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=kg(D_).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return Ay(e,jg(l,o)).depth(r).mul(t)}));class ES extends Wf{constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Nv(1),this.updateType=Cf.OBJECT}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=SS.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],c=e.morphAttributes.color||[];let u=0;!0===t&&(u=1),!0===n&&(u=2),!0===i&&(u=3);let h=e.attributes.position.count*u,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const m=new Float32Array(h*d*4*s),f=new Ei(m,h,d,s);f.type=Le,f.needsUpdate=!0;const g=4*u;for(let v=0;v{const t=Oy("morphTargetInfluences","float").element(e);!0===n&&$b.addAssign(MS({bufferMap:a,influence:t,stride:o,width:c,depth:e,offset:kg(0)})),!0===i&&pb.addAssign(MS({bufferMap:a,influence:t,stride:o,width:c,depth:e,offset:kg(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 AS=Lg(ES);Xf("MorphNode",ES);class wS extends Wf{constructor(){super("vec3")}getHash(){return"reflectVector"}setup(){return Qb.negate().reflect(gb).transformDirection(Qy)}}const RS=Ig(wS);Xf("ReflectVectorNode",wS);class CS extends My{constructor(e,t=null,n=null){super(e,t,n),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){return RS}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.renderer.coordinateSystem!==Fn&&n.isRenderTargetTexture?t:$g(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const NS=Lg(CS);rg("cubeTexture",NS),Xf("CubeTextureNode",CS);class PS extends Wf{constructor(){super("vec3")}generate(){}}Xf("LightingNode",PS);let LS=null;class IS extends PS{constructor(e=null){super(),this.updateType=Cf.FRAME,this.light=e,this.rtt=null,this.shadowNode=null,this.color=new $r,this._defaultColorNode=Nv(this.color),this.colorNode=this._defaultColorNode,this.isAnalyticLightNode=!0}getCacheKey(){return super.getCacheKey()+"-"+this.light.id+"-"+(this.light.castShadow?"1":"0")}getHash(){return this.light.uuid}setupShadow(e){let t=this.shadowNode;if(null===t){null===LS&&(LS=e.createNodeMaterial(),LS.fragmentNode=Qg(0,0,0,1),LS.isShadowNodeMaterial=!0);const n=this.light.shadow,i=e.getRenderTarget(n.mapSize.width,n.mapSize.height),r=new Qa;r.minFilter=ge,r.magFilter=ge,r.image.width=n.mapSize.width,r.image.height=n.mapSize.height,r.compareFunction=_n,i.depthTexture=r,n.camera.updateProjectionMatrix();const s=Oy("bias","float",n),a=Oy("normalBias","float",n);let o=Nv(n.matrix).mul(Zb.add(fb.mul(a)));o=o.xyz.div(o.w);const l=o.x.greaterThanEqual(0).and(o.x.lessThanEqual(1)).and(o.y.greaterThanEqual(0)).and(o.y.lessThanEqual(1)).and(o.z.lessThanEqual(1));let c=o.z.add(s);e.renderer.coordinateSystem===Fn&&(c=c.mul(2).sub(1)),o=$g(o.x,o.y.oneMinus(),c);const u=(e,t,n)=>Ey(e,t).compare(n);t=u(r,o.xy,o.z);const h=Ey(i.texture,o);this.rtt=i,this.colorNode=this.colorNode.mul(l.mix(1,t.mix(h.a.mix(1,h),1))),this.shadowNode=t,this.updateBeforeType=Cf.RENDER}}setup(e){this.light.castShadow?this.setupShadow(e):null!==this.shadowNode&&this.disposeShadow()}updateShadow(e){const{rtt:t,light:n}=this,{renderer:i,scene:r}=e,s=r.overrideMaterial;r.overrideMaterial=LS,t.setSize(n.shadow.mapSize.width,n.shadow.mapSize.height),n.shadow.updateMatrices(n);const a=i.getRenderTarget(),o=i.getRenderObjectFunction();i.setRenderObjectFunction(((e,...t)=>{!0===e.castShadow&&i.renderObject(e,...t)})),i.setRenderTarget(t),i.render(r,n.shadow.camera),i.setRenderTarget(a),i.setRenderObjectFunction(o),r.overrideMaterial=s}disposeShadow(){this.rtt.dispose(),this.shadowNode=null,this.rtt=null,this.colorNode=this._defaultColorNode}updateBefore(e){const{light:t}=this;t.castShadow&&this.updateShadow(e)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}Xf("AnalyticLightNode",IS);const US=new WeakMap;class OS extends Wf{constructor(e=[]){super("vec3"),this.totalDiffuseNode=$g().temp("totalDiffuse"),this.totalSpecularNode=$g().temp("totalSpecular"),this.outgoingLightNode=$g().temp("outgoingLight"),this.lightNodes=e,this._hash=null}get hasLight(){return this.lightNodes.length>0}getHash(){if(null===this._hash){const e=[];for(const t of this.lightNodes)e.push(t.getHash());this._hash="lights-"+e.join(",")}return this._hash}setup(e){const t=e.context,n=t.lightingModel;let i=this.outgoingLightNode;if(n){const{lightNodes:r,totalDiffuseNode:s,totalSpecularNode:a}=this;t.outgoingLight=i;const o=e.addStack();n.start(t,o,e);for(const t of r)t.build(e);n.indirectDiffuse(t,o,e),n.indirectSpecular(t,o,e),n.ambientOcclusion(t,o,e);const{backdrop:l,backdropAlpha:c}=t,{directDiffuse:u,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=t.reflectedLight;let m=u.add(d);null!==l&&(m=$g(null!==c?c.mix(m,l):l)),s.assign(m),a.assign(h.add(p)),i.assign(s.add(a)),n.finish(t,o,e),i=i.bypass(e.removeStack())}return i}_getLightNodeById(e){for(const t of this.lightNodes)if(t.isAnalyticLightNode&&t.light.id===e)return t;return null}fromLights(e=[]){const t=[];e=(e=>e.sort(((e,t)=>e.id-t.id)))(e);for(const n of e){let e=this._getLightNodeById(n.id);if(null===e){const t=n.constructor,i=US.has(t)?US.get(t):IS;e=Cg(new i(n))}t.push(e)}return this.lightNodes=t,this._hash=null,this}}const DS=e=>Cg((new OS).fromLights(e)),FS=Lg(OS);function BS(e,t){if(!US.has(e)){if("function"!=typeof e)throw new Error(`Light ${e.name} is not a class`);if("function"!=typeof t||!t.type)throw new Error(`Light node ${t.type} is not a class`);US.set(e,t)}}class VS extends PS{constructor(e=null){super(),this.aoNode=e}setup(e){const t=this.aoNode.x.sub(1).mul(1).add(1);e.context.ambientOcclusion.mulAssign(t)}}Xf("AONode",VS);class zS extends L_{constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._context=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:$g().temp("directDiffuse"),directSpecular:$g().temp("directSpecular"),indirectDiffuse:$g().temp("indirectDiffuse"),indirectSpecular:$g().temp("indirectSpecular")};return{radiance:$g().temp("radiance"),irradiance:$g().temp("irradiance"),iblIrradiance:$g().temp("iblIrradiance"),ambientOcclusion:Gg(1).temp("ambientOcclusion"),reflectedLight:n,backdrop:e,backdropAlpha:t}}setup(e){return this.context=this._context||(this._context=this.getContext()),this.context.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const GS=Lg(zS);rg("lightingContext",GS),Xf("LightingContextNode",zS);class kS extends qf{constructor(e=Kb){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.negate().clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Xg(t,n)}}const HS=Lg(kS);Xf("EquirectUVNode",kS);class WS extends Wf{constructor(e,t=null){super("float"),this.textureNode=e,this.roughnessNode=t}setup(){const{textureNode:e,roughnessNode:t}=this,n=Ty(e),i=t.mul(t).mul(Math.PI).div(t.add(1));return n.add(i.log2()).clamp(0,n)}}const XS=Lg(WS);Xf("SpecularMIPLevelNode",WS);const jS=new WeakMap;class qS extends PS{constructor(e=null){super(),this.envNode=e}setup(e){let t=this.envNode;if(t.isTextureNode&&!0!==t.value.isCubeTexture){let n=jS.get(t.value);if(void 0===n){const i=t.value,r=e.renderer,s=e.getCubeRenderTarget(512).fromEquirectangularTexture(r,i);n=NS(s.texture),jS.set(t.value,n)}t=n}const n=Oy("envMapIntensity","float",e.material),i=I_(t,YS(K_,gb)).mul(n),r=I_(t,$S(_b)).mul(Math.PI).mul(n),s=P_(i);e.context.radiance.addAssign(s),e.context.iblIrradiance.addAssign(r);const a=e.context.lightingModel.clearcoatRadiance;if(a){const e=I_(t,YS(ev,vb)).mul(n),i=P_(e);a.addAssign(i)}}}const YS=(e,t)=>{let n=null,i=null;return{getUV:r=>{let s=null;return null===n&&(n=Qb.negate().reflect(t),n=e.mul(e).mix(n,t).normalize(),n=n.transformDirection(Qy)),r.isCubeTextureNode?s=n:r.isTextureNode&&(null===i&&(i=HS(n)),s=i),s},getTextureLevel:()=>e,getTextureLevelAlgorithm:(e,t)=>XS(e,t)}},$S=e=>{let t=null;return{getUV:n=>{let i=null;return n.isCubeTextureNode?i=e:n.isTextureNode&&(null===t&&(t=HS(e),t=Xg(t.x,t.y.oneMinus())),i=t),i},getTextureLevel:e=>Ty(e)}};let ZS,KS;Xf("EnvironmentNode",qS);class JS extends Wf{constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===JS.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Cf.NONE;return this.scope!==JS.RESOLUTION&&this.scope!==JS.VIEWPORT||(e=Cf.FRAME),this.updateType=e,e}update({renderer:e}){this.scope===JS.VIEWPORT?e.getViewport(KS):e.getDrawingBufferSize(ZS)}setup(){const e=this.scope;let t=null;if(e===JS.RESOLUTION)t=Nv(ZS||(ZS=new Jn));else if(e===JS.VIEWPORT)t=Nv(KS||(KS=new Si));else{t=QS.div(eT);let n=t.x,i=t.y;/bottom/i.test(e)&&(i=i.oneMinus()),/right/i.test(e)&&(n=n.oneMinus()),t=Xg(n,i)}return t}generate(e){if(this.scope===JS.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(eT).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}JS.COORDINATE="coordinate",JS.RESOLUTION="resolution",JS.VIEWPORT="viewport",JS.TOP_LEFT="topLeft",JS.BOTTOM_LEFT="bottomLeft",JS.TOP_RIGHT="topRight",JS.BOTTOM_RIGHT="bottomRight";const QS=Ig(JS,JS.COORDINATE),eT=Ig(JS,JS.RESOLUTION),tT=Ig(JS,JS.VIEWPORT),nT=Ig(JS,JS.TOP_LEFT),iT=Ig(JS,JS.BOTTOM_LEFT),rT=Ig(JS,JS.TOP_RIGHT),sT=Ig(JS,JS.BOTTOM_RIGHT);Xf("ViewportNode",JS);const aT=new Jn;class oT extends My{constructor(e=nT,t=null,n=null){null===n&&((n=new Uu).minFilter=Me),super(n,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Cf.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(aT);const n=this.value;n.image.width===aT.width&&n.image.height===aT.height||(n.image.width=aT.width,n.image.height=aT.height,n.needsUpdate=!0);const i=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=i}clone(){return new this.constructor(this.uvNode,this.levelNode,this.value)}}const lT=Lg(oT),cT=Lg(oT,null,null,{generateMipmaps:!0});rg("viewportTexture",lT),rg("viewportMipTexture",cT),Xf("ViewportTextureNode",oT);let uT=null;class hT extends oT{constructor(e=nT,t=null){null===uT&&(uT=new Qa),super(e,t,uT)}}const dT=Lg(hT);rg("viewportDepthTexture",dT),Xf("ViewportDepthTextureNode",hT);class pT extends Wf{constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===pT.DEPTH_PIXEL?e.getFragDepth():super.generate(e)}setup(){const{scope:e}=this;let t=null;if(e===pT.DEPTH)t=mT(Jb.z,Zy,Ky);else if(e===pT.DEPTH_TEXTURE){const e=this.valueNode||dT(),n=_T(e,Zy,Ky);t=mT(n,Zy,Ky)}else e===pT.DEPTH_PIXEL&&null!==this.valueNode&&(t=vT().assign(this.valueNode));return t}}const mT=(e,t,n)=>e.add(t).div(t.sub(n)),fT=(e,t,n)=>t.sub(n).mul(e).sub(t),gT=(e,t,n)=>t.add(e).mul(n).div(t.sub(n).mul(e)),_T=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n));pT.DEPTH="depth",pT.DEPTH_TEXTURE="depthTexture",pT.DEPTH_PIXEL="depthPixel";const vT=Lg(pT,pT.DEPTH_PIXEL),xT=Ig(pT,pT.DEPTH),yT=Lg(pT,pT.DEPTH_TEXTURE),bT=Ig(pT,pT.DEPTH_PIXEL);bT.assign=e=>vT(e),Xf("ViewportDepthNode",pT);class ST extends Wf{constructor(e=ST.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{localClipIntersection:n,localClippingCount:i,globalClippingCount:r}=t,s=r+i,a=n?s-i:s;return this.scope===ST.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(t.planes,s,a):this.setupDefault(t.planes,s,a)}setupAlphaToCoverage(e,t,n){return Og((()=>{const i=Ly(e),r=Y_("float","distanceToPlane"),s=Y_("float","distanceToGradient"),a=Y_("float","clipOpacity");let o;if(a.assign(1),xS(n,(({i:e})=>{o=i.element(e),r.assign(Jb.dot(o.xyz).negate().add(o.w)),s.assign(r.fwidth().div(2)),a.mulAssign(ly(s.negate(),s,r)),a.equal(0).discard()})),n{o=i.element(t),r.assign(Jb.dot(o.xyz).negate().add(o.w)),s.assign(r.fwidth().div(2)),e.mulAssign(ly(s.negate(),s,r).oneMinus())})),a.mulAssign(e.oneMinus())}Z_.a.mulAssign(a),Z_.a.equal(0).discard()}))()}setupDefault(e,t,n){return Og((()=>{const i=Ly(e);let r;if(xS(n,(({i:e})=>{r=i.element(e),Jb.dot(r.xyz).greaterThan(r.w).discard()})),n{r=i.element(t),e.assign(Jb.dot(r.xyz).greaterThan(r.w).and(e))})),e.discard()}}))()}}ST.ALPHA_TO_COVERAGE="alphaToCoverage",ST.DEFAULT="default";class TT extends Wf{constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){return e.getFrontFacing()}}const MT=Ig(TT),ET=Gg(MT).mul(2).sub(1);Xf("FrontFacingNode",TT);const AT=new Map;class wT extends $s{constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!0,this.normals=!0,this.colorSpaced=!0,this.lightsNode=null,this.envNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.positionNode=null,this.depthNode=null,this.shadowNode=null,this.outputNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+Of(this)}build(e){this.setup(e)}setup(e){let t;e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),e.addFlow("vertex",e.removeStack()),e.addStack();const n=this.setupClipping(e);if(null===this.fragmentNode){!0===this.depthWrite&&this.setupDepth(e),!0===this.normals&&this.setupNormal(e),this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==n&&e.stack.add(n),t=this.setupOutput(e,Qg(i,Z_.a)),lv.assign(t),null!==this.outputNode&&(t=this.outputNode)}else t=this.setupOutput(e,this.fragmentNode);e.stack.outputNode=t,e.addFlow("fragment",e.removeStack())}setupClipping(e){const{globalClippingCount:t,localClippingCount:n}=e.clippingContext;let i=null;return(t||n)&&(this.alphaToCoverage?i=Cg(new ST(ST.ALPHA_TO_COVERAGE)):e.stack.add(Cg(new ST))),i}setupDepth(e){const{renderer:t}=e;let n=this.depthNode;if(null===n&&!0===t.logarithmicDepthBuffer){n=tS().w.add(1).log2().mul(Jy).mul(.5)}null!==n&&bT.assign(n).append()}setupPosition(e){const{object:t}=e,n=t.geometry;var i;e.addStack(),(n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&AS(t).append(),!0===t.isSkinnedMesh&&(i=t,Cg(new gS(i,!0))).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&!0===e.isAvailable("instance")&&lS(t).append(),null!==this.positionNode&&$b.assign(this.positionNode);const r=tS();return e.context.vertex=e.removeStack(),e.context.mvp=r,r}setupDiffuseColor({geometry:e}){let t=this.colorNode?Qg(this.colorNode):Sb;!0===this.vertexColors&&e.hasAttribute("color")&&(t=Qg(t.xyz.mul(E_("color","vec3")),t.a)),Z_.assign(t);const n=this.opacityNode?Gg(this.opacityNode):Eb;if(Z_.a.assign(Z_.a.mul(n)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Gg(this.alphaTestNode):bb;Z_.a.lessThanEqual(e).discard()}}setupVariants(){}setupNormal(){if(!0===this.flatShading){const e=Jb.dFdx().cross(Jb.dFdy()).normalize();gb.assign(e.mul(ET))}else{const e=this.normalNode?$g(this.normalNode):Pb;gb.assign(e.mul(ET))}}getEnvNode(e){let t=null;return this.envNode?t=this.envNode:this.envMap?t=this.envMap.isCubeTexture?NS(this.envMap):Ey(this.envMap):e.environmentNode&&(t=e.environmentNode),t}setupLights(e){const t=this.getEnvNode(e),n=[];t&&n.push(new qS(t)),e.material.aoMap&&n.push(new VS(Ey(e.material.aoMap)));let i=this.lightsNode||e.lightsNode;return n.length>0&&(i=FS([...i.lightNodes,...n])),i}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=Z_.rgb;if(s&&!1!==s.hasLight){const t=this.setupLightingModel(e);a=GS(s,t,n,i)}else null!==n&&(a=$g(null!==i?ry(a,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(a=a.add($g(r||Mb))),a}setupOutput(e,t){const n=e.renderer,i=e.toneMappingNode;if(!0===this.toneMapped&&i&&(t=Qg(i.context({color:t.rgb}),t.a)),!0===this.fog){const n=e.fogNode;n&&(t=Qg(n.mixAssign(t.rgb),t.a))}if(!0===this.colorSpaced){const e=n.currentColorSpace;e!==jt&&e!==Wt&&(t=t.linearToColorSpace(e))}return t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}Object.assign(this.defines,e.defines);const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const n=Jr.prototype.toJSON.call(this,e),i=Df(this);n.inputNodes={};for(const{property:t,childNode:r}of i)n.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),s=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.positionNode=e.positionNode,this.depthNode=e.depthNode,this.shadowNode=e.shadowNode,this.outputNode=e.outputNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}static fromMaterial(e){if(!0===e.isNodeMaterial)return e;const t=CT(e.type.replace("Material","NodeMaterial"));if(void 0===t)throw new Error(`NodeMaterial: Material "${e.type}" is not compatible.`);for(const n in e)t[n]=e[n];return t}}function RT(e,t){if("function"!=typeof t||!e)throw new Error(`Node material ${e} is not a class`);AT.has(e)||(AT.set(e,t),t.type=e)}function CT(e){const t=AT.get(e);if(void 0!==t)return new t}RT("NodeMaterial",wT);class NT{constructor(e,t=null){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 PT extends NT{constructor(e,t=0){super(e,t),this.isFloatUniform=!0,this.boundary=4,this.itemSize=1}}class LT extends NT{constructor(e,t=new Jn){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class IT extends NT{constructor(e,t=new Ni){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class UT extends NT{constructor(e,t=new Si){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class OT extends NT{constructor(e,t=new $r){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class DT extends NT{constructor(e,t=new Qn){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class FT extends NT{constructor(e,t=new ar){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class BT extends PT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class VT extends LT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class zT extends IT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class GT extends UT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class kT extends OT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class HT extends DT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class WT extends FT{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class XT extends Wf{constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const n=this.elseNode.getNodeType(e);if(e.getTypeLength(n)>e.getTypeLength(t))return n}return t}generate(e,t){const n=this.getNodeType(e),i={tempWrite:!1},r=e.getDataFromNode(this);if(void 0!==r.nodeProperty)return r.nodeProperty;const{ifNode:s,elseNode:a}=this,o="void"!==t,l=o?Y_(n).build(e):"";r.nodeProperty=l;const c=I_(this.condNode).build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let u=I_(s,i).build(e,n);if(u&&(u=o?l+" = "+u+";":"return "+u+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+u+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=I_(a,i).build(e,n);t&&(t=o?l+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,n,t)}}const jT=Lg(XT);rg("cond",jT),Xf("CondNode",XT);class qT extends Wf{constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}if(e,t){const n=new Rg(t);return this._currentCond=jT(e,n),this.add(this._currentCond)}elseif(e,t){const n=new Rg(t),i=jT(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}else(e){return this._currentCond.elseNode=new Rg(e),this}build(e,...t){const n=Fg();Dg(this);for(const t of this.nodes)t.build(e,"void");return Dg(n),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}}const YT=Lg(qT);Xf("StackNode",qT);class $T extends ra{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Ws(5,5,5),s=HS(Kb),a=CT("MeshBasicNodeMaterial");a.colorNode=Ey(t,s,0),a.side=d,a.blending=0;const o=new ks(r,a),l=new sc;l.add(o),t.minFilter===Me&&(t.minFilter=be);return new na(1,10,this).update(e,l),t.minFilter=n,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}}const ZT=new nf,KT=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),JT=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),QT=e=>(e=Number(e))+(e%1?"":".0");class eM{constructor(e,t,n,i=null,r=null){this.object=e,this.material=r||e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=i,this.nodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.hashNodes={},this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.toneMappingNode=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.bindingsOffset={vertex:0,fragment:0,compute:0},this.bindingsArray=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=YT(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={keywords:new j_,material:this.material},this.cache=new C_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getRenderTarget(e,t,n){return new Ti(e,t,n)}getCubeRenderTarget(e,t){return new $T(e,t)}includes(e){return this.nodes.includes(e)}_getSharedBindings(e){const t=[];for(const n of e)if(!0===n.shared){const e=n.getNodes();let i=ZT.get(e);void 0===i&&(ZT.set(e,n),i=n),t.push(i)}else t.push(n);return t}getBindings(){let e=this.bindingsArray;if(null===e){const t=this.bindings;this.bindingsArray=e=this._getSharedBindings(null!==this.material?[...t.vertex,...t.fragment]:t.compute)}return e}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}buildUpdateNodes(){for(const e of this.nodes){const t=e.getUpdateType(),n=e.getUpdateBeforeType();t!==Cf.NONE&&this.updateNodes.push(e.getSelf()),n!==Cf.NONE&&this.updateBeforeNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}setCache(e){this.cache=e}getCache(){return this.cache}isAvailable(){return!1}getVertexIndex(){}getInstanceIndex(){}getFrontFacing(){}getFragCoord(){}isFlipY(){return!1}generateTexture(){}generateTextureLod(){}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new $r:"vec2"===e?t=new Jn:"vec3"===e?t=new Ni:"vec4"===e&&(t=new Si)),"float"===e)return QT(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${QT(t.r)}, ${QT(t.g)}, ${QT(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}generateMethod(e){return e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new G_(e,t);return n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e}needsColorSpaceToLinear(){return!1}getTextureColorSpaceFromMap(e){let t;return t=e&&e.isTexture?e.colorSpace:e&&e.isWebGLRenderTarget?e.texture.colorSpace:Wt,t}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?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;const n=KT.get(e);return("float"===t?"":t[0])+n}getTypeFromArray(e){return JT.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof fs||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){return this.stack=YT(this.stack),this.stacks.push(Fg()||this.stack),Dg(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Dg(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getNodeData(e);return void 0===i&&(i={},n.setNodeData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e);let i=n.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new G_("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeFromNode(e,t=this.shaderStage){const n=this.getDataFromNode(e,t);if(void 0===n.structType){const i=this.structs.index++;e.name=`StructType${i}`,this.structs[t].push(e),n.structType=e}return e}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new k_(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),r.uniform=s}return s}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage){const r=this.getDataFromNode(e,i);let s=r.variable;if(void 0===s){const e=this.vars[i]||(this.vars[i]=[]);null===t&&(t="nodeVar"+e.length),s=new H_(t,n),e.push(s),r.variable=s}return s}getVaryingFromNode(e,t=null,n=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,s=e.length;null===t&&(t="nodeVarying"+s),r=new W_(t,n),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new X_("nodeCode"+s,t),e.push(r),i.code=r}return r}addLineFlowCode(e){return""===e||(e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}buildFunctionNode(e){const t=new xv,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout;let n;if(e.isArrayInput){n=[];for(const e of t.inputs)n.push(new dv(e.type,e.name))}else{n={};for(const e of t.inputs)n[e.name]=new dv(e.type,e.name)}e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.buildStage,s={code:""};this.flow=s,this.vars={};for(const n of Lf)this.setBuildStage(n),s.result=e.build(this,t);return s.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.setBuildStage(r),s}getFunctionOperator(){return null}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const s=this.flowChildNode(t,n);return null!==i&&(s.code+=`${this.tab+i} = ${s.result};\n`),this.flowCode[e]=this.flowCode[e]+s.code,this.setShaderStage(r),s}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){}getVaryings(){}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){}build(e=!0){const{object:t,material:n}=this;e&&(null!==n?wT.fromMaterial(n).build(this):this.addFlow("compute",t));for(const e of Lf){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of If){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t)return new BT(e);if("vec2"===t)return new VT(e);if("vec3"===t)return new zT(e);if("vec4"===t)return new GT(e);if("color"===t)return new kT(e);if("mat3"===t)return new HT(e);if("mat4"===t)return new WT(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){return CT(e)}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),n):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t[0]!==n[0]&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${e} - NodeMaterial System\n`}}class tM{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.setReference(this);if(t===Cf.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(e)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(e,this.frameId)}else if(t===Cf.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(e)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(e,this.renderId)}else t===Cf.OBJECT&&e.updateBefore(this)}updateNode(e){const t=e.getUpdateType(),n=e.setReference(this);if(t===Cf.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,n);t.get(e)!==this.frameId&&!1!==e.update(this)&&t.set(e,this.frameId)}else if(t===Cf.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,n);t.get(e)!==this.renderId&&!1!==e.update(this)&&t.set(e,this.renderId)}else t===Cf.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 nM{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}nM.isNodeFunctionInput=!0;class iM extends Wf{constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}Xf("StructTypeNode",iM);class rM extends Wf{constructor(...e){super(),this.isOutputStructNode=!0,this.members=e}setup(e){super.setup(e);const t=this.members,n=[];for(let i=0;iKx(Bv(4,e.mul(Fv(1,e))),t),cM=(e,t)=>e.lessThan(.5)?lM(e.mul(2),t).div(2):Fv(1,lM(Bv(Fv(1,e),2),t).div(2)),uM=(e,t,n)=>Kx(Vv(Kx(e,t),Dv(Kx(e,t),Kx(Fv(1,e),n))),1/t),hM=(e,t)=>Tx(ax.mul(t.mul(e).sub(1))).div(ax.mul(t.mul(e).sub(1)));rg("parabola",lM),rg("gain",cM),rg("pcurve",uM),rg("sinc",hM);const dM=Og((([e])=>e.fract().sub(.5).abs())),pM=Og((([e])=>$g(dM(e.z.add(dM(e.y.mul(1)))),dM(e.z.add(dM(e.x.mul(1)))),dM(e.y.add(dM(e.x.mul(1))))))),mM=Og((([e,t,n])=>{const i=$g(e).toVar(),r=Gg(1.4).toVar(),s=Gg(0).toVar(),a=$g(i).toVar();return xS({start:Gg(0),end:Gg(3),type:"float",condition:"<="},(()=>{const e=$g(pM(a.mul(2))).toVar();i.addAssign(e.add(n.mul(Gg(.1).mul(t)))),a.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const o=Gg(dM(i.z.add(dM(i.x.add(dM(i.y)))))).toVar();s.addAssign(o.div(r)),a.addAssign(.14)})),s}));let fM;dM.setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),pM.setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),mM.setLayout({name:"triNoise3D",type:"float",inputs:[{name:"p",type:"vec3"},{name:"spd",type:"float"},{name:"time",type:"float"}]});class gM extends XT{constructor(e){fM=fM||by("discard"),super(e,fM)}}const _M=Lg(gM),vM=e=>_M(e).append();rg("discard",vM),Xf("DiscardNode",gM);class xM extends Wf{constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let n=this._candidateFnCall;if(null===n){let i=null,r=-1;for(const n of this.functionNodes){const s=n.shaderNode.layout;if(null===s)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=s.inputs;if(t.length===a.length){let s=0;for(let n=0;nr&&(i=n,r=s)}}this._candidateFnCall=n=i(...t)}return n}}const yM=Lg(xM),bM=e=>(...t)=>yM(e,...t);Xf("FunctionOverloadingNode",xM);class SM extends qf{constructor(){super("vec2")}setup(){const e=$g(Qb.z,0,Qb.x.negate()).normalize(),t=Qb.cross(e);return Xg(e.dot(gb),t.dot(gb)).mul(.495).add(.5)}}const TM=Ig(SM);Xf("MatcapUVNode",SM);class MM extends Cv{constructor(e=MM.LOCAL,t=1,n=0){super(n),this.scope=e,this.scale=t,this.updateType=Cf.FRAME}update(e){const t=this.scope,n=this.scale;t===MM.LOCAL?this.value+=e.deltaTime*n:t===MM.DELTA?this.value=e.deltaTime*n:t===MM.FRAME?this.value=e.frameId:this.value=e.time*n}serialize(e){super.serialize(e),e.scope=this.scope,e.scale=this.scale}deserialize(e){super.deserialize(e),this.scope=e.scope,this.scale=e.scale}}MM.LOCAL="local",MM.GLOBAL="global",MM.DELTA="delta",MM.FRAME="frame";const EM=(e,t=0)=>Cg(new MM(MM.LOCAL,e,t)),AM=(e,t=0)=>Cg(new MM(MM.GLOBAL,e,t)),wM=(e,t=0)=>Cg(new MM(MM.DELTA,e,t)),RM=Ig(MM,MM.FRAME).uint();Xf("TimerNode",MM);class CM extends Wf{constructor(e=CM.SINE,t=EM()){super(),this.method=e,this.timeNode=t}getNodeType(e){return this.timeNode.getNodeType(e)}setup(){const e=this.method,t=Cg(this.timeNode);let n=null;return e===CM.SINE?n=t.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5):e===CM.SQUARE?n=t.fract().round():e===CM.TRIANGLE?n=t.add(.5).fract().mul(2).sub(1).abs():e===CM.SAWTOOTH&&(n=t.fract()),n}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}CM.SINE="sine",CM.SQUARE="square",CM.TRIANGLE="triangle",CM.SAWTOOTH="sawtooth";const NM=Lg(CM,CM.SINE),PM=Lg(CM,CM.SQUARE),LM=Lg(CM,CM.TRIANGLE),IM=Lg(CM,CM.SAWTOOTH);Xf("OscNode",CM);class UM extends qf{constructor(e,t){super(),this.scope=e,this.node=t}getNodeType(e){return this.node.getNodeType(e)}setup(){const{scope:e,node:t}=this;let n=null;return e===UM.DIRECTION_TO_COLOR?n=t.mul(.5).add(.5):e===UM.COLOR_TO_DIRECTION&&(n=t.mul(2).sub(1)),n}}UM.DIRECTION_TO_COLOR="directionToColor",UM.COLOR_TO_DIRECTION="colorToDirection";const OM=Lg(UM,UM.DIRECTION_TO_COLOR),DM=Lg(UM,UM.COLOR_TO_DIRECTION);rg("directionToColor",OM),rg("colorToDirection",DM),Xf("PackingNode",UM);class FM extends Wf{constructor(e,t,n,i=Gg(0),r=Gg(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:i,outHighNode:r,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const BM=Lg(FM,null,null,{doClamp:!1}),VM=Lg(FM);rg("remap",BM),rg("remapClamp",VM),Xf("RemapNode",FM);class zM extends qf{constructor(e,t,n=Xg(.5)){super("vec2"),this.uvNode=e,this.rotationNode=t,this.centerNode=n}setup(){const{uvNode:e,rotationNode:t,centerNode:n}=this;return e.sub(n).rotate(t).add(n)}}const GM=Lg(zM);rg("rotateUV",GM),Xf("RotateUVNode",zM);class kM extends qf{constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return i_(e,i,i.negate(),e).mul(n)}{const e=t,i=h_(Qg(1,0,0,0),Qg(0,Mx(e.x),Tx(e.x).negate(),0),Qg(0,Tx(e.x),Mx(e.x),0),Qg(0,0,0,1)),r=h_(Qg(Mx(e.y),0,Tx(e.y),0),Qg(0,1,0,0),Qg(Tx(e.y).negate(),0,Mx(e.y),0),Qg(0,0,0,1)),s=h_(Qg(Mx(e.z),Tx(e.z).negate(),0,0),Qg(Tx(e.z),Mx(e.z),0,0),Qg(0,0,1,0),Qg(0,0,0,1));return i.mul(r).mul(s).mul(Qg(n,1)).xyz}}}const HM=Lg(kM);rg("rotate",HM),Xf("RotateNode",kM);class WM extends Wf{constructor(e,t=Lv(),n=Gg(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=n}setup(){const{frameNode:e,uvNode:t,countNode:n}=this,{width:i,height:r}=n,s=e.mod(i.mul(r)).floor(),a=s.mod(i),o=r.sub(s.add(1).div(i).ceil()),l=n.reciprocal(),c=Xg(a,o);return t.add(c).mul(l)}}const XM=Lg(WM);Xf("SpriteSheetUVNode",WM);class jM extends Yf{constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}setup(e){return!1===e.isAvailable("storageBuffer")&&(this.node.instanceIndex||!0!==this.node.bufferObject||e.setupPBO(this.node)),super.setup(e)}generate(e,t){let n;const i=e.context.assign;if(!1===e.isAvailable("storageBuffer")){const{node:t}=this;n=t.instanceIndex||!0!==this.node.bufferObject||!0===i?t.build(e):e.generatePBO(this)}else n=super.generate(e);if(!0!==i){const i=this.getNodeType(e);n=e.format(n,i,t)}return n}}const qM=Lg(jM);rg("storageElement",qM),Xf("StorageArrayElementNode",jM);class YM extends Wf{constructor(e,t=null,n=null,i=Gg(1),r=$b,s=pb){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=n,this.scaleNode=i,this.positionNode=r,this.normalNode=s}setup(){const{textureXNode:e,textureYNode:t,textureZNode:n,scaleNode:i,positionNode:r,normalNode:s}=this;let a=s.abs().normalize();a=a.div(a.dot($g(1)));const o=r.yz.mul(i),l=r.zx.mul(i),c=r.xy.mul(i),u=e.value,h=null!==t?t.value:u,d=null!==n?n.value:u,p=Ey(u,o).mul(a.x),m=Ey(h,l).mul(a.y),f=Ey(d,c).mul(a.z);return Dv(p,m,f)}}const $M=Lg(YM),ZM=(...e)=>$M(...e);rg("triplanarTexture",ZM),Xf("TriplanarTexturesNode",YM);const KM=new la,JM=new Ni,QM=new Ni,eE=new Ni,tE=new ar,nE=new Ni(0,0,-1),iE=new Si,rE=new Ni,sE=new Ni,aE=new Si,oE=new Jn,lE=new Ti,cE=Xg(nT.x.oneMinus(),nT.y);let uE=!1;class hE extends My{constructor(e={}){super(lE.texture,cE);const{target:t=new Ir,resolution:n=1,generateMipmaps:i=!1,bounces:r=!0}=e;this.target=t,this.resolution=n,this.generateMipmaps=i,this.bounces=r,this.updateBeforeType=r?Cf.RENDER:Cf.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new WeakMap}_updateResolution(e,t){const n=this.resolution;t.getDrawingBufferSize(oE),e.setSize(Math.round(oE.width*n),Math.round(oE.height*n))}setup(e){return this._updateResolution(lE,e.renderer),super.setup(e)}getTextureNode(){return this.textureNode}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 Ti(0,0,{type:Ie}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&uE)return!1;uE=!0;const{scene:t,camera:n,renderer:i,material:r}=e,{target:s}=this,a=this.getVirtualCamera(n),o=this.getRenderTarget(a);if(i.getDrawingBufferSize(oE),this._updateResolution(o,i),QM.setFromMatrixPosition(s.matrixWorld),eE.setFromMatrixPosition(n.matrixWorld),tE.extractRotation(s.matrixWorld),JM.set(0,0,1),JM.applyMatrix4(tE),rE.subVectors(QM,eE),rE.dot(JM)>0)return;rE.reflect(JM).negate(),rE.add(QM),tE.extractRotation(n.matrixWorld),nE.set(0,0,-1),nE.applyMatrix4(tE),nE.add(eE),sE.subVectors(QM,nE),sE.reflect(JM).negate(),sE.add(QM),a.coordinateSystem=n.coordinateSystem,a.position.copy(rE),a.up.set(0,1,0),a.up.applyMatrix4(tE),a.up.reflect(JM),a.lookAt(sE),a.near=n.near,a.far=n.far,a.updateMatrixWorld(),a.projectionMatrix.copy(n.projectionMatrix),KM.setFromNormalAndCoplanarPoint(JM,QM),KM.applyMatrix4(a.matrixWorldInverse),iE.set(KM.normal.x,KM.normal.y,KM.normal.z,KM.constant);const l=a.projectionMatrix;aE.x=(Math.sign(iE.x)+l.elements[8])/l.elements[0],aE.y=(Math.sign(iE.y)+l.elements[9])/l.elements[5],aE.z=-1,aE.w=(1+l.elements[10])/l.elements[14],iE.multiplyScalar(1/iE.dot(aE));l.elements[2]=iE.x,l.elements[6]=iE.y,l.elements[10]=iE.z-0,l.elements[14]=iE.w,this.value=o.texture,r.visible=!1;const c=i.getRenderTarget();i.setRenderTarget(o),i.render(t,a),i.setRenderTarget(c),r.visible=!0,uE=!1}}const dE=e=>Cg(new hE(e));class pE extends Wf{constructor(e=pE.LOCAL){super("vec3"),this.scope=e}getHash(){return`bitangent-${this.scope}`}generate(e){const t=this.scope;let n;t===pE.GEOMETRY?n=db.cross(uS):t===pE.LOCAL?n=pb.cross(hS):t===pE.VIEW?n=mb.cross(dS):t===pE.WORLD&&(n=fb.cross(pS));const i=n.mul(uS.w).xyz;return bx(T_(i)).build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}pE.GEOMETRY="geometry",pE.LOCAL="local",pE.VIEW="view",pE.WORLD="world";const mE=Ig(pE,pE.GEOMETRY),fE=Ig(pE,pE.LOCAL),gE=Ig(pE,pE.VIEW),_E=Ig(pE,pE.WORLD),vE=bx(gb.cross(mS).mul(uS.w)),xE=bx(vE.transformDirection(Qy));Xf("BitangentNode",pE);const yE=o_(dS,gE,mb),bE=Qb.mul(yE),SE=(e,t)=>e.sub(bE.mul(t));class TE extends M_{constructor(e=0){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Si(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const ME=(...e)=>Cg(new TE(...e));Xf("VertexColorNode",TE);const EE=1/6,AE=e=>Bv(EE,Bv(e,Bv(e,e.negate().add(3)).sub(3)).add(1)),wE=e=>Bv(EE,Bv(e,Bv(e,Bv(3,e).sub(6))).add(4)),RE=e=>Bv(EE,Bv(e,Bv(e,Bv(-3,e).add(3)).add(3)).add(1)),CE=e=>Bv(EE,Kx(e,3)),NE=e=>AE(e).add(wE(e)),PE=e=>RE(e).add(CE(e)),LE=e=>Dv(-1,wE(e).div(AE(e).add(wE(e)))),IE=e=>Dv(1,CE(e).div(RE(e).add(CE(e)))),UE=(e,t,n)=>{const i=e.uvNode,r=Bv(i,t.zw).add(.5),s=xx(r),a=Sx(r),o=NE(a.x),l=PE(a.x),c=LE(a.x),u=IE(a.x),h=LE(a.y),d=IE(a.y),p=Xg(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=Xg(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=Xg(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),g=Xg(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),_=NE(a.y).mul(Dv(o.mul(e.uv(p).level(n)),l.mul(e.uv(m).level(n)))),v=PE(a.y).mul(Dv(o.mul(e.uv(f).level(n)),l.mul(e.uv(g).level(n))));return _.add(v)};class OE extends qf{constructor(e,t=Gg(3)){super("vec4"),this.textureNode=e,this.blurNode=t}setup(){return((e,t)=>{const n=Xg(e.size(kg(t))),i=Xg(e.size(kg(t.add(1)))),r=Vv(1,n),s=Vv(1,i),a=UE(e,Qg(r,n),xx(t)),o=UE(e,Qg(s,i),yx(t));return Sx(t).mix(a,o)})(this.textureNode,this.blurNode)}}const DE=Lg(OE);rg("bicubic",DE),Xf("TextureBicubicNode",OE);class FE extends Wf{constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const BE=Ig(FE);Xf("PointUVNode",FE);class VE extends Wf{constructor(e=VE.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=null!==this.scene?this.scene:e.scene;let i;return t===VE.BACKGROUND_BLURRINESS?i=Oy("backgroundBlurriness","float",n):t===VE.BACKGROUND_INTENSITY&&(i=Oy("backgroundIntensity","float",n)),i}}VE.BACKGROUND_BLURRINESS="backgroundBlurriness",VE.BACKGROUND_INTENSITY="backgroundIntensity";const zE=Ig(VE,VE.BACKGROUND_BLURRINESS),GE=Ig(VE,VE.BACKGROUND_INTENSITY);Xf("SceneNode",VE);class kE extends Ry{constructor(e,t,n=0){super(e,t,n),this.isStorageBufferNode=!0,this.bufferObject=!1,this._attribute=null,this._varying=null}getInputType(){return"storageBuffer"}element(e){return qM(this,e)}setBufferObject(e){return this.bufferObject=e,this}generate(e){if(e.isAvailable("storageBuffer"))return super.generate(e);const t=this.getNodeType(e);null===this._attribute&&(this._attribute=iS(this.value),this._varying=T_(this._attribute));const n=this._varying.build(e,t);return e.registerTransform(n,this._attribute),n}}const HE=(e,t,n)=>Cg(new kE(e,t,n)),WE=(e,t,n)=>Cg(new kE(e,t,n).setBufferObject(!0));Xf("StorageBufferNode",kE);class XE extends My{constructor(e,t,n=null){super(e,t),this.storeNode=n,this.isStoreTextureNode=!0}getInputType(){return"storageTexture"}setup(e){super.setup(e);e.getNodeProperties(this).storeNode=this.storeNode}generate(e,t){let n;return n=null!==this.storeNode?this.generateStore(e):super.generate(e,t),n}generateStore(e){const t=e.getNodeProperties(this),{uvNode:n,storeNode:i}=t,r=super.generate(e,"property"),s=n.build(e,"uvec2"),a=i.build(e,"vec4"),o=e.generateTextureStore(e,r,s,a);e.addLineFlowCode(o)}}const jE=Lg(XE),qE=(e,t,n)=>{const i=jE(e,t,n);return null!==n&&i.append(),i};Xf("TextureStoreNode",XE);class YE extends Uy{constructor(e,t,n=null){super(e,t,n),this.userData=n}update(e){this.reference=null!==this.userData?this.userData:e.object.userData,super.update(e)}}const $E=(e,t,n)=>Cg(new YE(e,t,n));Xf("UserDataNode",YE);const ZE=Og((({base:e,blend:t})=>{const n=n=>t[n].lessThan(rx).cond(t[n],e[n].oneMinus().div(t[n]).oneMinus().max(0));return $g(n("x"),n("y"),n("z"))})).setLayout({name:"burnColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),KE=Og((({base:e,blend:t})=>{const n=n=>t[n].equal(1).cond(t[n],e[n].div(t[n].oneMinus()).max(0));return $g(n("x"),n("y"),n("z"))})).setLayout({name:"dodgeColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),JE=Og((({base:e,blend:t})=>{const n=n=>e[n].oneMinus().mul(t[n].oneMinus()).oneMinus();return $g(n("x"),n("y"),n("z"))})).setLayout({name:"screenColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),QE=Og((({base:e,blend:t})=>{const n=n=>e[n].lessThan(.5).cond(e[n].mul(t[n],2),e[n].oneMinus().mul(t[n].oneMinus()).oneMinus());return $g(n("x"),n("y"),n("z"))})).setLayout({name:"overlayColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]});class eA extends qf{constructor(e,t,n){super(),this.blendMode=e,this.baseNode=t,this.blendNode=n}setup(){const{blendMode:e,baseNode:t,blendNode:n}=this,i={base:t,blend:n};let r=null;return e===eA.BURN?r=ZE(i):e===eA.DODGE?r=KE(i):e===eA.SCREEN?r=JE(i):e===eA.OVERLAY&&(r=QE(i)),r}}eA.BURN="burn",eA.DODGE="dodge",eA.SCREEN="screen",eA.OVERLAY="overlay";const tA=Lg(eA,eA.BURN),nA=Lg(eA,eA.DODGE),iA=Lg(eA,eA.OVERLAY),rA=Lg(eA,eA.SCREEN);rg("burn",tA),rg("dodge",nA),rg("overlay",iA),rg("screen",rA),Xf("BlendModeNode",eA);const sA=Og((({textureNode:e,bumpScale:t})=>{let n=e;if(!0!==n.isTextureNode&&n.traverse((e=>{!0===e.isTextureNode&&(n=e)})),!0!==n.isTextureNode)throw new Error("THREE.TSL: dHdxy_fwd() requires a TextureNode.");const i=Gg(e),r=n.uvNode||Lv(),s=t=>e.cache().context({getUV:()=>t,forceUVContext:!0});return Xg(Gg(s(r.add(r.dFdx()))).sub(i),Gg(s(r.add(r.dFdy()))).sub(i)).mul(t)})),aA=Og((e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(ET),c=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(c).normalize()}));class oA extends qf{constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=sA({textureNode:this.textureNode,bumpScale:e});return aA({surf_pos:Jb,surf_norm:mb,dHdxy:t})}}const lA=Lg(oA);rg("bumpMap",lA),Xf("BumpMapNode",oA);const cA=Og((({color:e,adjustment:t})=>t.mix(_A(e.rgb),e.rgb))),uA=Og((({color:e,adjustment:t})=>{const n=Dv(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(n).mul(t).mul(-3);return ry(e.rgb,i,r)})),hA=Og((({color:e,adjustment:t})=>{const n=$g(.57735,.57735,.57735),i=t.cos();return $g(e.rgb.mul(i).add(n.cross(e.rgb).mul(t.sin()).add(n.mul($x(n,e.rgb).mul(i.oneMinus())))))}));class dA extends qf{constructor(e,t,n=Gg(1)){super("vec3"),this.method=e,this.colorNode=t,this.adjustmentNode=n}setup(){const{method:e,colorNode:t,adjustmentNode:n}=this,i={color:t,adjustment:n};let r=null;return e===dA.SATURATION?r=cA(i):e===dA.VIBRANCE?r=uA(i):e===dA.HUE&&(r=hA(i)),r}}dA.SATURATION="saturation",dA.VIBRANCE="vibrance",dA.HUE="hue";const pA=Lg(dA,dA.SATURATION),mA=Lg(dA,dA.VIBRANCE),fA=Lg(dA,dA.HUE),gA=$g(.2125,.7154,.0721),_A=(e,t=gA)=>$x(e,t),vA=(e,t)=>ry($g(0),e,_A(e).sub(t).max(0));rg("saturation",pA),rg("vibrance",mA),rg("hue",fA),rg("threshold",vA),Xf("ColorAdjustmentNode",dA);const xA=Og((e=>{const{eye_pos:t,surf_norm:n,mapN:i,uv:r}=e,s=t.dFdx(),a=t.dFdy(),o=r.dFdx(),l=r.dFdy(),c=n,u=a.cross(c),h=c.cross(s),d=u.mul(o.x).add(h.mul(l.x)),p=u.mul(o.y).add(h.mul(l.y)),m=d.dot(d).max(p.dot(p)),f=ET.mul(m.inverseSqrt());return Dv(d.mul(i.x,f),p.mul(i.y,f),c.mul(i.z)).normalize()}));class yA extends qf{constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:n}=this;let i=this.node.mul(2).sub(1);null!==n&&(i=$g(i.xy.mul(n),i.z));let r=null;if(1===t)r=ab.mul(i).normalize();else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?yE.mul(i).normalize():xA({eye_pos:Jb,surf_norm:mb,mapN:i,uv:Lv()})}return r}}const bA=Lg(yA);rg("normalMap",bA),Xf("NormalMapNode",yA);class SA extends qf{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 TA=Lg(SA);rg("posterize",TA),Xf("PosterizeNode",SA);const MA=Og((({color:e,exposure:t})=>e.mul(t).clamp())),EA=Og((({color:e,exposure:t})=>(e=e.mul(t)).div(e.add(1)).clamp())),AA=Og((({color:e,exposure:t})=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(i).pow(2.2)})),wA=Og((({color:e})=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)})),RA=Og((({color:e,exposure:t})=>{const n=o_(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=o_(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=wA({color:e}),(e=i.mul(e)).clamp()})),CA=o_($g(1.6605,-.1246,-.0182),$g(-.5876,1.1329,-.1006),$g(-.0728,-.0083,1.1187)),NA=o_($g(.6274,.0691,.0164),$g(.3293,.9195,.088),$g(.0433,.0113,.8956)),PA=Og((([e])=>{const t=$g(e).toVar(),n=$g(t.mul(t)).toVar(),i=$g(n.mul(n)).toVar();return Gg(15.5).mul(i.mul(n)).sub(Bv(40.14,i.mul(t))).add(Bv(31.96,i).sub(Bv(6.868,n.mul(t))).add(Bv(.4298,n).add(Bv(.1191,t).sub(.00232))))})),LA=Og((({color:e,exposure:t})=>{const n=$g(e).toVar(),i=o_($g(.856627153315983,.137318972929847,.11189821299995),$g(.0951212405381588,.761241990602591,.0767994186031903),$g(.0482516061458583,.101439036467562,.811302368396859)),r=o_($g(1.1271005818144368,-.1413297634984383,-.14132976349843826),$g(-.11060664309660323,1.157823702216272,-.11060664309660294),$g(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=Gg(-12.47393),a=Gg(4.026069);return n.mulAssign(t),n.assign(NA.mul(n)),n.assign(i.mul(n)),n.assign(Hx(n,1e-10)),n.assign(gx(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(sy(n,0,1)),n.assign(PA(n)),n.assign(r.mul(n)),n.assign(Kx(Hx($g(0),n),$g(2.2))),n.assign(CA.mul(n)),n.assign(sy(n,0,1)),n})),IA={[J]:MA,[Q]:EA,[ee]:AA,[te]:RA,[ie]:LA};class UA extends qf{constructor(e=K,t=Gg(1),n=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=n}getCacheKey(){let e=super.getCacheKey();return e="{toneMapping:"+this.toneMapping+",nodes:"+e+"}",e}setup(e){const t=this.colorNode||e.context.color,n=this.toneMapping;if(n===K)return t;const i={exposure:this.exposureNode,color:t},r=IA[n];let s=null;return s=r?r(i):t,s}}const OA=(e,t,n)=>Cg(new UA(e,Cg(t),Cg(n)));Xf("ToneMappingNode",UA);let DA=null;class FA extends oT{constructor(e=nT,t=null){null===DA&&(DA=new Uu),super(e,t,DA)}}const BA=Lg(FA);rg("viewportSharedTexture",BA),Xf("ViewportSharedTextureNode",FA);class VA extends My{constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class zA extends qf{constructor(e,t,n){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this._pixelRatio=1,this._width=1,this._height=1;const i=new Qa;i.isRenderTargetTexture=!0,i.name="PostProcessingDepth";const r=new Ti(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Ie});r.texture.name="PostProcessing",r.depthTexture=i,this.renderTarget=r,this.updateBeforeType=Cf.FRAME,this._textureNode=Cg(new VA(this,r.texture)),this._depthTextureNode=Cg(new VA(this,i)),this._depthNode=null,this._cameraNear=Nv(0),this._cameraFar=Nv(0),this.isPassNode=!0}isGlobal(){return!0}getTextureNode(){return this._textureNode}getTextureDepthNode(){return this._depthTextureNode}getDepthNode(){if(null===this._depthNode){const e=this._cameraNear,t=this._cameraFar;this._depthNode=mT(_T(this._depthTextureNode,e,t),e,t)}return this._depthNode}setup(){return this.scope===zA.COLOR?this.getTextureNode():this.getDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n,camera:i}=this;this._pixelRatio=t.getPixelRatio();const r=t.getSize(new Jn);this.setSize(r.width,r.height);const s=t.toneMapping,a=t.toneMappingNode,o=t.getRenderTarget();this._cameraNear.value=i.near,this._cameraFar.value=i.far,t.toneMapping=K,t.toneMappingNode=null,t.setRenderTarget(this.renderTarget),t.render(n,i),t.toneMapping=s,t.toneMappingNode=a,t.setRenderTarget(o)}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget.setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}zA.COLOR="color",zA.DEPTH="depth";const GA=(e,t)=>Cg(new zA(zA.COLOR,e,t)),kA=(e,t)=>Cg(new VA(e,t)),HA=(e,t)=>Cg(new zA(zA.DEPTH,e,t));Xf("PassNode",zA);const WA=new wa(-1,1,1,-1,0,1);const XA=new class extends Ms{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new gs([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new gs(t,2))}};class jA{constructor(e=null){this._mesh=new ks(XA,e)}dispose(){this._mesh.geometry.dispose()}async renderAsync(e){await e.renderAsync(this._mesh,WA)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}get render(){return this.renderAsync}}const qA=new jA,YA=new jA;class $A extends qf{constructor(e,t=2){super("vec4"),this.textureNode=e,this.sigma=t,this.directionNode=Xg(1),this._invSize=Nv(new Jn),this._passDirection=Nv(new Jn),this._horizontalRT=new Ti,this._horizontalRT.texture.name="GaussianBlurNode.horizontal",this._verticalRT=new Ti,this._verticalRT.texture.name="GaussianBlurNode.vertical",this._textureNode=kA(this,this._verticalRT.texture),this.updateBeforeType=Cf.RENDER,this.resolution=new Jn(1,1)}setSize(e,t){e=Math.max(Math.round(e*this.resolution.x),1),t=Math.max(Math.round(t*this.resolution.y),1),this._invSize.value.set(1/e,1/t),this._horizontalRT.setSize(e,t),this._verticalRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,n=this.textureNode,i=n.value,r=t.getRenderTarget(),s=n.value;qA.material=this._material,YA.material=this._material,this.setSize(i.image.width,i.image.height);const a=i.type;this._horizontalRT.texture.type=a,this._verticalRT.texture.type=a,t.setRenderTarget(this._horizontalRT),this._passDirection.value.set(1,0),qA.render(t),n.value=this._horizontalRT.texture,t.setRenderTarget(this._verticalRT),this._passDirection.value.set(0,1),YA.render(t),t.setRenderTarget(r),n.value=s}getTextureNode(){return this._textureNode}setup(e){const t=this.textureNode;if(!0!==t.isTextureNode)return Qg();const n=t.uvNode||Lv(),i=e=>t.cache().context({getUV:()=>e,forceUVContext:!0}),r=Og((()=>{const e=3+2*this.sigma,t=this._getCoefficients(e),r=this._invSize,s=Xg(this.directionNode).mul(this._passDirection),a=Gg(t[0]).toVar(),o=Qg(i(n).mul(a)).toVar();for(let l=1;lCg(new $A(Cg(e),t));rg("gaussianBlur",ZA);const KA=new jA;class JA extends qf{constructor(e,t=.96){super(e),this.textureNode=e,this.textureNodeOld=Ey(),this.damp=Nv(t),this._compRT=new Ti,this._compRT.texture.name="AfterImageNode.comp",this._oldRT=new Ti,this._oldRT.texture.name="AfterImageNode.old",this._textureNode=kA(this,this._compRT.texture),this.updateBeforeType=Cf.RENDER}getTextureNode(){return this._textureNode}setSize(e,t){this._compRT.setSize(e,t),this._oldRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,n=this.textureNode,i=n.value,r=i.type;this._compRT.texture.type=r,this._oldRT.texture.type=r;const s=t.getRenderTarget(),a=n.value;this.textureNodeOld.value=this._oldRT.texture,t.setRenderTarget(this._compRT),KA.render(t);const o=this._oldRT;this._oldRT=this._compRT,this._compRT=o,this.setSize(i.image.width,i.image.height),t.setRenderTarget(s),n.value=a}setup(e){const t=this.textureNode,n=this.textureNodeOld;if(!0!==t.isTextureNode)return Qg();const i=t.uvNode||Lv();n.uvNode=i;const r=Og((([e,t])=>{const n=Gg(t).toVar(),i=Qg(e).toVar();return Hx(Nx(i.sub(n)),0)})),s=Og((()=>{const e=Qg(n),s=Qg((e=>t.cache().context({getUV:()=>e,forceUVContext:!0}))(i));return e.mulAssign(this.damp.mul(r(e,.1))),Hx(s,e)})),a=this._materialComposed||(this._materialComposed=e.createNodeMaterial());a.fragmentNode=s(),KA.material=a;return e.getNodeProperties(this).textureNode=t,this._textureNode}}const QA=(e,t)=>Cg(new JA(Cg(e),t));rg("afterImage",QA);const ew=new jA;class tw extends qf{constructor(e,t,n,i){super("vec4"),this.textureNode=e,this.tresholdNode=t,this.scaleNode=n,this.colorNode=$g(.1,0,1),this.samples=i,this.resolution=new Jn(1,1),this._renderTarget=new Ti,this._renderTarget.texture.name="anamorphic",this._invSize=Nv(new Jn),this._textureNode=kA(this,this._renderTarget.texture),this.updateBeforeType=Cf.RENDER}getTextureNode(){return this._textureNode}setSize(e,t){this._invSize.value.set(1/e,1/t),e=Math.max(Math.round(e*this.resolution.x),1),t=Math.max(Math.round(t*this.resolution.y),1),this._renderTarget.setSize(e,t)}updateBefore(e){const{renderer:t}=e,n=this.textureNode,i=n.value;this._renderTarget.texture.type=i.type;const r=t.getRenderTarget(),s=n.value;ew.material=this._material,this.setSize(i.image.width,i.image.height),t.setRenderTarget(this._renderTarget),ew.render(t),t.setRenderTarget(r),n.value=s}setup(e){const t=this.textureNode;if(!0!==t.isTextureNode)return Qg();const n=t.uvNode||Lv(),i=Og((()=>{const e=this.samples,i=Math.floor(e/2),r=$g(0).toVar();return xS({start:-i,end:i},(({i:e})=>{const s=Gg(e).abs().div(i).oneMinus(),a=(e=>t.cache().context({getUV:()=>e,forceUVContext:!0}))(Xg(n.x.add(this._invSize.x.mul(e).mul(this.scaleNode)),n.y)),o=vA(a,this.tresholdNode).mul(s);r.addAssign(o)})),r.mul(this.colorNode)}));(this._material||(this._material=e.createNodeMaterial())).fragmentNode=i();return e.getNodeProperties(this).textureNode=t,this._textureNode}}const nw=(e,t=.9,n=3,i=32)=>Cg(new tw(Cg(e),Cg(t),Cg(n),i));rg("anamorphic",nw);class iw extends qf{constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],n=this.functionNode,i=n.getInputs(e),r=this.parameters;if(Array.isArray(r))for(let n=0;n(t=t.length>1||t[0]&&!0===t[0].isNode?Pg(t):Ng(t[0]),Cg(new iw(Cg(e),t)));rg("call",rw),Xf("FunctionCallNode",iw);class sw extends Wf{constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new Bn,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:Gg()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Vf(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?zf(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 aw=Lg(sw);rg("scriptableValue",aw),Xf("ScriptableValueNode",sw);class ow extends Map{get(e,t=null,...n){if(this.has(e))return super.get(e);if(null!==t){const i=t(...n);return this.set(e,i),i}}}class lw{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 cw=new ow;class uw extends Wf{constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new ow,this._output=aw(),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 n=this._outputs;return void 0===n[e]?n[e]=aw(t):n[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const n=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),n[e]=t,n[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),n[e]=t,n[e].events.addEventListener("refresh",this.onRefresh)):void 0===n[e]?(n[e]=aw(t),n[e].events.addEventListener("refresh",this.onRefresh)):n[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 n=this.getObject()[e];if("function"==typeof n)return n(...t)}async callAsync(e,...t){const n=this.getObject()[e];if("function"==typeof n)return"AsyncFunction"===n.constructor.name?await n(...t):n(...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 lw(this),t=cw.get("THREE"),n=cw.get("TSL"),i=this.getMethod(this.codeNode),r=[e,this._local,cw,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,n];this._object=i(...r);const s=this._object.layout;if(s&&(!1===s.cache&&this._local.clear(),this._output.outputType=s.outputType||null,Array.isArray(s.elements)))for(const e of s.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:Gg()}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+" };",n="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],n),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()}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 hw=Lg(uw);rg("scriptable",hw),Xf("ScriptableNode",uw);class dw extends Wf{constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}mixAssign(e){return ry(e,this.colorNode,this)}setup(){return this.factorNode}}const pw=Lg(dw);rg("fog",pw),Xf("FogNode",dw);class mw extends dw{constructor(e,t,n){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=n}setup(){return ly(this.nearNode,this.farNode,Jb.z.negate())}}const fw=Lg(mw);rg("rangeFog",fw),Xf("FogRangeNode",mw);class gw extends dw{constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(){const e=Jb.z.negate(),t=this.densityNode;return t.mul(t,e,e).negate().exp().oneMinus()}}const _w=Lg(gw);rg("densityFog",_w),Xf("FogExp2Node",gw);let vw=null,xw=null;class yw extends Wf{constructor(e=Gg(),t=Gg()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Ff(this.minNode.value)),n=e.getTypeLength(Ff(this.maxNode.value));return t>n?t:n}getNodeType(e){return!0===e.object.isInstancedMesh?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let n=null;if(!0===t.isInstancedMesh){const i=this.minNode.value,r=this.maxNode.value,s=e.getTypeLength(Ff(i)),a=e.getTypeLength(Ff(r));vw=vw||new Si,xw=xw||new Si,vw.setScalar(0),xw.setScalar(0),1===s?vw.setScalar(i):i.isColor?vw.set(i.r,i.g,i.b):vw.set(i.x,i.y,i.z||0,i.w||0),1===a?xw.setScalar(r):r.isColor?xw.set(r.r,r.g,r.b):xw.set(r.x,r.y,r.z||0,r.w||0);const o=4,l=o*t.count,c=new Float32Array(l);for(let e=0;eCg(new Sw(Cg(e),t,n));rg("compute",Tw),Xf("ComputeNode",Sw);class Mw extends Wf{constructor(e=Mw.TARGET_DIRECTION,t=null){super(),this.scope=e,this.light=t}setup(){const{scope:e,light:t}=this;let n=null;return e===Mw.TARGET_DIRECTION&&(n=Qy.transformDirection(Wy(t).sub(Wy(t.target)))),n}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Mw.TARGET_DIRECTION="targetDirection";const Ew=Lg(Mw,Mw.TARGET_DIRECTION);Xf("LightNode",Mw);const Aw=Og((e=>{const{lightDistance:t,cutoffDistance:n,decayExponent:i}=e,r=t.pow(i).max(.01).reciprocal();return n.greaterThan(0).cond(r.mul(t.div(n).pow4().oneMinus().clamp().pow2()),r)}));class ww extends IS{constructor(e=null){super(e),this.cutoffDistanceNode=Nv(0),this.decayExponentNode=Nv(0)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=e.context.lightingModel,a=jy(r).sub(Jb),o=a.normalize(),l=a.length(),c=Aw({lightDistance:l,cutoffDistance:n,decayExponent:i}),u=t.mul(c),h=e.context.reflectedLight;s.direct({lightDirection:o,lightColor:u,reflectedLight:h},e.stack,e)}}Xf("PointLightNode",ww),BS(cp,ww);class Rw extends IS{constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,n=this.colorNode,i=Ew(this.light),r=e.context.reflectedLight;t.direct({lightDirection:i,lightColor:n,reflectedLight:r},e.stack,e)}}Xf("DirectionalLightNode",Rw),BS(hp,Rw);class Cw extends IS{constructor(e=null){super(e),this.coneCosNode=Nv(0),this.penumbraCosNode=Nv(0),this.cutoffDistanceNode=Nv(0),this.decayExponentNode=Nv(0)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e){const{coneCosNode:t,penumbraCosNode:n}=this;return ly(t,n,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:n,cutoffDistanceNode:i,decayExponentNode:r,light:s}=this,a=jy(s).sub(Jb),o=a.normalize(),l=o.dot(Ew(s)),c=this.getSpotAttenuation(l),u=a.length(),h=Aw({lightDistance:u,cutoffDistance:i,decayExponent:r}),d=n.mul(c).mul(h),p=e.context.reflectedLight;t.direct({lightDirection:o,lightColor:d,reflectedLight:p},e.stack,e)}}Xf("SpotLightNode",Cw),BS(rp,Cw);class Nw extends Cw{getSpotAttenuation(e){const t=this.light.iesMap;let n=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);n=Ey(t,Xg(i,0),0).r}else n=super.getSpotAttenuation(e);return n}}Xf("IESSpotLightNode",Nw),BS(class extends rp{constructor(e,t,n,i,r,s){super(e,t,n,i,r,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}},Nw);class Pw extends IS{constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}Xf("AmbientLightNode",Pw),BS(dp,Pw);class Lw extends IS{constructor(e=null){super(e),this.lightPositionNode=Wy(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Nv(new $r)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,r=mb.dot(i).mul(.5).add(.5),s=ry(n,t,r);e.context.irradiance.addAssign(s)}}Xf("HemisphereLightNode",Lw),BS(Jd,Lw);const Iw=Og((e=>{const t=e.uv.mul(2),n=t.x.floor(),i=t.y.floor();return n.add(i).mod(2).sign()}));class Uw extends qf{constructor(e=Lv()){super("float"),this.uvNode=e}setup(){return Iw({uv:this.uvNode})}}const Ow=Lg(Uw);rg("checker",Ow),Xf("CheckerNode",Uw);class Dw extends Gd{constructor(e){super(e),this.textures={}}load(e,t,n,i){const r=new Wd(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,(n=>{try{t(this.parse(JSON.parse(n)))}catch(t){i&&i(t),this.manager.itemError(e)}}),n,i)}parseNodes(e){const t={};if(void 0!==e){for(const n of e){const{uuid:e,type:i}=n;t[e]=Cg(jf(i)),t[e].uuid=e}const n={nodes:t,textures:this.textures};for(const i of e){i.meta=n;t[i.uuid].deserialize(i),delete i.meta}}return t}parse(e){const t=Cg(jf(e.type));t.uuid=e.uuid;const n={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=n,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}}const Fw=new Au;class Bw extends wT{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.setDefaultValues(Fw),this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor;this.vertexNode=Og((()=>{T_(Xg(),"vUv").assign(Lv());const e=E_("instancePosition"),t=Y_("vec4","mvPos");t.assign(sb.mul(Qg(e,1)));const n=tT.z.div(tT.w),i=Yy.mul(t),r=Y_("vec2","offset");return r.assign(Yb.xy),r.assign(r.mul(jb)),r.assign(r.div(tT.z)),r.y.assign(r.y.mul(n)),r.assign(r.mul(i.w)),i.assign(i.add(Qg(r,0,0))),i}))(),this.fragmentNode=Og((()=>{const n=T_(Xg(),"vUv"),i=Y_("float","alpha");i.assign(1);const r=n.x,s=n.y,a=r.mul(r).add(s.mul(s));if(e){const e=Y_("float","dlen");e.assign(a.fwidth()),i.assign(ly(e.oneMinus(),e.add(1),a).oneMinus())}else a.greaterThan(1).discard();let o;if(this.pointColorNode)o=this.pointColorNode;else if(t){o=E_("instanceColor").mul(Sb)}else o=Sb;return Qg(o,i)}))(),this.needsUpdate=!0}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}RT("InstancedPointsNodeMaterial",Bw);const Vw=new fu;class zw extends wT{constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(Vw),this.setValues(e)}}RT("LineBasicNodeMaterial",zw);const Gw=new _d;class kw extends wT{constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(Gw),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Gg(this.dashScaleNode):Gb,n=this.dashSizeNode?Gg(this.dashSizeNode):kb,i=this.dashSizeNode?Gg(this.dashGapNode):Hb;cv.assign(n),uv.assign(i);const r=T_(E_("lineDistance").mul(t));(e?r.add(e):r).mod(cv.add(uv)).greaterThan(cv).discard()}}RT("LineDashedNodeMaterial",kw);const Hw=new _d;class Ww extends wT{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.setDefaultValues(Hw),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor,n=this.dashed,i=this.worldUnits,r=Og((({start:e,end:t})=>{const n=Yy.element(2).element(2),i=Yy.element(3).element(2).mul(-.5).div(n).sub(e.z).div(t.z.sub(e.z));return Qg(ry(e.xyz,t.xyz,i),t.w)}));this.vertexNode=Og((()=>{$_("vec2","vUv").assign(Lv());const e=E_("instanceStart"),t=E_("instanceEnd"),s=Y_("vec4","start"),a=Y_("vec4","end");s.assign(sb.mul(Qg(e,1))),a.assign(sb.mul(Qg(t,1))),i&&($_("vec3","worldStart").assign(s.xyz),$_("vec3","worldEnd").assign(a.xyz));const o=tT.z.div(tT.w),l=Yy.element(2).element(3).equal(-1);Bg(l,(()=>{Bg(s.z.lessThan(0).and(a.z.greaterThan(0)),(()=>{a.assign(r({start:s,end:a}))})).elseif(a.z.lessThan(0).and(s.z.greaterThanEqual(0)),(()=>{s.assign(r({start:a,end:s}))}))}));const c=Yy.mul(s),u=Yy.mul(a),h=c.xyz.div(c.w),d=u.xyz.div(u.w),p=d.xy.sub(h.xy).temp();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const m=z_(Qg());if(i){const e=a.xyz.sub(s.xyz).normalize(),t=ry(s.xyz,a.xyz,.5).normalize(),i=e.cross(t).normalize(),r=e.cross(i),o=$_("vec4","worldPos");o.assign(Yb.y.lessThan(.5).cond(s,a));const l=Wb.mul(.5);o.addAssign(Qg(Yb.x.lessThan(0).cond(i.mul(l),i.mul(l).negate()),0)),n||(o.addAssign(Qg(Yb.y.lessThan(.5).cond(e.mul(l).negate(),e.mul(l)),0)),o.addAssign(Qg(r.mul(l),0)),Bg(Yb.y.greaterThan(1).or(Yb.y.lessThan(0)),(()=>{o.subAssign(Qg(r.mul(2).mul(l),0))}))),m.assign(Yy.mul(o));const c=z_($g());c.assign(Yb.y.lessThan(.5).cond(h,d)),m.z.assign(c.z.mul(m.w))}else{const e=Y_("vec2","offset");e.assign(Xg(p.y,p.x.negate())),p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(Yb.x.lessThan(0).cond(e.negate(),e)),Bg(Yb.y.lessThan(0),(()=>{e.assign(e.sub(p))})).elseif(Yb.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(Wb)),e.assign(e.div(tT.w)),m.assign(Yb.y.lessThan(.5).cond(c,u)),e.assign(e.mul(m.w)),m.assign(m.add(Qg(e,0,0)))}return m}))();const s=Og((({p1:e,p2:t,p3:n,p4:i})=>{const r=e.sub(n),s=i.sub(n),a=t.sub(e),o=r.dot(s),l=s.dot(a),c=r.dot(a),u=s.dot(s),h=a.dot(a).mul(u).sub(l.mul(l)),d=o.mul(l).sub(c.mul(u)).div(h).clamp(),p=o.add(l.mul(d)).div(u).clamp();return Xg(d,p)}));this.fragmentNode=Og((()=>{const r=$_("vec2","vUv");if(n){const e=this.offsetNode?Gg(this.offsetNodeNode):Xb,t=this.dashScaleNode?Gg(this.dashScaleNode):Gb,n=this.dashSizeNode?Gg(this.dashSizeNode):kb,i=this.dashSizeNode?Gg(this.dashGapNode):Hb;cv.assign(n),uv.assign(i);const s=E_("instanceDistanceStart"),a=E_("instanceDistanceEnd"),o=Yb.y.lessThan(.5).cond(t.mul(s),Gb.mul(a)),l=T_(o.add(Xb)),c=e?l.add(e):l;r.y.lessThan(-1).or(r.y.greaterThan(1)).discard(),c.mod(cv.add(uv)).greaterThan(cv).discard()}const a=Y_("float","alpha");if(a.assign(1),i){const t=$_("vec3","worldStart"),i=$_("vec3","worldEnd"),r=$_("vec4","worldPos").xyz.normalize().mul(1e5),o=i.sub(t),l=s({p1:t,p2:i,p3:$g(0,0,0),p4:r}),c=t.add(o.mul(l.x)),u=r.mul(l.y),h=c.sub(u).length().div(Wb);if(!n)if(e){const e=h.fwidth();a.assign(ly(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(e){const e=r.x,t=r.y.greaterThan(0).cond(r.y.sub(1),r.y.add(1)),n=e.mul(e).add(t.mul(t)),i=Y_("float","dlen");i.assign(n.fwidth()),Bg(r.y.abs().greaterThan(1),(()=>{a.assign(ly(i.oneMinus(),i.add(1),n).oneMinus())}))}else Bg(r.y.abs().greaterThan(1),(()=>{const e=r.x,t=r.y.greaterThan(0).cond(r.y.sub(1),r.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let o;if(this.lineColorNode)o=this.lineColorNode;else if(t){const e=E_("instanceColorStart"),t=E_("instanceColorEnd");o=Yb.y.lessThan(.5).cond(e,t).mul(Sb)}else o=Sb;return Qg(o,a)}))(),this.needsUpdate=!0}get worldUnits(){return this.useWorldUnits}set worldUnits(e){this.useWorldUnits!==e&&(this.useWorldUnits=e,this.setupShaders())}get dashed(){return this.useDash}set dashed(e){this.useDash!==e&&(this.useDash=e,this.setupShaders())}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}RT("Line2NodeMaterial",Ww);const Xw=new md;class jw extends wT{constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.colorSpaced=!1,this.setDefaultValues(Xw),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Gg(this.opacityNode):Eb;Z_.assign(Qg(OM(gb),e))}}RT("MeshNormalNodeMaterial",jw);const qw=new Qr;class Yw extends wT{constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(qw),this.setValues(e)}}RT("MeshBasicNodeMaterial",Yw);const $w=Og((({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),Zw=Og((e=>e.diffuseColor.mul(1/Math.PI))),Kw=Og((({dotNH:e})=>ov.mul(.5/Math.PI).add(1).mul(e.pow(ov)))),Jw=Og((({lightDirection:e})=>{const t=e.add(Qb).normalize(),n=gb.dot(t).clamp(),i=Qb.dot(t).clamp(),r=$w({f0:av,f90:1,dotVH:i}),s=Gg(.25),a=Kw({dotNH:n});return r.mul(s).mul(a)}));class Qw extends B_{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=gb.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(Zw({diffuseColor:Z_.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(Jw({lightDirection:e})).mul(wb))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Zw({diffuseColor:Z_})))}}const eR=new fd;class tR extends wT{constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(eR),this.setValues(e)}setupLightingModel(){return new Qw(!1)}}RT("MeshLambertNodeMaterial",tR);const nR=new dd;class iR extends wT{constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(nR),this.setValues(e)}setupLightingModel(){return new Qw}setupVariants(){const e=(this.shininessNode?Gg(this.shininessNode):Tb).max(1e-4);ov.assign(e);const t=this.specularNode||Ab;av.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}RT("MeshPhongNodeMaterial",iR);const rR=Og((()=>{const e=db.dFdx().abs().max(db.dFdy().abs());return e.x.max(e.y).max(e.z)})),sR=Og((e=>{const{roughness:t}=e,n=rR();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i})),aR=Og((e=>{const{alpha:t,dotNL:n,dotNV:i}=e,r=t.pow2(),s=n.mul(r.add(r.oneMinus().mul(i.pow2())).sqrt()),a=i.mul(r.add(r.oneMinus().mul(n.pow2())).sqrt());return Vv(.5,s.add(a).max(rx))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),oR=Og((({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),lR=Og((e=>{const{lightDirection:t,f0:n,f90:i,roughness:r,iridescenceFresnel:s}=e,a=e.normalView||gb,o=r.pow2(),l=t.add(Qb).normalize(),c=a.dot(t).clamp(),u=a.dot(Qb).clamp(),h=a.dot(l).clamp(),d=Qb.dot(l).clamp();let p=$w({f0:n,f90:i,dotVH:d});s&&(p=iv.mix(p,s));const m=aR({alpha:o,dotNL:c,dotNV:u}),f=oR({alpha:o,dotNH:h});return p.mul(m).mul(f)})),cR=Og((({roughness:e,dotNV:t})=>{const n=Qg(-1,-.0275,-.572,.022),i=Qg(1,.0425,1.04,-.04),r=e.mul(n).add(i),s=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return Xg(-1.04,1.04).mul(s).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),uR=Og((e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=cR({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))})),hR=Og((({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub($g(t).mul(s)).div(s.oneMinus())})).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),dR=Og((({roughness:e,dotNH:t})=>{const n=e.pow2(),i=Gg(1).div(n),r=t.pow2().oneMinus().max(.0078125);return Gg(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),pR=Og((({dotNV:e,dotNL:t})=>Gg(1).div(Gg(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),mR=Og((({lightDirection:e})=>{const t=e.add(Qb).normalize(),n=gb.dot(e).clamp(),i=gb.dot(Qb).clamp(),r=gb.dot(t).clamp(),s=dR({roughness:nv,dotNH:r}),a=pR({dotNV:i,dotNL:n});return tv.mul(s).mul(a)})),fR=o_(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),gR=(e,t)=>e.sub(t).div(e.add(t)).pow2(),_R=(e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=$g(54856e-17,44201e-17,52481e-17),r=$g(1681e3,1795300,2208400),s=$g(43278e5,93046e5,66121e5),a=Gg(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());o=$g(o.x.add(a),o.y,o.z).div(1.0685e-7);return fR.mul(o)},vR=Og((({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=ry(e,t,ly(0,.03,i)),a=e.div(s).pow2().mul(Gg(1).sub(n.pow2())),o=Gg(1).sub(a).sqrt(),l=gR(s,e),c=$w({f0:l,f90:1,dotVH:n}),u=c.oneMinus(),h=s.lessThan(e).cond(Math.PI,0),d=Gg(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return $g(1).add(t).div($g(1).sub(t))})(r.clamp(0,.9999)),m=gR(p,s.vec3()),f=$w({f0:m,f90:1,dotVH:o}),g=$g(p.x.lessThan(s).cond(Math.PI,0),p.y.lessThan(s).cond(Math.PI,0),p.z.lessThan(s).cond(Math.PI,0)),_=s.mul(i,o,2),v=$g(d).add(g),x=c.mul(f).clamp(1e-5,.9999),y=x.sqrt(),b=u.pow2().mul(f).div($g(1).sub(x));let S=c.add(b),T=b.sub(u);for(let e=1;e<=2;++e){T=T.mul(y);const t=_R(Gg(e).mul(_),Gg(e).mul(v)).mul(2);S=S.add(T.mul(t))}return S.max($g(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"}]}),xR=Og((({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.pow2(),s=jT(n.lessThan(.25),Gg(-339.2).mul(r).add(Gg(161.4).mul(n)).sub(25.9),Gg(-8.48).mul(r).add(Gg(14.3).mul(n)).sub(9.95)),a=jT(n.lessThan(.25),Gg(44).mul(r).sub(Gg(23.7).mul(n)).add(3.26),Gg(1.97).mul(r).sub(Gg(3.27).mul(n)).add(.72));return jT(n.lessThan(.25),0,Gg(.1).mul(n).sub(.025)).add(s.mul(i).add(a).exp()).mul(1/Math.PI).saturate()})),yR=$g(.04),bR=$g(1);class SR extends B_{constructor(e=!1,t=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(){if(!0===this.clearcoat&&(this.clearcoatRadiance=$g().temp("clearcoatRadiance"),this.clearcoatSpecularDirect=$g().temp("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=$g().temp("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=$g().temp("sheenSpecularDirect"),this.sheenSpecularIndirect=$g().temp("sheenSpecularIndirect")),!0===this.iridescence){const e=gb.dot(Qb).clamp();this.iridescenceFresnel=vR({outsideIOR:Gg(1),eta2:rv,cosTheta1:e,thinFilmThickness:sv,baseF0:av}),this.iridescenceF0=hR({f:this.iridescenceFresnel,f90:1,dotVH:e})}}computeMultiscattering(e,t,n=Gg(1)){const i=gb.dot(Qb).clamp(),r=cR({roughness:K_,dotNV:i}),s=(this.iridescenceF0?iv.mix(av,this.iridescenceF0):av).mul(r.x).add(n.mul(r.y)),a=r.x.add(r.y).oneMinus(),o=av.add(av.oneMinus().mul(.047619)),l=s.mul(o).div(a.mul(o).oneMinus());e.addAssign(s),t.addAssign(l.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=gb.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(mR({lightDirection:e}))),!0===this.clearcoat){const n=vb.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(lR({lightDirection:e,f0:yR,f90:bR,roughness:ev,normalView:vb})))}n.directDiffuse.addAssign(i.mul(Zw({diffuseColor:Z_.rgb}))),n.directSpecular.addAssign(i.mul(lR({lightDirection:e,f0:av,f90:1,roughness:K_,iridescence:this.iridescence,iridescenceFresnel:this.iridescenceFresnel})))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Zw({diffuseColor:Z_})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:n}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(tv,xR({normal:gb,viewDir:Qb,roughness:nv}))),!0===this.clearcoat){const e=vb.dot(Qb).clamp(),t=uR({dotNV:e,specularColor:yR,specularF90:bR,roughness:ev});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=$g().temp("singleScattering"),r=$g().temp("multiScattering"),s=t.mul(1/Math.PI);this.computeMultiscattering(i,r);const a=i.add(r),o=Z_.mul(a.r.max(a.g).max(a.b).oneMinus());n.indirectSpecular.addAssign(e.mul(i)),n.indirectSpecular.addAssign(r.mul(s)),n.indirectDiffuse.addAssign(o.mul(s))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const n=gb.dot(Qb).clamp().add(e),i=K_.mul(-16).oneMinus().negate().exp2(),r=e.sub(n.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(r)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=vb.dot(Qb).clamp(),n=$w({dotVH:e,f0:yR,f90:bR}),i=t.mul(Q_.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Q_));t.assign(i)}if(!0===this.sheen){const e=tv.r.max(tv.g).max(tv.b).mul(.157).oneMinus(),n=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const TR=new ud;class MR extends wT{constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(TR),this.setValues(e)}setupLightingModel(){return new SR}setupVariants(){const e=this.metalnessNode?Gg(this.metalnessNode):Nb;J_.assign(e);let t=this.roughnessNode?Gg(this.roughnessNode):Cb;t=sR({roughness:t}),K_.assign(t);const n=ry($g(.04),Z_.rgb,e);av.assign(n),Z_.assign(Qg(Z_.rgb.mul(e.oneMinus()),Z_.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}RT("MeshStandardNodeMaterial",MR);const ER=new hd;class AR extends MR{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.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.setDefaultValues(ER),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}setupLightingModel(){return new SR(this.useClearcoat,this.useSheen,this.useIridescence)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Gg(this.clearcoatNode):Lb,t=this.clearcoatRoughnessNode?Gg(this.clearcoatRoughnessNode):Ib;Q_.assign(e),ev.assign(t)}if(this.useSheen){const e=this.sheenNode?$g(this.sheenNode):Db,t=this.sheenRoughnessNode?Gg(this.sheenRoughnessNode):Fb;tv.assign(e),nv.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Gg(this.iridescenceNode):Bb,t=this.iridescenceIORNode?Gg(this.iridescenceIORNode):Vb,n=this.iridescenceThicknessNode?Gg(this.iridescenceThicknessNode):zb;iv.assign(e),rv.assign(t),sv.assign(n)}}setupNormal(e){super.setupNormal(e);const t=this.clearcoatNormalNode?$g(this.clearcoatNormalNode):Ub;vb.assign(t)}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,super.copy(e)}}RT("MeshPhysicalNodeMaterial",AR);class wR extends SR{constructor(e,t,n,i){super(e,t,n),this.useSSS=i}direct({lightDirection:e,lightColor:t,reflectedLight:n},i,r){if(!0===this.useSSS){const i=r.material,{thicknessColorNode:s,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:l,thicknessPowerNode:c,thicknessScaleNode:u}=i,h=e.add(gb.mul(a)).normalize(),d=Gg(Qb.dot(h.negate()).saturate().pow(c).mul(u)),p=$g(d.add(o).mul(s));n.directDiffuse.addAssign(p.mul(l.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:n},i,r)}}class RR extends AR{constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Gg(.1),this.thicknessAmbientNode=Gg(0),this.thicknessAttenuationNode=Gg(.1),this.thicknessPowerNode=Gg(2),this.thicknessScaleNode=Gg(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new wR(this.useClearcoat,this.useSheen,this.useIridescence,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)}}RT("MeshSSSNodeMaterial",RR);const CR=new Au;class NR extends wT{constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.normals=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(CR),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}RT("PointsNodeMaterial",NR);const PR=new cc;class LR extends wT{constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this.normals=!1,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(PR),this.setValues(e)}setupPosition({object:e,context:t}){const{positionNode:n,rotationNode:i,scaleNode:r}=this,s=$b;let a=sb.mul($g(n||0)),o=Xg(ob[0].xyz.length(),ob[1].xyz.length());null!==r&&(o=o.mul(r));let l=s.xy;e.center&&!0===e.center.isVector2&&(l=l.sub(Nv(e.center).sub(.5))),l=l.mul(o);const c=Gg(i||Ob),u=l.rotate(c);a=Qg(a.xy.add(u),a.zw);const h=Yy.mul(a);return t.vertex=s,h}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}}RT("SpriteNodeMaterial",LR);const IR=gp.createMaterialFromType;gp.createMaterialFromType=function(e){const t=CT(e);return void 0!==t?t:IR.call(this,e)};class UR extends gp{constructor(e){super(e),this.nodes={}}parse(e){const t=super.parse(e),n=this.nodes,i=e.inputNodes;for(const e in i){const r=i[e];t[e]=n[r]}return t}setNodes(e){return this.nodes=e,this}}class OR extends yp{constructor(e){super(e),this._nodesJSON=null}parse(e,t){this._nodesJSON=e.nodes;const n=super.parse(e,t);return this._nodesJSON=null,n}parseNodes(e,t){if(void 0!==e){const n=new Dw;return n.setTextures(t),n.parseNodes(e)}return{}}parseMaterials(e,t){const n={};if(void 0!==e){const i=this.parseNodes(this._nodesJSON,t),r=new UR;r.setTextures(t),r.setNodes(i);for(let t=0,i=e.length;t{const t=(e=e.trim()).indexOf(zR),n=-1!==t?e.slice(t+12):e,i=n.match(BR);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=VR.exec(r));)s.push(a);const o=[];let l=0;for(;l{const i=Gg(n).toVar(),r=Gg(t).toVar(),s=Wg(e).toVar();return jT(s,r,i)})),WR=Og((([e,t])=>{const n=Wg(t).toVar(),i=Gg(e).toVar();return jT(n,i.negate(),i)})),XR=Og((([e])=>{const t=Gg(e).toVar();return kg(xx(t))})),jR=Og((([e,t])=>{const n=Gg(e).toVar();return t.assign(XR(n)),n.sub(Gg(t))})),qR=Og((([e,t,n,i,r,s])=>{const a=Gg(s).toVar(),o=Gg(r).toVar(),l=Gg(i).toVar(),c=Gg(n).toVar(),u=Gg(t).toVar(),h=Gg(e).toVar(),d=Gg(Fv(1,o)).toVar();return Fv(1,a).mul(h.mul(d).add(u.mul(o))).add(a.mul(c.mul(d).add(l.mul(o))))})),YR=Og((([e,t,n,i,r,s])=>{const a=Gg(s).toVar(),o=Gg(r).toVar(),l=$g(i).toVar(),c=$g(n).toVar(),u=$g(t).toVar(),h=$g(e).toVar(),d=Gg(Fv(1,o)).toVar();return Fv(1,a).mul(h.mul(d).add(u.mul(o))).add(a.mul(c.mul(d).add(l.mul(o))))})),$R=bM([qR,YR]),ZR=Og((([e,t,n,i,r,s,a,o,l,c,u])=>{const h=Gg(u).toVar(),d=Gg(c).toVar(),p=Gg(l).toVar(),m=Gg(o).toVar(),f=Gg(a).toVar(),g=Gg(s).toVar(),_=Gg(r).toVar(),v=Gg(i).toVar(),x=Gg(n).toVar(),y=Gg(t).toVar(),b=Gg(e).toVar(),S=Gg(Fv(1,p)).toVar(),T=Gg(Fv(1,d)).toVar();return Gg(Fv(1,h)).toVar().mul(T.mul(b.mul(S).add(y.mul(p))).add(d.mul(x.mul(S).add(v.mul(p))))).add(h.mul(T.mul(_.mul(S).add(g.mul(p))).add(d.mul(f.mul(S).add(m.mul(p))))))})),KR=Og((([e,t,n,i,r,s,a,o,l,c,u])=>{const h=Gg(u).toVar(),d=Gg(c).toVar(),p=Gg(l).toVar(),m=$g(o).toVar(),f=$g(a).toVar(),g=$g(s).toVar(),_=$g(r).toVar(),v=$g(i).toVar(),x=$g(n).toVar(),y=$g(t).toVar(),b=$g(e).toVar(),S=Gg(Fv(1,p)).toVar(),T=Gg(Fv(1,d)).toVar();return Gg(Fv(1,h)).toVar().mul(T.mul(b.mul(S).add(y.mul(p))).add(d.mul(x.mul(S).add(v.mul(p))))).add(h.mul(T.mul(_.mul(S).add(g.mul(p))).add(d.mul(f.mul(S).add(m.mul(p))))))})),JR=bM([ZR,KR]),QR=Og((([e,t,n])=>{const i=Gg(n).toVar(),r=Gg(t).toVar(),s=Hg(e).toVar(),a=Hg(s.bitAnd(Hg(7))).toVar(),o=Gg(HR(a.lessThan(Hg(4)),r,i)).toVar(),l=Gg(Bv(2,HR(a.lessThan(Hg(4)),i,r))).toVar();return WR(o,Wg(a.bitAnd(Hg(1)))).add(WR(l,Wg(a.bitAnd(Hg(2)))))})),eC=Og((([e,t,n,i])=>{const r=Gg(i).toVar(),s=Gg(n).toVar(),a=Gg(t).toVar(),o=Hg(e).toVar(),l=Hg(o.bitAnd(Hg(15))).toVar(),c=Gg(HR(l.lessThan(Hg(8)),a,s)).toVar(),u=Gg(HR(l.lessThan(Hg(4)),s,HR(l.equal(Hg(12)).or(l.equal(Hg(14))),a,r))).toVar();return WR(c,Wg(l.bitAnd(Hg(1)))).add(WR(u,Wg(l.bitAnd(Hg(2)))))})),tC=bM([QR,eC]),nC=Og((([e,t,n])=>{const i=Gg(n).toVar(),r=Gg(t).toVar(),s=Kg(e).toVar();return $g(tC(s.x,r,i),tC(s.y,r,i),tC(s.z,r,i))})),iC=Og((([e,t,n,i])=>{const r=Gg(i).toVar(),s=Gg(n).toVar(),a=Gg(t).toVar(),o=Kg(e).toVar();return $g(tC(o.x,a,s,r),tC(o.y,a,s,r),tC(o.z,a,s,r))})),rC=bM([nC,iC]),sC=Og((([e])=>{const t=Gg(e).toVar();return Bv(.6616,t)})),aC=Og((([e])=>{const t=Gg(e).toVar();return Bv(.982,t)})),oC=Og((([e])=>{const t=$g(e).toVar();return Bv(.6616,t)})),lC=bM([sC,oC]),cC=Og((([e])=>{const t=$g(e).toVar();return Bv(.982,t)})),uC=bM([aC,cC]),hC=Og((([e,t])=>{const n=kg(t).toVar(),i=Hg(e).toVar();return i.shiftLeft(n).bitOr(i.shiftRight(kg(32).sub(n)))})),dC=Og((([e,t,n])=>{e.subAssign(n),e.bitXorAssign(hC(n,kg(4))),n.addAssign(t),t.subAssign(e),t.bitXorAssign(hC(e,kg(6))),e.addAssign(n),n.subAssign(t),n.bitXorAssign(hC(t,kg(8))),t.addAssign(e),e.subAssign(n),e.bitXorAssign(hC(n,kg(16))),n.addAssign(t),t.subAssign(e),t.bitXorAssign(hC(e,kg(19))),e.addAssign(n),n.subAssign(t),n.bitXorAssign(hC(t,kg(4))),t.addAssign(e)})),pC=Og((([e,t,n])=>{const i=Hg(n).toVar(),r=Hg(t).toVar(),s=Hg(e).toVar();return i.bitXorAssign(r),i.subAssign(hC(r,kg(14))),s.bitXorAssign(i),s.subAssign(hC(i,kg(11))),r.bitXorAssign(s),r.subAssign(hC(s,kg(25))),i.bitXorAssign(r),i.subAssign(hC(r,kg(16))),s.bitXorAssign(i),s.subAssign(hC(i,kg(4))),r.bitXorAssign(s),r.subAssign(hC(s,kg(14))),i.bitXorAssign(r),i.subAssign(hC(r,kg(24))),i})),mC=Og((([e])=>{const t=Hg(e).toVar();return Gg(t).div(Gg(Hg(kg(4294967295))))})),fC=Og((([e])=>{const t=Gg(e).toVar();return t.mul(t.mul(t.mul(t.mul(t.mul(6).sub(15)).add(10))))})),gC=Og((([e])=>{const t=kg(e).toVar(),n=Hg(Hg(1)).toVar(),i=Hg(Hg(kg(3735928559)).add(n.shiftLeft(Hg(2)).add(Hg(13)))).toVar();return pC(i.add(Hg(t)),i,i)})),_C=Og((([e,t])=>{const n=kg(t).toVar(),i=kg(e).toVar(),r=Hg(Hg(2)).toVar(),s=Hg().toVar(),a=Hg().toVar(),o=Hg().toVar();return s.assign(a.assign(o.assign(Hg(kg(3735928559)).add(r.shiftLeft(Hg(2)).add(Hg(13)))))),s.addAssign(Hg(i)),a.addAssign(Hg(n)),pC(s,a,o)})),vC=Og((([e,t,n])=>{const i=kg(n).toVar(),r=kg(t).toVar(),s=kg(e).toVar(),a=Hg(Hg(3)).toVar(),o=Hg().toVar(),l=Hg().toVar(),c=Hg().toVar();return o.assign(l.assign(c.assign(Hg(kg(3735928559)).add(a.shiftLeft(Hg(2)).add(Hg(13)))))),o.addAssign(Hg(s)),l.addAssign(Hg(r)),c.addAssign(Hg(i)),pC(o,l,c)})),xC=Og((([e,t,n,i])=>{const r=kg(i).toVar(),s=kg(n).toVar(),a=kg(t).toVar(),o=kg(e).toVar(),l=Hg(Hg(4)).toVar(),c=Hg().toVar(),u=Hg().toVar(),h=Hg().toVar();return c.assign(u.assign(h.assign(Hg(kg(3735928559)).add(l.shiftLeft(Hg(2)).add(Hg(13)))))),c.addAssign(Hg(o)),u.addAssign(Hg(a)),h.addAssign(Hg(s)),dC(c,u,h),c.addAssign(Hg(r)),pC(c,u,h)})),yC=Og((([e,t,n,i,r])=>{const s=kg(r).toVar(),a=kg(i).toVar(),o=kg(n).toVar(),l=kg(t).toVar(),c=kg(e).toVar(),u=Hg(Hg(5)).toVar(),h=Hg().toVar(),d=Hg().toVar(),p=Hg().toVar();return h.assign(d.assign(p.assign(Hg(kg(3735928559)).add(u.shiftLeft(Hg(2)).add(Hg(13)))))),h.addAssign(Hg(c)),d.addAssign(Hg(l)),p.addAssign(Hg(o)),dC(h,d,p),h.addAssign(Hg(a)),d.addAssign(Hg(s)),pC(h,d,p)})),bC=bM([gC,_C,vC,xC,yC]),SC=Og((([e,t])=>{const n=kg(t).toVar(),i=kg(e).toVar(),r=Hg(bC(i,n)).toVar(),s=Kg().toVar();return s.x.assign(r.bitAnd(kg(255))),s.y.assign(r.shiftRight(kg(8)).bitAnd(kg(255))),s.z.assign(r.shiftRight(kg(16)).bitAnd(kg(255))),s})),TC=Og((([e,t,n])=>{const i=kg(n).toVar(),r=kg(t).toVar(),s=kg(e).toVar(),a=Hg(bC(s,r,i)).toVar(),o=Kg().toVar();return o.x.assign(a.bitAnd(kg(255))),o.y.assign(a.shiftRight(kg(8)).bitAnd(kg(255))),o.z.assign(a.shiftRight(kg(16)).bitAnd(kg(255))),o})),MC=bM([SC,TC]),EC=Og((([e])=>{const t=Xg(e).toVar(),n=kg().toVar(),i=kg().toVar(),r=Gg(jR(t.x,n)).toVar(),s=Gg(jR(t.y,i)).toVar(),a=Gg(fC(r)).toVar(),o=Gg(fC(s)).toVar(),l=Gg($R(tC(bC(n,i),r,s),tC(bC(n.add(kg(1)),i),r.sub(1),s),tC(bC(n,i.add(kg(1))),r,s.sub(1)),tC(bC(n.add(kg(1)),i.add(kg(1))),r.sub(1),s.sub(1)),a,o)).toVar();return lC(l)})),AC=Og((([e])=>{const t=$g(e).toVar(),n=kg().toVar(),i=kg().toVar(),r=kg().toVar(),s=Gg(jR(t.x,n)).toVar(),a=Gg(jR(t.y,i)).toVar(),o=Gg(jR(t.z,r)).toVar(),l=Gg(fC(s)).toVar(),c=Gg(fC(a)).toVar(),u=Gg(fC(o)).toVar(),h=Gg(JR(tC(bC(n,i,r),s,a,o),tC(bC(n.add(kg(1)),i,r),s.sub(1),a,o),tC(bC(n,i.add(kg(1)),r),s,a.sub(1),o),tC(bC(n.add(kg(1)),i.add(kg(1)),r),s.sub(1),a.sub(1),o),tC(bC(n,i,r.add(kg(1))),s,a,o.sub(1)),tC(bC(n.add(kg(1)),i,r.add(kg(1))),s.sub(1),a,o.sub(1)),tC(bC(n,i.add(kg(1)),r.add(kg(1))),s,a.sub(1),o.sub(1)),tC(bC(n.add(kg(1)),i.add(kg(1)),r.add(kg(1))),s.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return uC(h)})),wC=bM([EC,AC]),RC=Og((([e])=>{const t=Xg(e).toVar(),n=kg().toVar(),i=kg().toVar(),r=Gg(jR(t.x,n)).toVar(),s=Gg(jR(t.y,i)).toVar(),a=Gg(fC(r)).toVar(),o=Gg(fC(s)).toVar(),l=$g($R(rC(MC(n,i),r,s),rC(MC(n.add(kg(1)),i),r.sub(1),s),rC(MC(n,i.add(kg(1))),r,s.sub(1)),rC(MC(n.add(kg(1)),i.add(kg(1))),r.sub(1),s.sub(1)),a,o)).toVar();return lC(l)})),CC=Og((([e])=>{const t=$g(e).toVar(),n=kg().toVar(),i=kg().toVar(),r=kg().toVar(),s=Gg(jR(t.x,n)).toVar(),a=Gg(jR(t.y,i)).toVar(),o=Gg(jR(t.z,r)).toVar(),l=Gg(fC(s)).toVar(),c=Gg(fC(a)).toVar(),u=Gg(fC(o)).toVar(),h=$g(JR(rC(MC(n,i,r),s,a,o),rC(MC(n.add(kg(1)),i,r),s.sub(1),a,o),rC(MC(n,i.add(kg(1)),r),s,a.sub(1),o),rC(MC(n.add(kg(1)),i.add(kg(1)),r),s.sub(1),a.sub(1),o),rC(MC(n,i,r.add(kg(1))),s,a,o.sub(1)),rC(MC(n.add(kg(1)),i,r.add(kg(1))),s.sub(1),a,o.sub(1)),rC(MC(n,i.add(kg(1)),r.add(kg(1))),s,a.sub(1),o.sub(1)),rC(MC(n.add(kg(1)),i.add(kg(1)),r.add(kg(1))),s.sub(1),a.sub(1),o.sub(1)),l,c,u)).toVar();return uC(h)})),NC=bM([RC,CC]),PC=Og((([e])=>{const t=Gg(e).toVar(),n=kg(XR(t)).toVar();return mC(bC(n))})),LC=Og((([e])=>{const t=Xg(e).toVar(),n=kg(XR(t.x)).toVar(),i=kg(XR(t.y)).toVar();return mC(bC(n,i))})),IC=Og((([e])=>{const t=$g(e).toVar(),n=kg(XR(t.x)).toVar(),i=kg(XR(t.y)).toVar(),r=kg(XR(t.z)).toVar();return mC(bC(n,i,r))})),UC=Og((([e])=>{const t=Qg(e).toVar(),n=kg(XR(t.x)).toVar(),i=kg(XR(t.y)).toVar(),r=kg(XR(t.z)).toVar(),s=kg(XR(t.w)).toVar();return mC(bC(n,i,r,s))})),OC=bM([PC,LC,IC,UC]),DC=Og((([e])=>{const t=Gg(e).toVar(),n=kg(XR(t)).toVar();return $g(mC(bC(n,kg(0))),mC(bC(n,kg(1))),mC(bC(n,kg(2))))})),FC=Og((([e])=>{const t=Xg(e).toVar(),n=kg(XR(t.x)).toVar(),i=kg(XR(t.y)).toVar();return $g(mC(bC(n,i,kg(0))),mC(bC(n,i,kg(1))),mC(bC(n,i,kg(2))))})),BC=Og((([e])=>{const t=$g(e).toVar(),n=kg(XR(t.x)).toVar(),i=kg(XR(t.y)).toVar(),r=kg(XR(t.z)).toVar();return $g(mC(bC(n,i,r,kg(0))),mC(bC(n,i,r,kg(1))),mC(bC(n,i,r,kg(2))))})),VC=Og((([e])=>{const t=Qg(e).toVar(),n=kg(XR(t.x)).toVar(),i=kg(XR(t.y)).toVar(),r=kg(XR(t.z)).toVar(),s=kg(XR(t.w)).toVar();return $g(mC(bC(n,i,r,s,kg(0))),mC(bC(n,i,r,s,kg(1))),mC(bC(n,i,r,s,kg(2))))})),zC=bM([DC,FC,BC,VC]),GC=Og((([e,t,n,i])=>{const r=Gg(i).toVar(),s=Gg(n).toVar(),a=kg(t).toVar(),o=$g(e).toVar(),l=Gg(0).toVar(),c=Gg(1).toVar();return xS({start:kg(0),end:a},(({i:e})=>{l.addAssign(c.mul(wC(o))),c.mulAssign(r),o.mulAssign(s)})),l})),kC=Og((([e,t,n,i])=>{const r=Gg(i).toVar(),s=Gg(n).toVar(),a=kg(t).toVar(),o=$g(e).toVar(),l=$g(0).toVar(),c=Gg(1).toVar();return xS({start:kg(0),end:a},(({i:e})=>{l.addAssign(c.mul(NC(o))),c.mulAssign(r),o.mulAssign(s)})),l})),HC=Og((([e,t,n,i])=>{const r=Gg(i).toVar(),s=Gg(n).toVar(),a=kg(t).toVar(),o=$g(e).toVar();return Xg(GC(o,a,s,r),GC(o.add($g(kg(19),kg(193),kg(17))),a,s,r))})),WC=Og((([e,t,n,i])=>{const r=Gg(i).toVar(),s=Gg(n).toVar(),a=kg(t).toVar(),o=$g(e).toVar(),l=$g(kC(o,a,s,r)).toVar(),c=Gg(GC(o.add($g(kg(19),kg(193),kg(17))),a,s,r)).toVar();return Qg(l,c)})),XC=Og((([e,t,n,i,r,s,a])=>{const o=kg(a).toVar(),l=Gg(s).toVar(),c=kg(r).toVar(),u=kg(i).toVar(),h=kg(n).toVar(),d=kg(t).toVar(),p=Xg(e).toVar(),m=$g(zC(Xg(d.add(u),h.add(c)))).toVar(),f=Xg(m.x,m.y).toVar();f.subAssign(.5),f.mulAssign(l),f.addAssign(.5);const g=Xg(Xg(Gg(d),Gg(h)).add(f)).toVar(),_=Xg(g.sub(p)).toVar();return Bg(o.equal(kg(2)),(()=>Cx(_.x).add(Cx(_.y)))),Bg(o.equal(kg(3)),(()=>Hx(Cx(_.x),Cx(_.y)))),$x(_,_)})),jC=Og((([e,t,n,i,r,s,a,o,l])=>{const c=kg(l).toVar(),u=Gg(o).toVar(),h=kg(a).toVar(),d=kg(s).toVar(),p=kg(r).toVar(),m=kg(i).toVar(),f=kg(n).toVar(),g=kg(t).toVar(),_=$g(e).toVar(),v=$g(zC($g(g.add(p),f.add(d),m.add(h)))).toVar();v.subAssign(.5),v.mulAssign(u),v.addAssign(.5);const x=$g($g(Gg(g),Gg(f),Gg(m)).add(v)).toVar(),y=$g(x.sub(_)).toVar();return Bg(c.equal(kg(2)),(()=>Cx(y.x).add(Cx(y.y).add(Cx(y.z))))),Bg(c.equal(kg(3)),(()=>Hx(Hx(Cx(y.x),Cx(y.y)),Cx(y.z)))),$x(y,y)})),qC=bM([XC,jC]),YC=Og((([e,t,n])=>{const i=kg(n).toVar(),r=Gg(t).toVar(),s=Xg(e).toVar(),a=kg().toVar(),o=kg().toVar(),l=Xg(jR(s.x,a),jR(s.y,o)).toVar(),c=Gg(1e6).toVar();return xS({start:-1,end:kg(1),name:"x",condition:"<="},(({x:e})=>{xS({start:-1,end:kg(1),name:"y",condition:"<="},(({y:t})=>{const n=Gg(qC(l,e,t,a,o,r,i)).toVar();c.assign(kx(c,n))}))})),Bg(i.equal(kg(0)),(()=>{c.assign(_x(c))})),c})),$C=Og((([e,t,n])=>{const i=kg(n).toVar(),r=Gg(t).toVar(),s=Xg(e).toVar(),a=kg().toVar(),o=kg().toVar(),l=Xg(jR(s.x,a),jR(s.y,o)).toVar(),c=Xg(1e6,1e6).toVar();return xS({start:-1,end:kg(1),name:"x",condition:"<="},(({x:e})=>{xS({start:-1,end:kg(1),name:"y",condition:"<="},(({y:t})=>{const n=Gg(qC(l,e,t,a,o,r,i)).toVar();Bg(n.lessThan(c.x),(()=>{c.y.assign(c.x),c.x.assign(n)})).elseif(n.lessThan(c.y),(()=>{c.y.assign(n)}))}))})),Bg(i.equal(kg(0)),(()=>{c.assign(_x(c))})),c})),ZC=Og((([e,t,n])=>{const i=kg(n).toVar(),r=Gg(t).toVar(),s=Xg(e).toVar(),a=kg().toVar(),o=kg().toVar(),l=Xg(jR(s.x,a),jR(s.y,o)).toVar(),c=$g(1e6,1e6,1e6).toVar();return xS({start:-1,end:kg(1),name:"x",condition:"<="},(({x:e})=>{xS({start:-1,end:kg(1),name:"y",condition:"<="},(({y:t})=>{const n=Gg(qC(l,e,t,a,o,r,i)).toVar();Bg(n.lessThan(c.x),(()=>{c.z.assign(c.y),c.y.assign(c.x),c.x.assign(n)})).elseif(n.lessThan(c.y),(()=>{c.z.assign(c.y),c.y.assign(n)})).elseif(n.lessThan(c.z),(()=>{c.z.assign(n)}))}))})),Bg(i.equal(kg(0)),(()=>{c.assign(_x(c))})),c})),KC=Og((([e,t,n])=>{const i=kg(n).toVar(),r=Gg(t).toVar(),s=$g(e).toVar(),a=kg().toVar(),o=kg().toVar(),l=kg().toVar(),c=$g(jR(s.x,a),jR(s.y,o),jR(s.z,l)).toVar(),u=Gg(1e6).toVar();return xS({start:-1,end:kg(1),name:"x",condition:"<="},(({x:e})=>{xS({start:-1,end:kg(1),name:"y",condition:"<="},(({y:t})=>{xS({start:-1,end:kg(1),name:"z",condition:"<="},(({z:n})=>{const s=Gg(qC(c,e,t,n,a,o,l,r,i)).toVar();u.assign(kx(u,s))}))}))})),Bg(i.equal(kg(0)),(()=>{u.assign(_x(u))})),u})),JC=bM([YC,KC]),QC=Og((([e,t,n])=>{const i=kg(n).toVar(),r=Gg(t).toVar(),s=$g(e).toVar(),a=kg().toVar(),o=kg().toVar(),l=kg().toVar(),c=$g(jR(s.x,a),jR(s.y,o),jR(s.z,l)).toVar(),u=Xg(1e6,1e6).toVar();return xS({start:-1,end:kg(1),name:"x",condition:"<="},(({x:e})=>{xS({start:-1,end:kg(1),name:"y",condition:"<="},(({y:t})=>{xS({start:-1,end:kg(1),name:"z",condition:"<="},(({z:n})=>{const s=Gg(qC(c,e,t,n,a,o,l,r,i)).toVar();Bg(s.lessThan(u.x),(()=>{u.y.assign(u.x),u.x.assign(s)})).elseif(s.lessThan(u.y),(()=>{u.y.assign(s)}))}))}))})),Bg(i.equal(kg(0)),(()=>{u.assign(_x(u))})),u})),eN=bM([$C,QC]),tN=Og((([e,t,n])=>{const i=kg(n).toVar(),r=Gg(t).toVar(),s=$g(e).toVar(),a=kg().toVar(),o=kg().toVar(),l=kg().toVar(),c=$g(jR(s.x,a),jR(s.y,o),jR(s.z,l)).toVar(),u=$g(1e6,1e6,1e6).toVar();return xS({start:-1,end:kg(1),name:"x",condition:"<="},(({x:e})=>{xS({start:-1,end:kg(1),name:"y",condition:"<="},(({y:t})=>{xS({start:-1,end:kg(1),name:"z",condition:"<="},(({z:n})=>{const s=Gg(qC(c,e,t,n,a,o,l,r,i)).toVar();Bg(s.lessThan(u.x),(()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(s)})).elseif(s.lessThan(u.y),(()=>{u.z.assign(u.y),u.y.assign(s)})).elseif(s.lessThan(u.z),(()=>{u.z.assign(s)}))}))}))})),Bg(i.equal(kg(0)),(()=>{u.assign(_x(u))})),u})),nN=bM([ZC,tN]);HR.setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),WR.setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),XR.setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),qR.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"}]}),YR.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"}]}),ZR.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"}]}),KR.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"}]}),QR.setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),eC.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"}]}),nC.setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),iC.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"}]}),sC.setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),aC.setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),oC.setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),cC.setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),hC.setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),pC.setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),mC.setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),fC.setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),gC.setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),_C.setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),vC.setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),xC.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"}]}),yC.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"}]}),SC.setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),TC.setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),EC.setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),AC.setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]}),RC.setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),CC.setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),PC.setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),LC.setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),IC.setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),UC.setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]}),DC.setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),FC.setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),BC.setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),VC.setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]}),GC.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"}]}),kC.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"}]}),HC.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"}]}),WC.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"}]}),XC.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"}]}),jC.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"}]}),YC.setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),$C.setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),ZC.setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),KC.setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),QC.setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),tN.setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]});const iN=Og((([e])=>{const t=$g(e).toVar(),n=Gg(t.x).toVar(),i=Gg(t.y).toVar(),r=Gg(t.z).toVar();Bg(i.lessThan(1e-4),(()=>$g(r,r,r))).else((()=>{n.assign(Bv(6,n.sub(xx(n))));const e=kg(Bx(n)).toVar(),t=Gg(n.sub(Gg(e))).toVar(),s=Gg(r.mul(Fv(1,i))).toVar(),a=Gg(r.mul(Fv(1,i.mul(t)))).toVar(),o=Gg(r.mul(Fv(1,i.mul(Fv(1,t))))).toVar();return Bg(e.equal(kg(0)),(()=>$g(r,o,s))).elseif(e.equal(kg(1)),(()=>$g(a,r,s))).elseif(e.equal(kg(2)),(()=>$g(s,r,o))).elseif(e.equal(kg(3)),(()=>$g(s,a,r))).elseif(e.equal(kg(4)),(()=>$g(o,s,r))),$g(r,s,a)}))})),rN=Og((([e])=>{const t=$g(e).toVar(),n=Gg(t.x).toVar(),i=Gg(t.y).toVar(),r=Gg(t.z).toVar(),s=Gg(kx(n,kx(i,r))).toVar(),a=Gg(Hx(n,Hx(i,r))).toVar(),o=Gg(a.sub(s)).toVar(),l=Gg().toVar(),c=Gg().toVar(),u=Gg().toVar();return u.assign(a),Bg(a.greaterThan(0),(()=>{c.assign(o.div(a))})).else((()=>{c.assign(0)})),Bg(c.lessThanEqual(0),(()=>{l.assign(0)})).else((()=>{Bg(n.greaterThanEqual(a),(()=>{l.assign(i.sub(r).div(o))})).elseif(i.greaterThanEqual(a),(()=>{l.assign(Dv(2,r.sub(n).div(o)))})).else((()=>{l.assign(Dv(4,n.sub(i).div(o)))})),l.mulAssign(1/6),Bg(l.lessThan(0),(()=>{l.addAssign(1)}))})),$g(l,c,u)}));iN.setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),rN.setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]});const sN=Og((([e])=>{const t=$g(e).toVar(),n=Jg(Wv(t,$g(.04045))).toVar(),i=$g(t.div(12.92)).toVar(),r=$g(Kx(Hx(t.add($g(.055)),$g(0)).div(1.055),$g(2.4))).toVar();return ry(i,r,n)}));sN.setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]});const aN=(e,t)=>{e=Gg(e),t=Gg(t);const n=Xg(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return ly(e.sub(n),e.add(n),t)},oN=(e,t,n,i)=>ry(e,t,n[i].clamp()),lN=(e,t,n=Lv())=>oN(e,t,n,"x"),cN=(e,t,n=Lv())=>oN(e,t,n,"y"),uN=(e,t,n,i,r)=>ry(e,t,aN(n,i[r])),hN=(e,t,n,i=Lv())=>uN(e,t,n,i,"x"),dN=(e,t,n,i=Lv())=>uN(e,t,n,i,"y"),pN=(e=1,t=0,n=Lv())=>n.mul(e).add(t),mN=(e,t=1)=>(e=Gg(e)).abs().pow(t).mul(e.sign()),fN=(e,t=1,n=.5)=>Gg(e).sub(n).mul(t).add(n),gN=(e=Lv(),t=1,n=0)=>wC(e.convert("vec2|vec3")).mul(t).add(n),_N=(e=Lv(),t=1,n=0)=>NC(e.convert("vec2|vec3")).mul(t).add(n),vN=(e=Lv(),t=1,n=0)=>{e=e.convert("vec2|vec3");return Qg(NC(e),wC(e.add(Xg(19,73)))).mul(t).add(n)},xN=(e=Lv(),t=1)=>JC(e.convert("vec2|vec3"),t,kg(1)),yN=(e=Lv(),t=1)=>eN(e.convert("vec2|vec3"),t,kg(1)),bN=(e=Lv(),t=1)=>nN(e.convert("vec2|vec3"),t,kg(1)),SN=(e=Lv())=>OC(e.convert("vec2|vec3")),TN=(e=Lv(),t=3,n=2,i=.5,r=1)=>GC(e,kg(t),n,i).mul(r),MN=(e=Lv(),t=3,n=2,i=.5,r=1)=>HC(e,kg(t),n,i).mul(r),EN=(e=Lv(),t=3,n=2,i=.5,r=1)=>kC(e,kg(t),n,i).mul(r),AN=(e=Lv(),t=3,n=2,i=.5,r=1)=>WC(e,kg(t),n,i).mul(r);function wN(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function RN(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}class CN{constructor(){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparent=[],this.lightsNode=new OS([]),this.lightsArray=[],this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparent.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,r,s){let a=this.renderItems[this.renderItemsIndex];return void 0===a?(a={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s},this.renderItems[this.renderItemsIndex]=a):(a.id=e.id,a.object=e,a.geometry=t,a.material=n,a.groupOrder=i,a.renderOrder=e.renderOrder,a.z=r,a.group=s),this.renderItemsIndex++,a}push(e,t,n,i,r,s){const a=this.getNextRenderItem(e,t,n,i,r,s);!0===e.occlusionTest&&this.occlusionQueryCount++,(!0===n.transparent?this.transparent:this.opaque).push(a)}unshift(e,t,n,i,r,s){const a=this.getNextRenderItem(e,t,n,i,r,s);(!0===n.transparent?this.transparent:this.opaque).unshift(a)}pushLight(e){this.lightsArray.push(e)}getLightsNode(){return this.lightsNode.fromLights(this.lightsArray)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||wN),this.transparent.length>1&&this.transparent.sort(t||RN)}finish(){this.lightsNode.fromLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,c=o.height>>t;let u=e.depthTexture||r[t],h=!1;void 0===u&&(u=new Qa,u.format=e.stencilBuffer?ke:Ge,u.type=e.stencilBuffer?De:Pe,u.image.width=l,u.image.height=c,r[t]=u),n.width===o.width&&o.height===n.height||(h=!0,u.needsUpdate=!0,u.image.width=l,u.image.height=c),n.width=o.width,n.height=o.height,n.textures=a,n.depthTexture=u,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u.needsUpdate=!0,n.sampleCount=i);const d={sampleCount:i};for(let e=0;e{if(e.removeEventListener("dispose",t),void 0!==a)for(let e=0;e0){const i=e.image;if(void 0===i);else if(!1===i.complete);else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0}if(!0!==n.initialized){n.initialized=!0,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}n.version=e.version}getSize(e,t=UN){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),t.width=n.width,t.height=n.height,t.depth=e.isCubeTexture?6:n.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==ge&&e.minFilter!==be)}isEnvironmentTexture(e){const t=e.mapping;return t===ue||t===he||t===le||t===ce}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class DN extends $r{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}const FN=new DN;class BN extends hf{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(FN,this.renderer.currentColorSpace),FN.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(FN,this.renderer.currentColorSpace),FN.a=1,s=!0;else if(!0===r.isNode){const n=this.get(e),s=r;FN.copy(i._clearColor);let a=n.backgroundMesh;if(void 0===a){const e=I_(Qg(s),{getUV:()=>fb,getTextureLevel:e=>zE.mul(Ty(e))}).mul(GE);let t=tS();t=t.setZ(t.w);const i=new wT;i.side=d,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.vertexNode=t,i.fragmentNode=e,n.backgroundMeshNode=e,n.backgroundMesh=a=new ks(new ed(1,32,32),i),a.frustumCulled=!1,a.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)}}const o=s.getCacheKey();n.backgroundCacheKey!==o&&(n.backgroundMeshNode.node=Qg(s),a.material.needsUpdate=!0,n.backgroundCacheKey=o),t.unshift(a,a.geometry,a.material,0,0,null)}if(!0===i.autoClear||!0===s){FN.multiplyScalar(FN.a);const e=n.clearColorValue;e.r=FN.r,e.g=FN.g,e.b=FN.b,e.a=FN.a,n.depthClearValue=i._clearDepth,n.stencilClearValue=i._clearStencil,n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}class VN{constructor(e,t,n,i,r,s,a,o=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=o,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){let n=t;!0!==t.shared&&(n=t.clone()),e.push(n)}return e}}class zN extends hf{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new tM,this.nodeBuilderCache=new Map,this.callHashCache=new nf,this.groupsData=new nf}updateGroup(e){const t=e.groupNode,n=t.name;if(n===Rv.name)return!0;if(n===wv.name){const t=this.get(e),n=this.nodeFrame.renderId;return t.renderId!==n&&(t.renderId=n,!0)}if(n===Av.name){const t=this.get(e),n=this.nodeFrame.frameId;return t.frameId!==n&&(t.frameId=n,!0)}const i=[t,e];let r=this.groupsData.get(i);return void 0===r&&this.groupsData.set(i,r={}),r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(n=i.get(r),void 0===n){const t=this.backend.createNodeBuilder(e.object,this.renderer,e.scene);t.material=e.material,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.toneMappingNode=this.getToneMappingNode(),t.clippingContext=e.clippingContext,t.build(),n=this._createNodeBuilderState(t),i.set(r,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),n=this._createNodeBuilderState(i),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new VN(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.transforms)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getToneMappingNode(){return!1===this.isToneMappingState?null:this.renderer.toneMappingNode||this.get(this.renderer).toneMappingNode||null}getCacheKey(e,t){const n=[e,t],i=this.renderer.info.calls;let r=this.callHashCache.get(n);if(void 0===r||r.callId!==i){const s=this.getEnvironmentNode(e),a=this.getFogNode(e),o=this.getToneMappingNode(),l=[];t&&l.push(t.getCacheKey()),s&&l.push(s.getCacheKey()),a&&l.push(a.getCacheKey()),o&&l.push(o.getCacheKey()),r={callId:i,cacheKey:l.join(",")},this.callHashCache.set(n,r)}return r.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e),this.updateToneMapping()}get isToneMappingState(){const e=this.renderer.getRenderTarget();return!e||!e.isCubeRenderTarget}updateToneMapping(){const e=this.renderer,t=this.get(e),n=e.toneMapping;if(this.isToneMappingState&&n!==K){if(t.toneMapping!==n){const i=t.rendererToneMappingNode||OA(n,Oy("toneMappingExposure","float",e));i.toneMapping=n,t.rendererToneMappingNode=i,t.toneMappingNode=i,t.toneMapping=n}}else delete t.toneMappingNode,delete t.toneMapping}updateBackground(e){const t=this.get(e),n=e.background;if(n){if(t.background!==n){let e=null;if(!0===n.isCubeTexture)e=NS(n,fb);else if(!0===n.isTexture){let t=null;n.mapping===ue||n.mapping===he?(t=HS(),n.flipY=!1):t=iT,e=Ey(n,t).setUpdateMatrix(!0)}else n.isColor;t.backgroundNode=e,t.background=n}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){let e=null;n.isFogExp2?e=_w(Oy("color","color",n),Oy("density","float",n)):n.isFog&&(e=fw(Oy("color","color",n),Oy("near","float",n),Oy("far","float",n))),t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){let e=null;!0===n.isCubeTexture?e=NS(n):!0===n.isTexture&&(e=Ey(n)),t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=i,s.material=r,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}updateBefore(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateBeforeNodes)t.updateBeforeNode(e)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}dispose(){super.dispose(),this.nodeFrame=new tM,this.nodeBuilderCache=new Map}}const GN=new sc,kN=new Jn,HN=new Si,WN=new ha,XN=new ar,jN=new Ni;class qN{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,alpha:i=!0}=t;this.domElement=e.getDomElement(),this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=n,this.outputColorSpace=Xt,this.toneMapping=K,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=!0,this.stencil=!0,this.clippingPlanes=[],this.info=new yf,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Si(0,0,this._width,this._height),this._scissor=new Si(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null;const r=!0===this.alpha?0:1;this._clearColor=new DN(0,0,0,r),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._handleObjectFunction=this._renderObjectDirect,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.shadowMap={enabled:!1,type:null},this.xr={enabled:!1}}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)=>{const n=this.backend;try{await n.init(this)}catch(e){return void t(e)}this._nodes=new zN(this,n),this._animation=new tf(this._nodes,this.info),this._attributes=new gf(n),this._background=new BN(this,this._nodes),this._geometries=new xf(this._attributes,this.info),this._textures=new ON(this,n,this.info),this._pipelines=new Af(n,this._nodes),this._bindings=new wf(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new uf(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new NN,this._renderContexts=new IN,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,l=!0===e.isScene?e:GN;null===n&&(n=e);const c=this._renderTarget,u=this._renderContexts.get(n,t,c),h=this._activeMipmapLevel,d=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new of),u.clippingContext.updateGlobal(this,t),l.onBeforeRender(this,e,t,c);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p),n!==e&&n.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==c){this._textures.updateRenderTarget(c,h);const e=this._textures.get(c);u.textures=e.textures,u.depthTexture=e.depthTexture}else u.textures=null,u.depthTexture=null;this._nodes.updateScene(l),this._background.update(l,p,u);const m=p.opaque,f=p.transparent,g=p.lightsNode;m.length>0&&this._renderObjects(m,t,l,g),f.length>0&&this._renderObjects(f,t,l,g),i.renderId=r,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init();const n=this._renderContext(e,t);await this.backend.resolveTimestampAsync(n,"render")}render(e,t){!1!==this._initialized&&this._renderContext(e,t)}_renderContext(e,t){const n=this._nodes.nodeFrame,i=n.renderId,r=this._currentRenderContext,s=this._currentRenderObjectFunction,a=!0===e.isScene?e:GN,o=this._renderTarget,l=this._renderContexts.get(e,t,o),c=this._activeCubeFace,u=this._activeMipmapLevel;this._currentRenderContext=l,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,n.renderId=this.info.calls;const h=this.coordinateSystem;t.coordinateSystem!==h&&(t.coordinateSystem=h,t.updateProjectionMatrix()),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===this.info.autoReset&&this.info.reset();let d=this._viewport,p=this._scissor,m=this._pixelRatio;null!==o&&(d=o.viewport,p=o.scissor,m=1),this.getDrawingBufferSize(kN),HN.set(0,0,kN.width,kN.height);const f=void 0===d.minDepth?0:d.minDepth,g=void 0===d.maxDepth?1:d.maxDepth;l.viewportValue.copy(d).multiplyScalar(m).floor(),l.viewportValue.width>>=u,l.viewportValue.height>>=u,l.viewportValue.minDepth=f,l.viewportValue.maxDepth=g,l.viewport=!1===l.viewportValue.equals(HN),l.scissorValue.copy(p).multiplyScalar(m).floor(),l.scissor=this._scissorTest&&!1===l.scissorValue.equals(HN),l.scissorValue.width>>=u,l.scissorValue.height>>=u,l.clippingContext||(l.clippingContext=new of),l.clippingContext.updateGlobal(this,t),a.onBeforeRender(this,e,t,o),XN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),WN.setFromProjectionMatrix(XN,h);const _=this._renderLists.get(e,t);if(_.begin(),this._projectObject(e,t,0,_),_.finish(),!0===this.sortObjects&&_.sort(this._opaqueSort,this._transparentSort),null!==o){this._textures.updateRenderTarget(o,u);const e=this._textures.get(o);l.textures=e.textures,l.depthTexture=e.depthTexture,l.width=e.width,l.height=e.height,l.renderTarget=o,l.depth=o.depthBuffer,l.stencil=o.stencilBuffer}else l.textures=null,l.depthTexture=null,l.width=this.domElement.width,l.height=this.domElement.height,l.depth=this.depth,l.stencil=this.stencil;l.width>>=u,l.height>>=u,l.activeCubeFace=c,l.activeMipmapLevel=u,l.occlusionQueryCount=_.occlusionQueryCount,this._nodes.updateScene(a),this._background.update(a,_,l),this.backend.beginRender(l);const v=_.opaque,x=_.transparent,y=_.lightsNode;return v.length>0&&this._renderObjects(v,t,a,y),x.length>0&&this._renderObjects(x,t,a,y),this.backend.finishRender(l),n.renderId=i,this._currentRenderContext=r,this._currentRenderObjectFunction=s,a.onAfterRender(this,e,t,o),l}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)}getArrayBuffer(e){return this.getArrayBufferAsync(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.setSize(this._width,this._height,!1)}setDrawingBufferSize(e,t,n){this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,n=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._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,n,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=r,a.maxDepth=s}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,n=!0){let i=null;const r=this._renderTarget;null!==r&&(this._textures.updateRenderTarget(r),i=this._textures.get(r)),this.backend.clear(e,t,n,i)}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,n=!0){!1===this._initialized&&await this.init(),this.clear(e,t,n)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentColorSpace(){const e=this._renderTarget;if(null!==e){const t=e.texture;return(Array.isArray(t)?t[0]:t).colorSpace}return this.outputColorSpace}dispose(){this.info.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}async computeAsync(e){!1===this._initialized&&await this.init();const t=this._nodes.nodeFrame,n=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.computeCalls++,t.renderId=this.info.calls,!0===this.info.autoReset&&this.info.resetCompute();const i=this.backend,r=this._pipelines,s=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.");i.beginCompute(e);for(const t of o){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),s.delete(t),a.delete(t)};t.addEventListener("dispose",e),t.onInit({renderer:this})}a.updateForCompute(t),s.updateForCompute(t);const n=s.getForCompute(t),o=r.getForCompute(t,n);i.compute(e,t,n,o)}i.finishCompute(e),await this.backend.resolveTimestampAsync(e,"compute"),t.renderId=n}hasFeatureAsync(e){return this.backend.hasFeatureAsync(e)}hasFeature(e){return this.backend.hasFeature(e)}copyFramebufferToTexture(e){const t=this._currentRenderContext;this._textures.updateTexture(e),this.backend.copyFramebufferToTexture(e,t)}readRenderTargetPixelsAsync(e,t,n,i,r){return this.backend.copyTextureToBuffer(e.texture,t,n,i,r)}_projectObject(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||WN.intersectsSprite(e)){!0===this.sortObjects&&jN.setFromMatrixPosition(e.matrixWorld).applyMatrix4(XN);const t=e.geometry,r=e.material;r.visible&&i.push(e,t,r,n,jN.z,null)}}else if(e.isLineLoop);else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||WN.intersectsObject(e))){const t=e.geometry,r=e.material;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),jN.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(XN)),Array.isArray(r)){const s=t.groups;for(let a=0,o=s.length;a0?r:"";t=`${n.name} {\n\t${i} ${e.name}[${s}];\n};\n`}else{t=`${this.getVectorType(e.type)} ${e.name};`,r=!0}const s=e.node.precision;if(null!==s&&(t=oP[s]+" "+t),r){t="\t"+t;const n=e.groupNode.name;(i[n]||(i[n]=[])).push(t)}else t="uniform "+t,n.push(t)}let r="";for(const t in i){const n=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,n.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Ne){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[],n=e.getMemberTypes();for(let e=0;e0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${i.result};`)))}const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=n}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){if("texture"===t)a=new rP(r.name,r.node),this.bindings[n].push(a);else if("cubeTexture"===t)a=new sP(r.name,r.node),this.bindings[n].push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new JN(e);t.name=e.name,this.bindings[n].push(t),a=t}else{const i=e.groupNode,s=i.name,o=this.uniformGroups[n]||(this.uniformGroups[n]={});let l=o[s];void 0===l&&(l=new tP(n+"_"+s,i),o[s]=l,this.bindings[n].push(l)),a=this.getNodeUniform(r,t),l.addUniform(a)}s.uniformGPU=a}return r}}let hP=null,dP=null,pP=null;class mP{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(e){}finish(e){}draw(e,t){}createProgram(e){}destroyProgram(e){}createBindings(e){}updateBindings(e){}createRenderPipeline(e){}createComputePipeline(e,t){}destroyPipeline(e){}needsRenderUpdate(e){}getRenderCacheKey(e){}createNodeBuilder(e){}createSampler(e){}createDefaultTexture(e){}createTexture(e){}copyTextureToBuffer(e,t,n,i,r){}createAttribute(e){}createIndexAttribute(e){}updateAttribute(e){}destroyAttribute(e){}getContext(){}updateSize(){}resolveTimestampAsync(e,t){}hasFeatureAsync(e){}hasFeature(e){}getInstanceCount(e){const{object:t,geometry:n}=e;return n.isInstancedBufferGeometry?n.instanceCount:t.isInstancedMesh?t.count:1}getDrawingBufferSize(){return hP=hP||new Jn,this.renderer.getDrawingBufferSize(hP)}getScissor(){return dP=dP||new Si,this.renderer.getScissor(dP)}setScissorTest(e){}getClearColor(){const e=this.renderer;return pP=pP||new DN,e.getClearColor(pP),pP.getRGB(pP,this.renderer.currentColorSpace),pP}getDomElement(){let t=this.domElement;return null===t&&(t=void 0!==this.parameters.canvas?this.parameters.canvas:si(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${e} webgpu`),this.domElement=t),t}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)}}let fP=0;class gP{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 _P{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,c=o.bufferGPU;if(void 0===c&&(c=this._createBuffer(i,t,r,s),o.bufferGPU=c,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let u={bufferGPU:c,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===Ne,id:fP++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,s);u=new gP(u,e)}n.set(e,u)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()}))}}let TP,MP,EP,AP=!1;class wP{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===AP&&(this._init(this.gl),AP=!0)}_init(e){TP={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[fe]:e.MIRRORED_REPEAT},MP={[ge]:e.NEAREST,[_e]:e.NEAREST_MIPMAP_NEAREST,[xe]:e.NEAREST_MIPMAP_LINEAR,[be]:e.LINEAR,[Se]:e.LINEAR_MIPMAP_NEAREST,[Me]:e.LINEAR_MIPMAP_LINEAR},EP={[gn]:e.NEVER,[Tn]:e.ALWAYS,[_n]:e.LESS,[xn]:e.LEQUAL,[vn]:e.EQUAL,[Sn]:e.GEQUAL,[yn]:e.GREATER,[bn]:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===ge||e===_e||e===xe?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r=!1){const{gl:s,extensions:a}=this;if(null!==e&&void 0!==s[e])return s[e];let o=t;return t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8)),t===s.RGB&&(n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4)),t===s.RGBA&&(n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=i===Xt&&!1===r?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_INT&&(o=s.DEPTH24_STENCIL8),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:i,backend:r}=this,{currentAnisotropy:s}=r.get(t);n.texParameteri(e,n.TEXTURE_WRAP_S,TP[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,TP[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||n.texParameteri(e,n.TEXTURE_WRAP_R,TP[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,MP[t.magFilter]);const a=t.isVideoTexture||t.minFilter!==be?t.minFilter:Me;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,MP[a]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,EP[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===ge)return;if(t.minFilter!==xe&&t.minFilter!==Me)return;if(t.type===Le&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1||s!==t.anisotropy){const s=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy())),r.get(t).currentAnisotropy=t.anisotropy}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:r,width:s,height:a,depth:o}=t,l=i.utils.convert(e.format,e.colorSpace),c=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,l,c,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,h),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,e.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,e.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.NONE),this.setTextureParameters(d,e),e.isDataArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,u,s,a,o):e.isVideoTexture||n.texStorage2D(d,r,u,s,a),i.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:c,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{textureGPU:r,glTextureType:s,glFormat:a,glType:o}=i.get(t),{width:l,height:c}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(s,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,c,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:c}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===s)return;const u=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(a,s),e.isCompressedTexture){const i=e.mipmaps;for(let r=0;r0?(s&&s.isDepthTexture&&s.type===n.FLOAT&&(t=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,r,t,l,c)):n.renderbufferStorage(n.RENDERBUFFER,t,l,c),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else a&&o&&(r>0?n.renderbufferStorageMultisample(n.RENDERBUFFER,r,n.DEPTH24_STENCIL8,l,c):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,l,c),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,n,i,r){const{backend:s,gl:a}=this,{textureGPU:o,glFormat:l,glType:c}=this.backend.get(e),u=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,u),a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,o,0);const h=this._getTypedArrayType(c),d=i*r,p=d*this._getBytesPerTexel(l),m=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,m),a.bufferData(a.PIXEL_PACK_BUFFER,p,a.STREAM_READ),a.readPixels(t,n,i,r,l,c,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await s.utils._clientWaitAsync();const f=new h(d);return a.bindBuffer(a.PIXEL_PACK_BUFFER,m),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteFramebuffer(u),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.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e){const{gl:t}=this;return e===t.RGBA?4:e===t.RGB?3:e===t.ALPHA?1:void 0}}class RP{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)),t}has(e){return this.availableExtensions.includes(e)}}class CP{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 n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const NP={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"};class PP extends mP{constructor(e={}){super(e),this.isWebGLBackend=!0}init(e){super.init(e);const t=this.parameters,n=void 0!==t.context?t.context:e.domElement.getContext("webgl2");this.gl=n,this.extensions=new RP(this),this.capabilities=new CP(this),this.attributeUtils=new _P(this),this.textureUtils=new wP(this),this.state=new bP(this),this.utils=new SP(this),this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.extensions.get("EXT_color_buffer_float"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this._currentContext=null}get coordinateSystem(){return Dn}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.gl}beginRender(e){const{gl:t}=this,n=this.get(e);if(n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1),e.viewport?this.updateViewport(e):t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight),e.scissor){const{x:n,y:i,width:r,height:s}=e.scissorValue;t.scissor(n,i,r,s)}const i=e.occlusionQueryCount;i>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e).previousContext,r=e.textures;if(null!==r)for(let e=0;e0){const r=i.msaaFrameBuffer,o=e.textures;n.bindFramebuffer(t.READ_FRAMEBUFFER,r),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,s);for(let n=0;n0){if(s>this.get(e).occlusionQueryIndex){const{gl:e}=this;e.endQuery(e.ANY_SAMPLES_PASSED)}this.resolveOccludedAsync(e)}}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=0;for(let t=0;t0&&e.add(i[t]),n[t]=null,r.deleteQuery(s),a++))}a1?a.drawElementsInstanced(g,u.count,e.type,m,_):a.drawElements(g,u.count,e.type,m),t.update(h,n,1)}else{const e=d.attributes.position,n=p.count!==1/0?p.count:e.count;_>1?a.drawArraysInstanced(g,0,n,_):a.drawArrays(g,0,n),t.update(h,n,1)}a.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(e){return e.id}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,n,i,r){return this.textureUtils.copyTextureToBuffer(e,t,n,i,r)}createSampler(){}destroySampler(){}createNodeBuilder(e,t,n=null){return new uP(e,t,n)}createProgram(e){const t=this.gl,{stage:n,code:i}=e,r="fragment"===n?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(){}createRenderPipeline(e,t){const n=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:s}=i,a=n.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU;if(n.attachShader(a,o),n.attachShader(a,l),n.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const r=new Promise((t=>{const r=this.parallel,s=()=>{n.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(s)};s()}));t.push(r)}else this._completeCompile(e,i)}_completeCompile(e,t){const n=this.gl,i=this.get(t),{programGPU:r,fragmentShader:s,vertexShader:a}=i;n.getProgramParameter(r,n.LINK_STATUS),n.useProgram(r),this._setupBindings(e.getBindings(),r),this.set(t,{programGPU:r})}createComputePipeline(e,t){const n=this.gl,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:r}=e,s=n.createProgram(),a=this.get(i).shaderGPU,o=this.get(r).shaderGPU,l=r.transforms,c=[],u=[];for(let e=0;eNP[t]===e)),n=this.extensions;for(let e=0;e0){if(void 0===d){const i=[];d=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,d);const r=[],c=e.textures;for(let n=0;n,\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({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:DP,stripIndexFormat:QP},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:DP,stripIndexFormat:QP},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size,a=this.getTransferPipeline(i),o=this.getFlipYPipeline(i),l=this.device.createTexture({size:{width:r,height:s,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:wL,baseArrayLayer:n}),u=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:wL,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),d=(e,t,n)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),s=h.beginRenderPass({colorAttachments:[{view:n,loadOp:qP,storeOp:XP,clearValue:[0,0,0,0]}]});s.setPipeline(e),s.setBindGroup(0,r),s.draw(4,1,0,0),s.end()};d(a,c,u),d(o,u,c),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0){const i=this.getTransferPipeline(t.format),r=this.device.createCommandEncoder({}),s=i.getBindGroupLayout(0);let a=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:wL,baseArrayLayer:n});for(let o=1;o1&&(u=Math.pow(2,Math.floor(Math.log2(u))),2===u&&(u=4));const h=e.isRenderTargetTexture?1:u;let d=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(d|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&(d|=GPUTextureUsage.RENDER_ATTACHMENT);const p={label:e.name,size:{width:r,height:s,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:h,dimension:l,format:c,usage:d};if(e.isVideoTexture){const t=e.source.data,n=new VideoFrame(t);p.size.width=n.displayWidth,p.size.height=n.displayHeight,n.close(),i.externalTexture=t}else{if(void 0===c)return this.createDefaultTexture(e);i.texture=n.device.createTexture(p)}if(e.isRenderTargetTexture&&u>1){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=u,i.msaaTexture=n.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,n=t.get(e);n.texture.destroy(),void 0!==n.msaaTexture&&n.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else this._generateMipmaps(t.texture,t.textureDescriptorGPU)}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:n}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:n,depthOrArrayLayers:1},sampleCount:e.parameters.sampleCount,format:eL.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!0){const n=this.backend,{width:i,height:r}=n.getDrawingBufferSize(),s=this.depthTexture,a=n.get(s).texture;let o,l;if(t?(o=ke,l=De):e&&(o=Ge,l=Pe),void 0!==a){if(s.image.width===i&&s.image.height===r&&s.format===o&&s.type===l)return a;this.destroyTexture(s)}return s.name="depthBuffer",s.format=o,s.type=l,s.image.width=i,s.image.height=r,this.createTexture(s,{sampleCount:n.parameters.sampleCount,width:i,height:r}),n.get(s).texture}updateTexture(e,t){const n=this.backend.get(e),{textureDescriptorGPU:i}=n;if(!e.isRenderTargetTexture&&void 0!==i){if(e.isDataTexture||e.isData3DTexture)this._copyBufferToTexture(t.image,n.texture,i,0,e.flipY);else if(e.isDataArrayTexture)for(let r=0;r]*\s*([a-z_0-9]+)?/i,XL=/[a-z_0-9]+|<(.*?)>+/gi,jL={f32:"float"};class qL extends FR{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s}=(e=>{const t=(e=e.trim()).match(WL);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=XL.exec(n));)i.push(r);const s=[];let a=0;for(;a "+this.type:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class YL extends DR{parseFunction(e){return new qL(e)}}const $L=self.GPUShaderStage,ZL={vertex:$L?$L.VERTEX:1,fragment:$L?$L.FRAGMENT:2,compute:$L?$L.COMPUTE:4},KL={instance:!0,storageBuffer:!0},JL={"^^":"threejs_xor"},QL={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",imat2:"mat2x2",umat2:"mat2x2",bmat2:"mat2x2",mat3:"mat3x3",imat3:"mat3x3",umat3:"mat3x3",bmat3:"mat3x3",mat4:"mat4x4",imat4:"mat4x4",umat4:"mat4x4",bmat4:"mat4x4"},eI={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"threejs_mod_float",mod_vec2:"threejs_mod_vec2",mod_vec3:"threejs_mod_vec3",mod_vec4:"threejs_mod_vec4",equals_bool:"threejs_equals_bool",equals_bvec2:"threejs_equals_bvec2",equals_bvec3:"threejs_equals_bvec3",equals_bvec4:"threejs_equals_bvec4",lessThanEqual:"threejs_lessThanEqual",greaterThan:"threejs_greaterThan",inversesqrt:"inverseSqrt",bitcast:"bitcast"},tI={threejs_xor:new mv("\nfn threejs_xor( a : bool, b : bool ) -> bool {\n\n\treturn ( a || b ) && !( a && b );\n\n}\n"),lessThanEqual:new mv("\nfn threejs_lessThanEqual( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x <= b.x, a.y <= b.y, a.z <= b.z );\n\n}\n"),greaterThan:new mv("\nfn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x > b.x, a.y > b.y, a.z > b.z );\n\n}\n"),mod_float:new mv("fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new mv("fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new mv("fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new mv("fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new mv("fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new mv("fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new mv("fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new mv("fn threejs_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:new mv("\nfn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n")};class nI extends eM{constructor(e,t,n=null){super(e,t,new YL,n),this.uniformGroups={},this.builtins={}}needsColorSpaceToLinear(e){return!0===e.isVideoTexture&&e.colorSpace!==Wt}_generateTextureSample(e,t,n,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureLod(e,t,n)}_generateVideoSample(e,t,n=this.shaderStage){if("fragment"===n)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`}_generateTextureSampleLevel(e,t,n,i,r,s=this.shaderStage){return"fragment"===s&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.generateTextureLod(e,t,n,i)}generateTextureLod(e,t,n,i="0"){this._include("repeatWrapping");return`textureLoad( ${t}, threejs_repeatWrapping( ${n}, ${`textureDimensions( ${t}, 0 )`} ), i32( ${i} ) )`}generateTextureLoad(e,t,n,i,r="0u"){return i?`textureLoad( ${t}, ${n}, ${i}, ${r} )`:`textureLoad( ${t}, ${n}, ${r} )`}generateTextureStore(e,t,n,i){return`textureStore( ${t}, ${n}, ${i} )`}isUnfilterable(e){return!0===e.isDataTexture&&e.type===Le}generateTexture(e,t,n,i,r=this.shaderStage){let s=null;return s=!0===e.isVideoTexture?this._generateVideoSample(t,n,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,n,"0",i,r):this._generateTextureSample(e,t,n,i,r),s}generateTextureCompare(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`}generateTextureLevel(e,t,n,i,r,s=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,n,s):this._generateTextureSampleLevel(e,t,n,i,r,s),a}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"storageTexture"===n?t:"buffer"===n||"storageBuffer"===n?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=JL[e];return void 0!==t?(this._include(t),t):null}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let i;const a=this.bindings[n];if("texture"===t||"cubeTexture"===t||"storageTexture"===t){let s=null;if("texture"===t||"storageTexture"===t?s=new rP(r.name,r.node):"cubeTexture"===t&&(s=new sP(r.name,r.node)),s.store=!0===e.isStoreTextureNode,s.setVisibility(ZL[n]),"fragment"===n&&!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new OL(`${r.name}_sampler`,r.node);e.setVisibility(ZL[n]),a.push(e,s),i=[e,s]}else a.push(s),i=[s]}else if("buffer"===t||"storageBuffer"===t){const r=new("storageBuffer"===t?BL:JN)(e);r.setVisibility(ZL[n]),a.push(r),i=r}else{const s=e.groupNode,o=s.name,l=this.uniformGroups[n]||(this.uniformGroups[n]={});let c=l[o];void 0===c&&(c=new tP(o,s),c.setVisibility(ZL[n]),l[o]=c,a.push(c)),i=this.getNodeUniform(r,t),c.addUniform(i)}s.uniformGPU=i,"vertex"===n&&(this.bindingsOffset.fragment=a.length)}return r}isReference(e){return super.isReference(e)||"texture_2d"===e||"texture_cube"===e||"texture_depth_2d"===e||"texture_storage_2d"===e}getBuiltin(e,t,n,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:n}),t}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));return`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n\treturn ${n.result};\n\n}`}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}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")}isFlipY(){return!1}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getAttributes(e){const t=[];if("compute"===e&&this.getBuiltin("global_invocation_id","id","vec3","attribute"),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e`)}return t.join(",\n")}getStructs(e){const t=[],n=this.structs[e];for(let e=0,i=n.length;e","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];for(let r=0;r";else if(!0===t.isDataArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i="texture_depth_2d";else if(!0===t.isVideoTexture)i="texture_external";else if(!0===r.node.isStoreTextureNode){i="texture_storage_2d<"+HL(t)+", write>"}else i="texture_2d";n.push(`@binding( ${a++} ) @group( 0 ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type){const e=r.node,t=this.getType(e.bufferType),n=e.bufferCount,s=n>0?", "+n:"",o=`\t${r.name} : array< ${t}${s} >\n`,l=e.isStorageBufferNode?"storage,read_write":"uniform";i.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,o,l,a++))}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(s[t]||(s[t]={index:a++,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}for(const e in s){const t=s[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index))}let o=n.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};for(const t in e){const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n\t`),i+=`${r.code}\n\t`,e===s&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(o)n.returnType=a.nodeType,i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar output : OutputStruct;\n\n",i+=`output.color = ${r.result};\n\n\treturn output;`}}n.flow=i}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getType(e){return QL[e]||e}isAvailable(e){return!0===KL[e]}_getWGSLMethod(e){return void 0!==tI[e]&&this._include(e),eI[e]}_include(e){const t=tI[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\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\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// system\nvar instanceIndex : u32;\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x;\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,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}class iI{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=eL.Depth24PlusStencil8:e.depth&&(t=eL.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).texture.format}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):eL.BGRA8Unorm,t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?LP:e.isLineSegments||e.isMesh&&!0===t.wireframe?IP:e.isLine?UP:e.isMesh?OP:void 0}getSampleCount(e){return null!==e.textures?e.sampleCount:this.backend.parameters.sampleCount}}const rI=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),sI=new Map([[fs,["float16"]]]),aI=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class oI{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const e=i.device;let a=n.array;if((n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&3===n.itemSize){n.itemSize=4,a=new a.constructor(4*n.count);for(let e=0;e1&&(T=Math.pow(2,Math.floor(Math.log2(T))),2===T&&(T=4));const M={vertex:Object.assign({},v,{buffers:p}),fragment:Object.assign({},x,{targets:_}),primitive:y,depthStencil:{format:S,depthWriteEnabled:i.depthWrite,depthCompare:b,stencilFront:f,stencilBack:{},stencilReadMask:i.stencilFuncMask,stencilWriteMask:i.stencilWriteMask},multisample:{count:T,alphaToCoverageEnabled:i.alphaToCoverage},layout:c.createPipelineLayout({bindGroupLayouts:[d.layout]})};if(null===t)h.pipeline=c.createRenderPipeline(M);else{const e=new Promise((e=>{c.createRenderPipelineAsync(M).then((t=>{h.pipeline=t,e()}))}));t.push(e)}}createComputePipeline(e,t){const n=this.backend,i=n.device,r=n.get(e.computeProgram).module,s=n.get(e),a=n.get(t);s.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:[a.layout]})})}_getBlending(e){let t,n;const i=e.blending;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:aL.One,r=null!==e.blendDstAlpha?e.blendDstAlpha:aL.Zero,s=null!==e.blendEquationAlpha?e.blendEquationAlpha:aL.Add;t={srcFactor:this._getBlendFactor(e.blendSrc),dstFactor:this._getBlendFactor(e.blendDst),operation:this._getBlendOperation(e.blendEquation)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(r),operation:this._getBlendOperation(s)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:oL},n={srcFactor:r,dstFactor:s,operation:oL}};if(e.premultipliedAlpha)switch(i){case 1:r(aL.SrcAlpha,aL.OneMinusSrcAlpha,aL.One,aL.OneMinusSrcAlpha);break;case 2:r(aL.SrcAlpha,aL.One,aL.One,aL.One);break;case 3:r(aL.Zero,aL.OneMinusSrc,aL.Zero,aL.One);break;case 4:r(aL.Zero,aL.Src,aL.Zero,aL.SrcAlpha)}else switch(i){case 1:r(aL.SrcAlpha,aL.OneMinusSrcAlpha,aL.One,aL.OneMinusSrcAlpha);break;case 2:r(aL.SrcAlpha,aL.One,aL.SrcAlpha,aL.One);break;case 3:r(aL.Zero,aL.OneMinusSrc,aL.Zero,aL.One);break;case 4:r(aL.Zero,aL.Src,aL.Zero,aL.Src)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n}}_getBlendFactor(e){let t;switch(e){case E:t=aL.Zero;break;case A:t=aL.One;break;case w:t=aL.Src;break;case R:t=aL.OneMinusSrc;break;case C:t=aL.SrcAlpha;break;case N:t=aL.OneMinusSrcAlpha;break;case I:t=aL.Dst;break;case U:t=aL.OneMinusDstColor;break;case P:t=aL.DstAlpha;break;case L:t=aL.OneMinusDstAlpha;break;case O:t=aL.SrcAlphaSaturated;break;case 211:t=aL.Constant;break;case 212:t=aL.OneMinusConstant}return t}_getStencilCompare(e){let t;switch(e.stencilFunc){case 512:t=FP;break;case fn:t=WP;break;case 513:t=BP;break;case 515:t=zP;break;case 514:t=VP;break;case 518:t=HP;break;case 516:t=GP;break;case 517:t=kP}return t}_getStencilOperation(e){let t;switch(e){case en:t=mL;break;case 0:t=fL;break;case 7681:t=gL;break;case 5386:t=_L;break;case 7682:t=vL;break;case 7683:t=xL;break;case 34055:t=yL;break;case 34056:t=bL}return t}_getBlendOperation(e){let t;switch(e){case y:t=oL;break;case b:t=lL;break;case S:t=cL;break;case T:t=uL;break;case M:t=hL}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?JP:QP),n.side){case h:i.frontFace=YP,i.cullMode=KP;break;case d:i.frontFace=YP,i.cullMode=ZP;break;case 2:i.frontFace=YP,i.cullMode=$P}return i}_getColorWriteMask(e){return!0===e.colorWrite?pL:dL}_getDepthCompare(e){let t;if(!1===e.depthTest)t=WP;else{switch(e.depthFunc){case 0:t=FP;break;case 1:t=WP;break;case 2:t=BP;break;case 3:t=zP;break;case 4:t=VP;break;case 5:t=HP;break;case 6:t=GP;break;case 7:t=kP}}return t}}class uI extends mP{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.antialias=!0===e.antialias,!0===this.parameters.antialias?this.parameters.sampleCount=void 0===e.sampleCount?4:e.sampleCount:this.parameters.sampleCount=1,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.adapter=null,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new iI(this),this.attributeUtils=new oI(this),this.bindingUtils=new lI(this),this.pipelineUtils=new cI(this),this.textureUtils=new kL(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters,n={powerPreference:t.powerPreference},i=await navigator.gpu.requestAdapter(n);if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(IL),s=[];for(const e of r)i.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits},o=await i.requestDevice(a),l=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.adapter=i,this.device=o,this.context=l;const c=t.alpha?"premultiplied":"opaque";this.context.configure({device:this.device,format:eL.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:c}),this.updateSize()}get coordinateSystem(){return Fn}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;const t=this.parameters.antialias;if(null===e){const n=this.renderer;e={colorAttachments:[{view:null}],depthStencilAttachment:{view:this.textureUtils.getDepthBuffer(n.depth,n.stencil).createView()}};const i=e.colorAttachments[0];!0===t?i.view=this.colorBuffer.createView():i.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const n=e.colorAttachments[0];return!0===t?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),e}_getRenderPassDescriptor(e){const t=e.renderTarget,n=this.get(t);let i=n.descriptors;void 0===i&&(i=[],n.descriptors=i),n.width===t.width&&n.height===t.height&&n.activeMipmapLevel===t.activeMipmapLevel&&n.samples===t.samples||(i.length=0);let r=i[e.activeCubeFace];if(void 0===r){const s=e.textures,a=[];for(let t=0;t0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:i}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e),this.initTimestampQuery(e,s),s.occlusionQuerySet=r;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;nt.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),n>0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(this.prepareTimestampBuffer(e,t.encoder),this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e 1; } - deserialize( data ) { - - super.deserialize( data ); - - this.nodeType = data.nodeType; - this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; - - this.precision = data.precision || null; - - if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + build( builder, output ) { - } + const buildStage = builder.getBuildStage(); - generate( /*builder, output*/ ) { + if ( buildStage === 'generate' ) { - } + const type = builder.getVectorType( this.getNodeType( builder, output ) ); + const nodeData = builder.getDataFromNode( this ); -} + if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { -addNodeClass( 'InputNode', InputNode ); + return builder.format( nodeData.propertyName, type, output ); -class UniformGroupNode extends Node { + } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - constructor( name, shared = false ) { + const snippet = super.build( builder, type ); - super( 'string' ); + const nodeVar = builder.getVarFromNode( this, null, type ); + const propertyName = builder.getPropertyName( nodeVar ); - this.name = name; - this.version = 0; + builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - this.shared = shared; + nodeData.snippet = snippet; + nodeData.propertyName = propertyName; - this.isUniformGroup = true; + return builder.format( nodeData.propertyName, type, output ); - } + } - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + return super.build( builder, output ); } } -const uniformGroup = ( name ) => new UniformGroupNode( name ); -const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); - -const frameGroup = sharedUniformGroup( 'frame' ); -const renderGroup = sharedUniformGroup( 'render' ); -const objectGroup = uniformGroup( 'object' ); - -addNodeClass( 'UniformGroupNode', UniformGroupNode ); +addNodeClass( 'TempNode', TempNode ); class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute @@ -2344,66 +2535,11 @@ class ConvertNode extends Node { addNodeClass( 'ConvertNode', ConvertNode ); -class TempNode extends Node { +class JoinNode extends TempNode { - constructor( type ) { + constructor( nodes = [], nodeType = null ) { - super( type ); - - this.isTempNode = true; - - } - - hasDependencies( builder ) { - - return builder.getDataFromNode( this ).dependenciesCount > 1; - - } - - build( builder, output ) { - - const buildStage = builder.getBuildStage(); - - if ( buildStage === 'generate' ) { - - const type = builder.getVectorType( this.getNodeType( builder, output ) ); - const nodeData = builder.getDataFromNode( this ); - - if ( builder.context.tempRead !== false && nodeData.propertyName !== undefined ) { - - return builder.format( nodeData.propertyName, type, output ); - - } else if ( builder.context.tempWrite !== false && type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) { - - const snippet = super.build( builder, type ); - - const nodeVar = builder.getVarFromNode( this, null, type ); - const propertyName = builder.getPropertyName( nodeVar ); - - builder.addLineFlowCode( `${propertyName} = ${snippet}` ); - - nodeData.snippet = snippet; - nodeData.propertyName = propertyName; - - return builder.format( nodeData.propertyName, type, output ); - - } - - } - - return super.build( builder, output ); - - } - -} - -addNodeClass( 'TempNode', TempNode ); - -class JoinNode extends TempNode { - - constructor( nodes = [], nodeType = null ) { - - super( nodeType ); + super( nodeType ); this.nodes = nodes; @@ -2426,7 +2562,7 @@ class JoinNode extends TempNode { const type = this.getNodeType( builder ); const nodes = this.nodes; - const primitiveType = builder.getPrimitiveType( type ); + const primitiveType = builder.getComponentType( type ); const snippetValues = []; @@ -2434,7 +2570,7 @@ class JoinNode extends TempNode { let inputSnippet = input.build( builder ); - const inputPrimitiveType = builder.getPrimitiveType( input.getNodeType( builder ) ); + const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) ); if ( inputPrimitiveType !== primitiveType ) { @@ -2485,15 +2621,15 @@ class SplitNode extends Node { } - getPrimitiveType( builder ) { + getComponentType( builder ) { - return builder.getPrimitiveType( this.node.getNodeType( builder ) ); + return builder.getComponentType( this.node.getNodeType( builder ) ); } getNodeType( builder ) { - return builder.getTypeFromLength( this.components.length, this.getPrimitiveType( builder ) ); + return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) ); } @@ -2514,7 +2650,7 @@ class SplitNode extends Node { // needed expand the input node - type = builder.getTypeFromLength( this.getVectorLength(), this.getPrimitiveType( builder ) ); + type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) ); } @@ -2621,6 +2757,83 @@ class SetNode extends TempNode { addNodeClass( 'SetNode', SetNode ); +class InputNode extends Node { + + constructor( value, nodeType = null ) { + + super( nodeType ); + + this.isInputNode = true; + + this.value = value; + this.precision = null; + + } + + getNodeType( /*builder*/ ) { + + if ( this.nodeType === null ) { + + return getValueType( this.value ); + + } + + return this.nodeType; + + } + + getInputType( builder ) { + + return this.getNodeType( builder ); + + } + + setPrecision( precision ) { + + this.precision = precision; + + return this; + + } + + serialize( data ) { + + super.serialize( data ); + + data.value = this.value; + + if ( this.value && this.value.toArray ) data.value = this.value.toArray(); + + data.valueType = getValueType( this.value ); + data.nodeType = this.nodeType; + + if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value ); + + data.precision = this.precision; + + } + + deserialize( data ) { + + super.deserialize( data ); + + this.nodeType = data.nodeType; + this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value; + + this.precision = data.precision || null; + + if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value ); + + } + + generate( /*builder, output*/ ) { + + } + +} + +addNodeClass( 'InputNode', InputNode ); + class ConstNode extends InputNode { constructor( value, nodeType = null ) { @@ -3206,6 +3419,11 @@ const ivec4 = new ConvertType( 'ivec4' ); const uvec4 = new ConvertType( 'uvec4' ); const bvec4 = new ConvertType( 'bvec4' ); +const mat2 = new ConvertType( 'mat2' ); +const imat2 = new ConvertType( 'imat2' ); +const umat2 = new ConvertType( 'umat2' ); +const bmat2 = new ConvertType( 'bmat2' ); + const mat3 = new ConvertType( 'mat3' ); const imat3 = new ConvertType( 'imat3' ); const umat3 = new ConvertType( 'umat3' ); @@ -3236,6 +3454,10 @@ addNodeElement( 'vec4', vec4 ); addNodeElement( 'ivec4', ivec4 ); addNodeElement( 'uvec4', uvec4 ); addNodeElement( 'bvec4', bvec4 ); +addNodeElement( 'mat2', mat2 ); +addNodeElement( 'imat2', imat2 ); +addNodeElement( 'umat2', umat2 ); +addNodeElement( 'bmat2', bmat2 ); addNodeElement( 'mat3', mat3 ); addNodeElement( 'imat3', imat3 ); addNodeElement( 'umat3', umat3 ); @@ -3256,159 +3478,118 @@ const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node addNodeElement( 'element', element ); addNodeElement( 'convert', convert ); -class UniformNode extends InputNode { - - constructor( value, nodeType = null ) { - - super( value, nodeType ); - - this.isUniformNode = true; - - this.groupNode = objectGroup; - - } +class AssignNode extends TempNode { - setGroup( group ) { + constructor( targetNode, sourceNode ) { - this.groupNode = group; + super(); - return this; + this.targetNode = targetNode; + this.sourceNode = sourceNode; } - getGroup() { + hasDependencies() { - return this.groupNode; + return false; } - getUniformHash( builder ) { + getNodeType( builder, output ) { - return this.getHash( builder ); + return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; } - generate( builder, output ) { - - const type = this.getNodeType( builder ); - - const hash = this.getUniformHash( builder ); + needsSplitAssign( builder ) { - let sharedNode = builder.getNodeFromHash( hash ); + const { targetNode } = this; - if ( sharedNode === undefined ) { + if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) { - builder.setHashNode( this, hash ); + const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) ); + const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components; - sharedNode = this; + return assignDiferentVector; } - const sharedNodeType = sharedNode.getInputType( builder ); - - const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); - const propertyName = builder.getPropertyName( nodeUniform ); - - if ( builder.context.label !== undefined ) delete builder.context.label; - - return builder.format( propertyName, type, output ); - - } - -} - -const uniform = ( arg1, arg2 ) => { - - const nodeType = getConstNodeType( arg2 || arg1 ); - - // @TODO: get ConstNode from .traverse() in the future - const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; - - return nodeObject( new UniformNode( value, nodeType ) ); - -}; - -addNodeClass( 'UniformNode', UniformNode ); - -class ArrayUniformNode extends UniformNode { - - constructor( nodes = [] ) { - - super(); - - this.isArrayUniformNode = true; - - this.nodes = nodes; + return false; } - getNodeType( builder ) { + generate( builder, output ) { - return this.nodes[ 0 ].getNodeType( builder ); + const { targetNode, sourceNode } = this; - } + const needsSplitAssign = this.needsSplitAssign( builder ); -} + const targetType = targetNode.getNodeType( builder ); -addNodeClass( 'ArrayUniformNode', ArrayUniformNode ); + const target = targetNode.context( { assign: true } ).build( builder ); + const source = sourceNode.build( builder, targetType ); -class AssignNode extends TempNode { + const sourceType = sourceNode.getNodeType( builder ); - constructor( targetNode, sourceNode ) { + const nodeData = builder.getDataFromNode( this ); - super(); + // - this.targetNode = targetNode; - this.sourceNode = sourceNode; + let snippet; - } + if ( nodeData.initialized === true ) { - hasDependencies() { + if ( output !== 'void' ) { - return false; + snippet = target; - } + } - getNodeType( builder, output ) { + } else if ( needsSplitAssign ) { - return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void'; + const sourceVar = builder.getVarFromNode( this, null, targetType ); + const sourceProperty = builder.getPropertyName( sourceVar ); - } + builder.addLineFlowCode( `${ sourceProperty } = ${ source }` ); - generate( builder, output ) { + const targetRoot = targetNode.node.context( { assign: true } ).build( builder ); - const targetNode = this.targetNode; - const sourceNode = this.sourceNode; + for ( let i = 0; i < targetNode.components.length; i ++ ) { - const targetType = targetNode.getNodeType( builder ); + const component = targetNode.components[ i ]; - const target = targetNode.build( builder ); - const source = sourceNode.build( builder, targetType ); + builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` ); - const snippet = `${ target } = ${ source }`; + } - if ( output === 'void' ) { + if ( output !== 'void' ) { - builder.addLineFlowCode( snippet ); + snippet = target; - return; + } } else { - const sourceType = sourceNode.getNodeType( builder ); + snippet = `${ target } = ${ source }`; - if ( sourceType === 'void' ) { + if ( output === 'void' || sourceType === 'void' ) { builder.addLineFlowCode( snippet ); - return target; + if ( output !== 'void' ) { - } + snippet = target; + + } - return builder.format( snippet, targetType, output ); + } } + nodeData.initialized = true; + + return builder.format( snippet, targetType, output ); + } } @@ -4164,6 +4345,12 @@ class CodeNode extends Node { } + isGlobal() { + + return true; + + } + setIncludes( includes ) { this.includes = includes; @@ -4348,19 +4535,125 @@ const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' ); addNodeClass( 'FunctionNode', FunctionNode ); -class UVNode extends AttributeNode { +class UniformGroupNode extends Node { - constructor( index = 0 ) { + constructor( name, shared = false ) { - super( null, 'vec2' ); + super( 'string' ); - this.isUVNode = true; + this.name = name; + this.version = 0; - this.index = index; + this.shared = shared; + + this.isUniformGroup = true; } - getAttributeName( /*builder*/ ) { + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +const uniformGroup = ( name ) => new UniformGroupNode( name ); +const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true ); + +const frameGroup = sharedUniformGroup( 'frame' ); +const renderGroup = sharedUniformGroup( 'render' ); +const objectGroup = uniformGroup( 'object' ); + +addNodeClass( 'UniformGroupNode', UniformGroupNode ); + +class UniformNode extends InputNode { + + constructor( value, nodeType = null ) { + + super( value, nodeType ); + + this.isUniformNode = true; + + this.groupNode = objectGroup; + + } + + setGroup( group ) { + + this.groupNode = group; + + return this; + + } + + getGroup() { + + return this.groupNode; + + } + + getUniformHash( builder ) { + + return this.getHash( builder ); + + } + + generate( builder, output ) { + + const type = this.getNodeType( builder ); + + const hash = this.getUniformHash( builder ); + + let sharedNode = builder.getNodeFromHash( hash ); + + if ( sharedNode === undefined ) { + + builder.setHashNode( this, hash ); + + sharedNode = this; + + } + + const sharedNodeType = sharedNode.getInputType( builder ); + + const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, builder.context.label ); + const propertyName = builder.getPropertyName( nodeUniform ); + + if ( builder.context.label !== undefined ) delete builder.context.label; + + return builder.format( propertyName, type, output ); + + } + +} + +const uniform = ( arg1, arg2 ) => { + + const nodeType = getConstNodeType( arg2 || arg1 ); + + // @TODO: get ConstNode from .traverse() in the future + const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1; + + return nodeObject( new UniformNode( value, nodeType ) ); + +}; + +addNodeClass( 'UniformNode', UniformNode ); + +class UVNode extends AttributeNode { + + constructor( index = 0 ) { + + super( null, 'vec2' ); + + this.isUVNode = true; + + this.index = index; + + } + + getAttributeName( /*builder*/ ) { const index = this.index; @@ -4455,7 +4748,7 @@ class OperatorNode extends TempNode { const bNode = this.bNode; const typeA = aNode.getNodeType( builder ); - const typeB = bNode.getNodeType( builder ); + const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( typeA === 'void' || typeB === 'void' ) { @@ -4465,11 +4758,11 @@ class OperatorNode extends TempNode { return typeA; - } else if ( op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { + } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { return builder.getIntegerType( typeA ); - } else if ( op === '==' || op === '&&' || op === '||' || op === '^^' ) { + } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) { return 'bool'; @@ -4526,7 +4819,7 @@ class OperatorNode extends TempNode { if ( type !== 'void' ) { typeA = aNode.getNodeType( builder ); - typeB = bNode.getNodeType( builder ); + typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null; if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) { @@ -4572,7 +4865,7 @@ class OperatorNode extends TempNode { } const a = aNode.build( builder, typeA ); - const b = bNode.build( builder, typeB ); + const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null; const outputLength = builder.getTypeLength( output ); const fnOpSnippet = builder.getFunctionOperator( op ); @@ -4595,6 +4888,10 @@ class OperatorNode extends TempNode { return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output ); + } else if ( op === '!' || op === '~' ) { + + return builder.format( `(${op}${a})`, typeA, output ); + } else if ( fnOpSnippet ) { return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output ); @@ -4652,8 +4949,10 @@ const lessThanEqual = nodeProxy( OperatorNode, '<=' ); const greaterThanEqual = nodeProxy( OperatorNode, '>=' ); const and = nodeProxy( OperatorNode, '&&' ); const or = nodeProxy( OperatorNode, '||' ); +const not = nodeProxy( OperatorNode, '!' ); const xor = nodeProxy( OperatorNode, '^^' ); const bitAnd = nodeProxy( OperatorNode, '&' ); +const bitNot = nodeProxy( OperatorNode, '~' ); const bitOr = nodeProxy( OperatorNode, '|' ); const bitXor = nodeProxy( OperatorNode, '^' ); const shiftLeft = nodeProxy( OperatorNode, '<<' ); @@ -4672,8 +4971,10 @@ addNodeElement( 'lessThanEqual', lessThanEqual ); addNodeElement( 'greaterThanEqual', greaterThanEqual ); addNodeElement( 'and', and ); addNodeElement( 'or', or ); +addNodeElement( 'not', not ); addNodeElement( 'xor', xor ); addNodeElement( 'bitAnd', bitAnd ); +addNodeElement( 'bitNot', bitNot ); addNodeElement( 'bitOr', bitOr ); addNodeElement( 'bitXor', bitXor ); addNodeElement( 'shiftLeft', shiftLeft ); @@ -4735,6 +5036,14 @@ class MathNode extends TempNode { return 'vec3'; + } else if ( method === MathNode.ALL ) { + + return 'bool'; + + } else if ( method === MathNode.EQUALS ) { + + return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' ); + } else if ( method === MathNode.MOD ) { return this.aNode.getNodeType( builder ); @@ -4873,6 +5182,10 @@ class MathNode extends TempNode { // 1 input +MathNode.ALL = 'all'; +MathNode.ANY = 'any'; +MathNode.EQUALS = 'equals'; + MathNode.RADIANS = 'radians'; MathNode.DEGREES = 'degrees'; MathNode.EXP = 'exp'; @@ -4929,6 +5242,12 @@ MathNode.FACEFORWARD = 'faceforward'; const EPSILON = float( 1e-6 ); const INFINITY = float( 1e6 ); +const PI = float( Math.PI ); +const PI2 = float( Math.PI * 2 ); + +const all = nodeProxy( MathNode, MathNode.ALL ); +const any = nodeProxy( MathNode, MathNode.ANY ); +const equals = nodeProxy( MathNode, MathNode.EQUALS ); const radians = nodeProxy( MathNode, MathNode.RADIANS ); const degrees = nodeProxy( MathNode, MathNode.DEGREES ); @@ -4978,6 +5297,7 @@ const pow4 = nodeProxy( MathNode, MathNode.POW, 4 ); const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ); const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) ); +const lengthSq = ( a ) => dot( a, a ); const mix = nodeProxy( MathNode, MathNode.MIX ); const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) ); const saturate = ( value ) => clamp( value ); @@ -4988,6 +5308,10 @@ const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD ); const mixElement = ( t, e1, e2 ) => mix( e1, e2, t ); const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x ); +addNodeElement( 'all', all ); +addNodeElement( 'any', any ); +addNodeElement( 'equals', equals ); + addNodeElement( 'radians', radians ); addNodeElement( 'degrees', degrees ); addNodeElement( 'exp', exp ); @@ -5009,6 +5333,7 @@ addNodeElement( 'atan', atan ); addNodeElement( 'abs', abs ); addNodeElement( 'sign', sign ); addNodeElement( 'length', length ); +addNodeElement( 'lengthSq', lengthSq ); addNodeElement( 'negate', negate ); addNodeElement( 'oneMinus', oneMinus ); addNodeElement( 'dFdx', dFdx ); @@ -5262,7 +5587,7 @@ class TextureNode extends UniformNode { } - updateReference( /*frame*/ ) { + setReference( /*state*/ ) { return this.value; @@ -5571,232 +5896,434 @@ addNodeElement( 'texture', texture ); addNodeClass( 'TextureNode', TextureNode ); -class ReferenceNode extends Node { - - constructor( property, uniformType, object = null ) { +class BufferNode extends UniformNode { - super(); + constructor( value, bufferType, bufferCount = 0 ) { - this.property = property; - this.index = null; + super( value, bufferType ); - this.uniformType = uniformType; + this.isBufferNode = true; - this.object = object; - this.reference = null; + this.bufferType = bufferType; + this.bufferCount = bufferCount; - this.node = null; + } - this.updateType = NodeUpdateType.OBJECT; + getInputType( /*builder*/ ) { - this.setNodeType( uniformType ); + return 'buffer'; } - updateReference( frame ) { +} - this.reference = this.object !== null ? this.object : frame.object; +const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - return this.reference; +addNodeClass( 'BufferNode', BufferNode ); - } +class UniformsElementNode extends ArrayElementNode { - setIndex( index ) { + constructor( arrayBuffer, indexNode ) { - this.index = index; + super( arrayBuffer, indexNode ); - return this; + this.isArrayBufferElementNode = true; } - getIndex() { + getNodeType( builder ) { - return this.index; + return this.node.getElementType( builder ); } - setNodeType( uniformType ) { + generate( builder ) { - let node = null; + const snippet = super.generate( builder ); + const type = this.getNodeType(); - if ( uniformType === 'texture' ) { + return builder.format( snippet, 'vec4', type ); - node = texture( null ); + } - } else { +} - node = uniform( uniformType ); +class UniformsNode extends BufferNode { - } + constructor( value, elementType = null ) { - this.node = node; + super( null, 'vec4' ); - } + this.array = value; + this.elementType = elementType; - getNodeType( builder ) { + this._elementType = null; + this._elementLength = 0; - return this.node.getNodeType( builder ); + this.updateType = NodeUpdateType.RENDER; - } + this.isArrayBufferNode = true; - update( /*frame*/ ) { + } - let value = this.reference[ this.property ]; + getElementType() { - if ( this.index !== null ) { + return this.elementType || this._elementType; - value = value[ this.index ]; + } - } + getElementLength() { - this.node.value = value; + return this._elementLength; } - setup( /*builder*/ ) { + update( /*frame*/ ) { - return this.node; + const { array, value } = this; - } + const elementLength = this.getElementLength(); + const elementType = this.getElementType(); -} + if ( elementLength === 1 ) { -const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); -const referenceIndex = ( name, index, type, object ) => nodeObject( new ReferenceNode( name, type, object ).setIndex( index ) ); + for ( let i = 0; i < array.length; i ++ ) { -addNodeClass( 'ReferenceNode', ReferenceNode ); + const index = i * 4; -class MaterialReferenceNode extends ReferenceNode { + value[ index ] = array[ i ]; - constructor( property, inputType, material = null ) { + } - super( property, inputType, material ); + } else if ( elementType === 'color' ) { - this.material = material; + for ( let i = 0; i < array.length; i ++ ) { - //this.updateType = NodeUpdateType.RENDER; + const index = i * 4; + const vector = array[ i ]; - } + value[ index ] = vector.r; + value[ index + 1 ] = vector.g; + value[ index + 2 ] = vector.b || 0; + //value[ index + 3 ] = vector.a || 0; - /*setNodeType( node ) { + } - super.setNodeType( node ); + } else { - this.node.groupNode = renderGroup; + for ( let i = 0; i < array.length; i ++ ) { - }*/ + const index = i * 4; + const vector = array[ i ]; - updateReference( frame ) { + value[ index ] = vector.x; + value[ index + 1 ] = vector.y; + value[ index + 2 ] = vector.z || 0; + value[ index + 3 ] = vector.w || 0; - this.reference = this.material !== null ? this.material : frame.material; + } - return this.reference; + } } setup( builder ) { - const material = this.material !== null ? this.material : builder.material; + const length = this.array.length; - this.node.value = material[ this.property ]; + this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType; + this._elementLength = builder.getTypeLength( this._elementType ); + + this.value = new Float32Array( length * 4 ); + this.bufferCount = length; return super.setup( builder ); } -} - -const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); + element( indexNode ) { -addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); + return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) ); -class Object3DNode extends Node { + } - constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { +} - super(); +const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) ); - this.scope = scope; - this.object3d = object3d; +addNodeClass( 'UniformsNode', UniformsNode ); - this.updateType = NodeUpdateType.OBJECT; +class ReferenceElementNode extends ArrayElementNode { - this._uniformNode = new UniformNode( null ); + constructor( referenceNode, indexNode ) { - } + super( referenceNode, indexNode ); - getNodeType() { + this.referenceNode = referenceNode; - const scope = this.scope; + this.isReferenceElementNode = true; - if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + } - return 'mat4'; + getNodeType() { - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + return this.referenceNode.uniformType; - return 'mat3'; + } - } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + generate( builder ) { - return 'vec3'; + const snippet = super.generate( builder ); + const arrayType = this.referenceNode.getNodeType(); + const elementType = this.getNodeType(); - } + return builder.format( snippet, arrayType, elementType ); } - update( frame ) { +} - const object = this.object3d; - const uniformNode = this._uniformNode; - const scope = this.scope; +class ReferenceNode extends Node { - if ( scope === Object3DNode.VIEW_MATRIX ) { + constructor( property, uniformType, object = null, count = null ) { - uniformNode.value = object.modelViewMatrix; + super(); - } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + this.property = property; + this.uniformType = uniformType; + this.object = object; + this.count = count; - uniformNode.value = object.normalMatrix; + this.properties = property.split( '.' ); + this.reference = null; + this.node = null; - } else if ( scope === Object3DNode.WORLD_MATRIX ) { + this.updateType = NodeUpdateType.OBJECT; - uniformNode.value = object.matrixWorld; + } - } else if ( scope === Object3DNode.POSITION ) { + element( indexNode ) { - uniformNode.value = uniformNode.value || new Vector3(); + return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) ); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } - } else if ( scope === Object3DNode.SCALE ) { + setNodeType( uniformType ) { - uniformNode.value = uniformNode.value || new Vector3(); + let node = null; - uniformNode.value.setFromMatrixScale( object.matrixWorld ); + if ( this.count !== null ) { - } else if ( scope === Object3DNode.DIRECTION ) { + node = buffer( null, uniformType, this.count ); - uniformNode.value = uniformNode.value || new Vector3(); + } else if ( Array.isArray( this.getValueFromReference() ) ) { - object.getWorldDirection( uniformNode.value ); + node = uniforms( null, uniformType ); - } else if ( scope === Object3DNode.VIEW_POSITION ) { + } else if ( uniformType === 'texture' ) { - const camera = frame.camera; + node = texture( null ); - uniformNode.value = uniformNode.value || new Vector3(); - uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + } else { - uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); + node = uniform( null, uniformType ); } + this.node = node; + } - generate( builder ) { + getNodeType( builder ) { - const scope = this.scope; + return this.node.getNodeType( builder ); + + } + + getValueFromReference( object = this.reference ) { + + const { properties } = this; + + let value = object[ properties[ 0 ] ]; + + for ( let i = 1; i < properties.length; i ++ ) { + + value = value[ properties[ i ] ]; + + } + + return value; + + } + + setReference( state ) { + + this.reference = this.object !== null ? this.object : state.object; + + return this.reference; + + } + + setup() { + + this.updateValue(); + + return this.node; + + } + + update( /*frame*/ ) { + + this.updateValue(); + + } + + updateValue() { + + if ( this.node === null ) this.setNodeType( this.uniformType ); + + const value = this.getValueFromReference(); + + if ( Array.isArray( value ) ) { + + this.node.array = value; + + } else { + + this.node.value = value; + + } + + } + +} + +const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) ); +const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) ); + +addNodeClass( 'ReferenceNode', ReferenceNode ); + +class MaterialReferenceNode extends ReferenceNode { + + constructor( property, inputType, material = null ) { + + super( property, inputType, material ); + + this.material = material; + + //this.updateType = NodeUpdateType.RENDER; + + } + + /*setNodeType( node ) { + + super.setNodeType( node ); + + this.node.groupNode = renderGroup; + + }*/ + + setReference( state ) { + + this.reference = this.material !== null ? this.material : state.material; + + return this.reference; + + } + +} + +const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) ); + +addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode ); + +class Object3DNode extends Node { + + constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) { + + super(); + + this.scope = scope; + this.object3d = object3d; + + this.updateType = NodeUpdateType.OBJECT; + + this._uniformNode = new UniformNode( null ); + + } + + getNodeType() { + + const scope = this.scope; + + if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { + + return 'mat4'; + + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + + return 'mat3'; + + } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) { + + return 'vec3'; + + } + + } + + update( frame ) { + + const object = this.object3d; + const uniformNode = this._uniformNode; + const scope = this.scope; + + if ( scope === Object3DNode.VIEW_MATRIX ) { + + uniformNode.value = object.modelViewMatrix; + + } else if ( scope === Object3DNode.NORMAL_MATRIX ) { + + uniformNode.value = object.normalMatrix; + + } else if ( scope === Object3DNode.WORLD_MATRIX ) { + + uniformNode.value = object.matrixWorld; + + } else if ( scope === Object3DNode.POSITION ) { + + uniformNode.value = uniformNode.value || new Vector3(); + + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + + } else if ( scope === Object3DNode.SCALE ) { + + uniformNode.value = uniformNode.value || new Vector3(); + + uniformNode.value.setFromMatrixScale( object.matrixWorld ); + + } else if ( scope === Object3DNode.DIRECTION ) { + + uniformNode.value = uniformNode.value || new Vector3(); + + object.getWorldDirection( uniformNode.value ); + + } else if ( scope === Object3DNode.VIEW_POSITION ) { + + const camera = frame.camera; + + uniformNode.value = uniformNode.value || new Vector3(); + uniformNode.value.setFromMatrixPosition( object.matrixWorld ); + + uniformNode.value.applyMatrix4( camera.matrixWorldInverse ); + + } + + } + + generate( builder ) { + + const scope = this.scope; if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) { @@ -5870,7 +6397,7 @@ class CameraNode extends Object3DNode { const scope = this.scope; - if ( scope === CameraNode.PROJECTION_MATRIX ) { + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { return 'mat4'; @@ -5900,6 +6427,10 @@ class CameraNode extends Object3DNode { uniformNode.value = camera.projectionMatrix; + } else if ( scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { + + uniformNode.value = camera.projectionMatrixInverse; + } else if ( scope === CameraNode.NEAR ) { uniformNode.value = camera.near; @@ -5926,7 +6457,7 @@ class CameraNode extends Object3DNode { const scope = this.scope; - if ( scope === CameraNode.PROJECTION_MATRIX ) { + if ( scope === CameraNode.PROJECTION_MATRIX || scope === CameraNode.PROJECTION_MATRIX_INVERSE ) { this._uniformNode.nodeType = 'mat4'; @@ -5943,11 +6474,13 @@ class CameraNode extends Object3DNode { } CameraNode.PROJECTION_MATRIX = 'projectionMatrix'; +CameraNode.PROJECTION_MATRIX_INVERSE = 'projectionMatrixInverse'; CameraNode.NEAR = 'near'; CameraNode.FAR = 'far'; CameraNode.LOG_DEPTH = 'logDepth'; -const cameraProjectionMatrix = label( nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ), 'projectionMatrix' ); +const cameraProjectionMatrix = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX ); +const cameraProjectionMatrixInverse = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX_INVERSE ); const cameraNear = nodeImmutable( CameraNode, CameraNode.NEAR ); const cameraFar = nodeImmutable( CameraNode, CameraNode.FAR ); const cameraLogDepth = nodeImmutable( CameraNode, CameraNode.LOG_DEPTH ); @@ -6295,11 +6828,11 @@ class MaterialNode extends Node { } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) { - const iridescenceThicknessMaximum = reference( 1, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange ); if ( material.iridescenceThicknessMap ) { - const iridescenceThicknessMinimum = reference( 0, 'float', material.iridescenceThicknessRange ); + const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange ); node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum ); @@ -6568,12 +7101,14 @@ class BufferAttributeNode extends InputNode { const nodeType = this.getNodeType( builder ); - const nodeUniform = builder.getBufferAttributeFromNode( this, nodeType ); - const propertyName = builder.getPropertyName( nodeUniform ); + const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType ); + const propertyName = builder.getPropertyName( nodeAttribute ); let output = null; - if ( builder.shaderStage === 'vertex' ) { + if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) { + + this.name = propertyName; output = propertyName; @@ -6686,31 +7221,6 @@ const instance = nodeProxy( InstanceNode ); addNodeClass( 'InstanceNode', InstanceNode ); -class BufferNode extends UniformNode { - - constructor( value, bufferType, bufferCount = 0 ) { - - super( value, bufferType ); - - this.isBufferNode = true; - - this.bufferType = bufferType; - this.bufferCount = bufferCount; - - } - - getInputType( /*builder*/ ) { - - return 'buffer'; - - } - -} - -const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) ); - -addNodeClass( 'BufferNode', BufferNode ); - class TangentNode extends Node { constructor( scope = TangentNode.LOCAL ) { @@ -6752,13 +7262,19 @@ class TangentNode extends Node { outputNode = attribute( 'tangent', 'vec4' ); + if ( builder.geometry.hasAttribute( 'tangent' ) === false ) { + + builder.geometry.computeTangents(); + + } + } else if ( scope === TangentNode.LOCAL ) { outputNode = varying( tangentGeometry.xyz ); } else if ( scope === TangentNode.VIEW ) { - const vertexNode = modelViewMatrix.mul( tangentLocal ).xyz; + const vertexNode = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz; outputNode = normalize( varying( vertexNode ) ); } else if ( scope === TangentNode.WORLD ) { @@ -6806,11 +7322,12 @@ addNodeClass( 'TangentNode', TangentNode ); class SkinningNode extends Node { - constructor( skinnedMesh ) { + constructor( skinnedMesh, useReference = false ) { super( 'void' ); this.skinnedMesh = skinnedMesh; + this.useReference = useReference; this.updateType = NodeUpdateType.OBJECT; @@ -6819,9 +7336,25 @@ class SkinningNode extends Node { this.skinIndexNode = attribute( 'skinIndex', 'uvec4' ); this.skinWeightNode = attribute( 'skinWeight', 'vec4' ); - this.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); - this.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); - this.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode; + + if ( useReference ) { + + bindMatrixNode = reference( 'bindMatrix', 'mat4' ); + bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' ); + boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length ); + + } else { + + bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' ); + bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' ); + boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length ); + + } + + this.bindMatrixNode = bindMatrixNode; + this.bindMatrixInverseNode = bindMatrixInverseNode; + this.boneMatricesNode = boneMatricesNode; } @@ -6883,59 +7416,255 @@ class SkinningNode extends Node { } - update() { + update( frame ) { + + const object = this.useReference ? frame.object : this.skinnedMesh; - this.skinnedMesh.skeleton.update(); + object.skeleton.update(); } } -const skinning = nodeProxy( SkinningNode ); +const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) ); +const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) ); addNodeClass( 'SkinningNode', SkinningNode ); -const morphTextures = new WeakMap(); -const morphVec4 = new Vector4(); +class LoopNode extends Node { -const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => { + constructor( params = [] ) { - const texelIndex = int( vertexIndex ).mul( stride ).add( offset ); + super(); - const y = texelIndex.div( width ); - const x = texelIndex.sub( y.mul( width ) ); + this.params = params; - const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ); + } - return bufferAttrib.mul( influence ); + getVarName( index ) { -} ); + return String.fromCharCode( 'i'.charCodeAt() + index ); -function getEntry( geometry ) { + } - const hasMorphPosition = geometry.morphAttributes.position !== undefined; - const hasMorphNormals = geometry.morphAttributes.normal !== undefined; - const hasMorphColors = geometry.morphAttributes.color !== undefined; + getProperties( builder ) { - // instead of using attributes, the WebGL 2 code path encodes morph targets - // into an array of data textures. Each layer represents a single morph target. + const properties = builder.getNodeProperties( this ); - const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; - const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + if ( properties.stackNode !== undefined ) return properties; - let entry = morphTextures.get( geometry ); + // - if ( entry === undefined || entry.count !== morphTargetsCount ) { + const inputs = {}; - if ( entry !== undefined ) entry.texture.dispose(); + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - const morphTargets = geometry.morphAttributes.position || []; - const morphNormals = geometry.morphAttributes.normal || []; - const morphColors = geometry.morphAttributes.color || []; + const param = this.params[ i ]; - let vertexDataCount = 0; + const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); + const type = ( param.isNode !== true && param.type ) || 'int'; - if ( hasMorphPosition === true ) vertexDataCount = 1; + inputs[ name ] = expression( name, type ); + + } + + properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); + properties.stackNode = builder.removeStack(); + + return properties; + + } + + getNodeType( builder ) { + + const { returnsNode } = this.getProperties( builder ); + + return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; + + } + + setup( builder ) { + + // setup properties + + this.getProperties( builder ); + + } + + generate( builder ) { + + const properties = this.getProperties( builder ); + + const contextData = { tempWrite: false }; + + const params = this.params; + const stackNode = properties.stackNode; + + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { + + const param = params[ i ]; + + let start = null, end = null, name = null, type = null, condition = null, update = null; + + if ( param.isNode ) { + + type = 'int'; + name = this.getVarName( i ); + start = '0'; + end = param.build( builder, type ); + condition = '<'; + + } else { + + type = param.type || 'int'; + name = param.name || this.getVarName( i ); + start = param.start; + end = param.end; + condition = param.condition; + update = param.update; + + if ( typeof start === 'number' ) start = start.toString(); + else if ( start && start.isNode ) start = start.build( builder, type ); + + if ( typeof end === 'number' ) end = end.toString(); + else if ( end && end.isNode ) end = end.build( builder, type ); + + if ( start !== undefined && end === undefined ) { + + start = start + ' - 1'; + end = '0'; + condition = '>='; + + } else if ( end !== undefined && start === undefined ) { + + start = '0'; + condition = '<'; + + } + + if ( condition === undefined ) { + + if ( Number( start ) > Number( end ) ) { + + condition = '>='; + + } else { + + condition = '<'; + + } + + } + + } + + const internalParam = { start, end, condition }; + + // + + const startSnippet = internalParam.start; + const endSnippet = internalParam.end; + + let declarationSnippet = ''; + let conditionalSnippet = ''; + let updateSnippet = ''; + + if ( ! update ) { + + if ( type === 'int' || type === 'uint' ) { + + if ( condition.includes( '<' ) ) update = '++'; + else update = '--'; + + } else { + + if ( condition.includes( '<' ) ) update = '+= 1.'; + else update = '-= 1.'; + + } + + } + + declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; + + conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; + updateSnippet += name + ' ' + update; + + const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; + + builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); + + } + + const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); + + const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; + + builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); + + for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + + builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); + + } + + builder.addFlowTab(); + + return returnsSnippet; + + } + +} + +const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); +const Continue = () => expression( 'continue' ).append(); +const Break = () => expression( 'break' ).append(); + +addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); + +addNodeClass( 'LoopNode', LoopNode ); + +const morphTextures = new WeakMap(); +const morphVec4 = new Vector4(); + +const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => { + + const texelIndex = int( vertexIndex ).mul( stride ).add( offset ); + + const y = texelIndex.div( width ); + const x = texelIndex.sub( y.mul( width ) ); + + const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ); + + return bufferAttrib.mul( influence ); + +} ); + +function getEntry( geometry ) { + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; if ( hasMorphNormals === true ) vertexDataCount = 2; if ( hasMorphColors === true ) vertexDataCount = 3; @@ -7070,10 +7799,9 @@ class MorphNode extends Node { const width = int( size.width ); - for ( let i = 0; i < morphTargetsCount; i ++ ) { + loop( morphTargetsCount, ( { i } ) => { - const influence = referenceIndex( 'morphTargetInfluences', i, 'float' ); - const depth = int( i ); + const influence = reference( 'morphTargetInfluences', 'float' ).element( i ); if ( hasMorphPosition === true ) { @@ -7082,7 +7810,7 @@ class MorphNode extends Node { influence, stride, width, - depth, + depth: i, offset: int( 0 ) } ) ); @@ -7095,13 +7823,13 @@ class MorphNode extends Node { influence, stride, width, - depth, + depth: i, offset: int( 1 ) } ) ); } - } + } ); } @@ -7123,7 +7851,7 @@ class MorphNode extends Node { } -const morph = nodeProxy( MorphNode ); +const morphReference = nodeProxy( MorphNode ); addNodeClass( 'MorphNode', MorphNode ); @@ -7225,7 +7953,7 @@ class LightingNode extends Node { addNodeClass( 'LightingNode', LightingNode ); -let depthMaterial = null; +let overrideMaterial = null; class AnalyticLightNode extends LightingNode { @@ -7267,7 +7995,13 @@ class AnalyticLightNode extends LightingNode { if ( shadowNode === null ) { - if ( depthMaterial === null ) depthMaterial = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ); + if ( overrideMaterial === null ) { + + overrideMaterial = builder.createNodeMaterial(); + overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 ); + overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode + + } const shadow = this.light.shadow; const rtt = builder.getRenderTarget( shadow.mapSize.width, shadow.mapSize.height ); @@ -7355,8 +8089,10 @@ class AnalyticLightNode extends LightingNode { */ // + const shadowColor = texture( rtt.texture, shadowCoord ); + this.rtt = rtt; - this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode ) ); + this.colorNode = this.colorNode.mul( frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) ) ); this.shadowNode = shadowNode; @@ -7382,7 +8118,7 @@ class AnalyticLightNode extends LightingNode { const currentOverrideMaterial = scene.overrideMaterial; - scene.overrideMaterial = depthMaterial; + scene.overrideMaterial = overrideMaterial; rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height ); @@ -7608,7 +8344,7 @@ class LightsNode extends Node { } const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) ); -const lightNodes = nodeProxy( LightsNode ); +const lightsNode = nodeProxy( LightsNode ); function addLightNode( lightClass, lightNodeClass ) { @@ -7986,8 +8722,6 @@ class ViewportNode extends Node { const scope = this.scope; - if ( scope === ViewportNode.COORDINATE ) return; - let output = null; if ( scope === ViewportNode.RESOLUTION ) { @@ -8060,7 +8794,7 @@ const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIG addNodeClass( 'ViewportNode', ViewportNode ); -const _size$1 = new Vector2(); +const _size$2 = new Vector2(); class ViewportTextureNode extends TextureNode { @@ -8086,16 +8820,16 @@ class ViewportTextureNode extends TextureNode { updateBefore( frame ) { const renderer = frame.renderer; - renderer.getDrawingBufferSize( _size$1 ); + renderer.getDrawingBufferSize( _size$2 ); // const framebufferTexture = this.value; - if ( framebufferTexture.image.width !== _size$1.width || framebufferTexture.image.height !== _size$1.height ) { + if ( framebufferTexture.image.width !== _size$2.width || framebufferTexture.image.height !== _size$2.height ) { - framebufferTexture.image.width = _size$1.width; - framebufferTexture.image.height = _size$1.height; + framebufferTexture.image.width = _size$2.width; + framebufferTexture.image.height = _size$2.height; framebufferTexture.needsUpdate = true; } @@ -8136,9 +8870,6 @@ class ViewportDepthTextureNode extends ViewportTextureNode { if ( sharedDepthbuffer === null ) { sharedDepthbuffer = new DepthTexture(); - sharedDepthbuffer.minFilter = NearestMipmapNearestFilter; - sharedDepthbuffer.type = UnsignedIntType; - sharedDepthbuffer.format = DepthFormat; } @@ -8244,86 +8975,247 @@ depthPixel.assign = ( value ) => depthPixelBase( value ); addNodeClass( 'ViewportDepthNode', ViewportDepthNode ); -const NodeMaterials = new Map(); - -class NodeMaterial extends ShaderMaterial { +class ClippingNode extends Node { - constructor() { + constructor( scope = ClippingNode.DEFAULT ) { super(); - this.isNodeMaterial = true; + this.scope = scope; - this.type = this.constructor.type; + } - this.forceSinglePass = false; + setup( builder ) { - this.fog = true; - this.lights = true; - this.normals = true; + super.setup( builder ); - this.colorSpaced = true; + const clippingContext = builder.clippingContext; + const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext; - this.lightsNode = null; - this.envNode = null; + const numClippingPlanes = globalClippingCount + localClippingCount; + const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes; - this.colorNode = null; - this.normalNode = null; - this.opacityNode = null; - this.backdropNode = null; - this.backdropAlphaNode = null; - this.alphaTestNode = null; + if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) { - this.positionNode = null; + return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); - this.depthNode = null; + } else { - this.outputNode = null; + return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes ); - this.fragmentNode = null; - this.vertexNode = null; + } } - customProgramCacheKey() { + setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) { - return this.type + getCacheKey( this ); + return tslFn( () => { - } + const clippingPlanes = uniforms( planes ); - build( builder ) { + const distanceToPlane = property( 'float', 'distanceToPlane' ); + const distanceGradient = property( 'float', 'distanceToGradient' ); - this.setup( builder ); + const clipOpacity = property( 'float', 'clipOpacity' ); - } + clipOpacity.assign( 1 ); - setup( builder ) { + let plane; - // < VERTEX STAGE > + loop( numUnionClippingPlanes, ( { i } ) => { - builder.addStack(); + plane = clippingPlanes.element( i ); - builder.stack.outputNode = this.vertexNode || this.setupPosition( builder ); + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); - builder.addFlow( 'vertex', builder.removeStack() ); + clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) ); - // < FRAGMENT STAGE > + clipOpacity.equal( 0.0 ).discard(); - builder.addStack(); + } ); - let resultNode; + if ( numUnionClippingPlanes < numClippingPlanes ) { - if ( this.fragmentNode === null ) { + const unionClipOpacity = property( 'float', 'unionclipOpacity' ); - if ( this.depthWrite === true ) this.setupDepth( builder ); + unionClipOpacity.assign( 1 ); - if ( this.normals === true ) this.setupNormal( builder ); + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { - this.setupDiffuseColor( builder ); - this.setupVariants( builder ); + plane = clippingPlanes.element( i ); + + distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) ); + distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) ); + + unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() ); + + } ); + + clipOpacity.mulAssign( unionClipOpacity.oneMinus() ); + + } + + diffuseColor.a.mulAssign( clipOpacity ); + + diffuseColor.a.equal( 0.0 ).discard(); + + } )(); + + } + + setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) { + + return tslFn( () => { + + const clippingPlanes = uniforms( planes ); + + let plane; + + loop( numUnionClippingPlanes, ( { i } ) => { + + plane = clippingPlanes.element( i ); + positionView.dot( plane.xyz ).greaterThan( plane.w ).discard(); + + } ); + + if ( numUnionClippingPlanes < numClippingPlanes ) { + + const clipped = property( 'bool', 'clipped' ); + + clipped.assign( true ); + + loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => { + + plane = clippingPlanes.element( i ); + clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) ); + + } ); + + clipped.discard(); + } + + } )(); + + } + +} + +ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage'; +ClippingNode.DEFAULT = 'default'; + +const clipping = () => nodeObject( new ClippingNode() ); + +const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) ); + +class FrontFacingNode extends Node { + + constructor() { + + super( 'bool' ); + + this.isFrontFacingNode = true; + + } + + generate( builder ) { + + return builder.getFrontFacing(); + + } + +} + +const frontFacing = nodeImmutable( FrontFacingNode ); +const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); + +addNodeClass( 'FrontFacingNode', FrontFacingNode ); + +const NodeMaterials = new Map(); + +class NodeMaterial extends ShaderMaterial { + + constructor() { + + super(); + + this.isNodeMaterial = true; + + this.type = this.constructor.type; + + this.forceSinglePass = false; + + this.fog = true; + this.lights = true; + this.normals = true; + + this.colorSpaced = true; + + this.lightsNode = null; + this.envNode = null; + + this.colorNode = null; + this.normalNode = null; + this.opacityNode = null; + this.backdropNode = null; + this.backdropAlphaNode = null; + this.alphaTestNode = null; + + this.positionNode = null; + + this.depthNode = null; + this.shadowNode = null; + + this.outputNode = null; + + this.fragmentNode = null; + this.vertexNode = null; + + } + + customProgramCacheKey() { + + return this.type + getCacheKey( this ); + + } + + build( builder ) { + + this.setup( builder ); + + } + + setup( builder ) { + + // < VERTEX STAGE > + + builder.addStack(); + + builder.stack.outputNode = this.vertexNode || this.setupPosition( builder ); + + builder.addFlow( 'vertex', builder.removeStack() ); + + // < FRAGMENT STAGE > + + builder.addStack(); + + let resultNode; + + const clippingNode = this.setupClipping( builder ); + + if ( this.fragmentNode === null ) { + + if ( this.depthWrite === true ) this.setupDepth( builder ); + + if ( this.normals === true ) this.setupNormal( builder ); + + this.setupDiffuseColor( builder ); + this.setupVariants( builder ); const outgoingLightNode = this.setupLighting( builder ); + if ( clippingNode !== null ) builder.stack.add( clippingNode ); + resultNode = this.setupOutput( builder, vec4( outgoingLightNode, diffuseColor.a ) ); // OUTPUT NODE @@ -8346,6 +9238,31 @@ class NodeMaterial extends ShaderMaterial { } + setupClipping( builder ) { + + const { globalClippingCount, localClippingCount } = builder.clippingContext; + + let result = null; + + if ( globalClippingCount || localClippingCount ) { + + if ( this.alphaToCoverage ) { + + // to be added to flow when the color/alpha value has been determined + result = clippingAlpha(); + + } else { + + builder.stack.add( clipping() ); + + } + + } + + return result; + + } + setupDepth( builder ) { const { renderer } = builder; @@ -8381,13 +9298,13 @@ class NodeMaterial extends ShaderMaterial { if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) { - morph( object ).append(); + morphReference( object ).append(); } if ( object.isSkinnedMesh === true ) { - skinning( object ).append(); + skinningReference( object ).append(); } @@ -8459,13 +9376,13 @@ class NodeMaterial extends ShaderMaterial { const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize(); - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } else { const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal; - transformedNormalView.assign( normalNode ); + transformedNormalView.assign( normalNode.mul( faceDirection ) ); } @@ -8513,15 +9430,15 @@ class NodeMaterial extends ShaderMaterial { } - let lightsNode = this.lightsNode || builder.lightsNode; + let lightsN = this.lightsNode || builder.lightsNode; if ( materialLightsNode.length > 0 ) { - lightsNode = lightNodes( [ ...lightsNode.lightNodes, ...materialLightsNode ] ); + lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] ); } - return lightsNode; + return lightsN; } @@ -8720,6 +9637,7 @@ class NodeMaterial extends ShaderMaterial { this.positionNode = source.positionNode; this.depthNode = source.depthNode; + this.shadowNode = source.shadowNode; this.outputNode = source.outputNode; @@ -9079,23 +9997,45 @@ class CondNode extends Node { } - generate( builder ) { + generate( builder, output ) { const type = this.getNodeType( builder ); const context$1 = { tempWrite: false }; + const nodeData = builder.getDataFromNode( this ); + + if ( nodeData.nodeProperty !== undefined ) { + + return nodeData.nodeProperty; + + } + const { ifNode, elseNode } = this; - const needsProperty = ifNode.getNodeType( builder ) !== 'void' || ( elseNode && elseNode.getNodeType( builder ) !== 'void' ); - const nodeProperty = needsProperty ? property( type ).build( builder ) : ''; + const needsOutput = output !== 'void'; + const nodeProperty = needsOutput ? property( type ).build( builder ) : ''; + + nodeData.nodeProperty = nodeProperty; const nodeSnippet = context( this.condNode/*, context*/ ).build( builder, 'bool' ); builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab(); - let ifSnippet = context( this.ifNode, context$1 ).build( builder, type ); + let ifSnippet = context( ifNode, context$1 ).build( builder, type ); + + if ( ifSnippet ) { + + if ( needsOutput ) { + + ifSnippet = nodeProperty + ' = ' + ifSnippet + ';'; + + } else { + + ifSnippet = 'return ' + ifSnippet + ';'; - ifSnippet = needsProperty ? nodeProperty + ' = ' + ifSnippet + ';' : ifSnippet; + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' ); @@ -9104,7 +10044,20 @@ class CondNode extends Node { builder.addFlowCode( ' else {\n\n' ).addFlowTab(); let elseSnippet = context( elseNode, context$1 ).build( builder, type ); - elseSnippet = nodeProperty ? nodeProperty + ' = ' + elseSnippet + ';' : elseSnippet; + + if ( elseSnippet ) { + + if ( needsOutput ) { + + elseSnippet = nodeProperty + ' = ' + elseSnippet + ';'; + + } else { + + elseSnippet = 'return ' + elseSnippet + ';'; + + } + + } builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' ); @@ -9114,7 +10067,7 @@ class CondNode extends Node { } - return nodeProperty; + return builder.format( nodeProperty, type, output ); } @@ -9317,6 +10270,8 @@ class NodeBuilder { this.fogNode = null; this.toneMappingNode = null; + this.clippingContext = null; + this.vertexShader = null; this.fragmentShader = null; this.computeShader = null; @@ -9695,7 +10650,7 @@ class NodeBuilder { isReference( type ) { - return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture'; + return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture'; } @@ -9705,12 +10660,6 @@ class NodeBuilder { } - /** @deprecated, r152 */ - getTextureEncodingFromMap( map ) { - return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding; - - } - getTextureColorSpaceFromMap( map ) { let colorSpace; @@ -9754,7 +10703,7 @@ class NodeBuilder { getVectorType( type ) { if ( type === 'color' ) return 'vec3'; - if ( type === 'texture' ) return 'vec4'; + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) return 'vec4'; return type; @@ -9806,6 +10755,7 @@ class NodeBuilder { if ( vecNum !== null ) return Number( vecNum[ 1 ] ); if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1; + if ( /mat2/.test( type ) === true ) return 4; if ( /mat3/.test( type ) === true ) return 9; if ( /mat4/.test( type ) === true ) return 16; @@ -10394,24 +11344,12 @@ class NodeBuilder { } - createNodeMaterial( type ) { + createNodeMaterial( type = 'NodeMaterial' ) { return createNodeMaterialFromType( type ); } - getPrimitiveType( type ) { - - let primitiveType; - - if ( type[ 0 ] === 'i' ) primitiveType = 'int'; - else if ( type[ 0 ] === 'u' ) primitiveType = 'uint'; - else primitiveType = 'float'; - - return primitiveType; - - } - format( snippet, fromType, toType ) { fromType = this.getVectorType( fromType ); @@ -10471,7 +11409,7 @@ class NodeBuilder { // convert a number value to vector type, e.g: // vec3( 1u ) -> vec3( float( 1u ) ) - snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`; + snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`; } @@ -10532,7 +11470,7 @@ class NodeFrame { updateBeforeNode( node ) { const updateType = node.getUpdateBeforeType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -10540,9 +11478,11 @@ class NodeFrame { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.updateBefore( this ) !== false ) { + + frameMap.set( node, this.frameId ); - node.updateBefore( this ); + } } @@ -10552,9 +11492,11 @@ class NodeFrame { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.updateBefore( this ) !== false ) { + + renderMap.set( node, this.renderId ); - node.updateBefore( this ); + } } @@ -10569,7 +11511,7 @@ class NodeFrame { updateNode( node ) { const updateType = node.getUpdateType(); - const reference = node.updateReference( this ); + const reference = node.setReference( this ); if ( updateType === NodeUpdateType.FRAME ) { @@ -10577,9 +11519,11 @@ class NodeFrame { if ( frameMap.get( node ) !== this.frameId ) { - frameMap.set( node, this.frameId ); + if ( node.update( this ) !== false ) { + + frameMap.set( node, this.frameId ); - node.update( this ); + } } @@ -10589,9 +11533,11 @@ class NodeFrame { if ( renderMap.get( node ) !== this.renderId ) { - renderMap.set( node, this.renderId ); + if ( node.update( this ) !== false ) { + + renderMap.set( node, this.renderId ); - node.update( this ); + } } @@ -10743,6 +11689,85 @@ addNodeElement( 'hash', hash ); addNodeClass( 'HashNode', HashNode ); +// remapping functions https://iquilezles.org/articles/functions/ +const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k ); +const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) ); +const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a ); +const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) ); + + +addNodeElement( 'parabola', parabola ); +addNodeElement( 'gain', gain ); +addNodeElement( 'pcurve', pcurve ); +addNodeElement( 'sinc', sinc ); + +// https://github.com/cabbibo/glsl-tri-noise-3d + +const tri = tslFn( ( [ x ] ) => { + + return x.fract().sub( .5 ).abs(); + +} ); + +const tri3 = tslFn( ( [ p ] ) => { + + return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) ); + +} ); + +const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => { + + const p = vec3( p_immutable ).toVar(); + const z = float( 1.4 ).toVar(); + const rz = float( 0.0 ).toVar(); + const bp = vec3( p ).toVar(); + + loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => { + + const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar(); + p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) ); + bp.mulAssign( 1.8 ); + z.mulAssign( 1.5 ); + p.mulAssign( 1.2 ); + + const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar(); + rz.addAssign( t.div( z ) ); + bp.addAssign( 0.14 ); + + } ); + + return rz; + +} ); + +// layouts + +tri.setLayout( { + name: 'tri', + type: 'float', + inputs: [ + { name: 'x', type: 'float' } + ] +} ); + +tri3.setLayout( { + name: 'tri3', + type: 'vec3', + inputs: [ + { name: 'p', type: 'vec3' } + ] +} ); + +triNoise3D.setLayout( { + name: 'triNoise3D', + type: 'float', + inputs: [ + { name: 'p', type: 'vec3' }, + { name: 'spd', type: 'float' }, + { name: 'time', type: 'float' } + ] +} ); + let discardExpression; class DiscardNode extends CondNode { @@ -10855,202 +11880,11 @@ const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( f addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode ); -class LoopNode extends Node { +class MatcapUVNode extends TempNode { - constructor( params = [] ) { + constructor() { - super(); - - this.params = params; - - } - - getVarName( index ) { - - return String.fromCharCode( 'i'.charCodeAt() + index ); - - } - - getProperties( builder ) { - - const properties = builder.getNodeProperties( this ); - - if ( properties.stackNode !== undefined ) return properties; - - // - - const inputs = {}; - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - const param = this.params[ i ]; - - const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); - const type = ( param.isNode !== true && param.type ) || 'int'; - - inputs[ name ] = expression( name, type ); - - } - - properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder.addStack(), builder ); - properties.stackNode = builder.removeStack(); - - return properties; - - } - - getNodeType( builder ) { - - const { returnsNode } = this.getProperties( builder ); - - return returnsNode ? returnsNode.getNodeType( builder ) : 'void'; - - } - - setup( builder ) { - - // setup properties - - this.getProperties( builder ); - - } - - generate( builder ) { - - const properties = this.getProperties( builder ); - - const contextData = { tempWrite: false }; - - const params = this.params; - const stackNode = properties.stackNode; - - for ( let i = 0, l = params.length - 1; i < l; i ++ ) { - - const param = params[ i ]; - - let start = null, end = null, name = null, type = null, condition = null, update = null; - - if ( param.isNode ) { - - type = 'int'; - name = this.getVarName( i ); - start = '0'; - end = param.build( builder, type ); - condition = '<'; - - } else { - - type = param.type || 'int'; - name = param.name || this.getVarName( i ); - start = param.start; - end = param.end; - condition = param.condition; - update = param.update; - - if ( typeof start === 'number' ) start = start.toString(); - else if ( start && start.isNode ) start = start.build( builder, type ); - - if ( typeof end === 'number' ) end = end.toString(); - else if ( end && end.isNode ) end = end.build( builder, type ); - - if ( start !== undefined && end === undefined ) { - - start = start + ' - 1'; - end = '0'; - condition = '>='; - - } else if ( end !== undefined && start === undefined ) { - - start = '0'; - condition = '<'; - - } - - if ( condition === undefined ) { - - if ( Number( start ) > Number( end ) ) { - - condition = '>='; - - } else { - - condition = '<'; - - } - - } - - } - - const internalParam = { start, end, condition }; - - // - - const startSnippet = internalParam.start; - const endSnippet = internalParam.end; - - let declarationSnippet = ''; - let conditionalSnippet = ''; - let updateSnippet = ''; - - if ( ! update ) { - - if ( type === 'int' ) { - - if ( condition.includes( '<' ) ) update = '++'; - else update = '--'; - - } else { - - if ( condition.includes( '<' ) ) update = '+= 1'; - else update = '-= 1'; - - } - - } - - declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet; - - conditionalSnippet += name + ' ' + condition + ' ' + endSnippet; - updateSnippet += name + ' ' + update; - - const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`; - - builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab(); - - } - - const stackSnippet = context( stackNode, contextData ).build( builder, 'void' ); - - const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : ''; - - builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); - - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { - - builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); - - } - - builder.addFlowTab(); - - return returnsSnippet; - - } - -} - -const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append(); - -addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) ); - -addNodeClass( 'LoopNode', LoopNode ); - -class MatcapUVNode extends TempNode { - - constructor() { - - super( 'vec2' ); + super( 'vec2' ); } @@ -11254,200 +12088,553 @@ class PackingNode extends TempNode { const { scope, node } = this; - let result = null; + let result = null; + + if ( scope === PackingNode.DIRECTION_TO_COLOR ) { + + result = node.mul( 0.5 ).add( 0.5 ); + + } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) { + + result = node.mul( 2.0 ).sub( 1 ); + + } + + return result; + + } + +} + +PackingNode.DIRECTION_TO_COLOR = 'directionToColor'; +PackingNode.COLOR_TO_DIRECTION = 'colorToDirection'; + +const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR ); +const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION ); + +addNodeElement( 'directionToColor', directionToColor ); +addNodeElement( 'colorToDirection', colorToDirection ); + +addNodeClass( 'PackingNode', PackingNode ); + +class RemapNode extends Node { + + constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) { + + super(); + + this.node = node; + this.inLowNode = inLowNode; + this.inHighNode = inHighNode; + this.outLowNode = outLowNode; + this.outHighNode = outHighNode; + + this.doClamp = true; + + } + + setup() { + + const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this; + + let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) ); + + if ( doClamp === true ) t = t.clamp(); + + return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode ); + + } + +} + +const remap = nodeProxy( RemapNode, null, null, { doClamp: false } ); +const remapClamp = nodeProxy( RemapNode ); + +addNodeElement( 'remap', remap ); +addNodeElement( 'remapClamp', remapClamp ); + +addNodeClass( 'RemapNode', RemapNode ); + +class RotateUVNode extends TempNode { + + constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) { + + super( 'vec2' ); + + this.uvNode = uvNode; + this.rotationNode = rotationNode; + this.centerNode = centerNode; + + } + + setup() { + + const { uvNode, rotationNode, centerNode } = this; + + const vector = uvNode.sub( centerNode ); + + return vector.rotate( rotationNode ).add( centerNode ); + + } + +} + +const rotateUV = nodeProxy( RotateUVNode ); + +addNodeElement( 'rotateUV', rotateUV ); + +addNodeClass( 'RotateUVNode', RotateUVNode ); + +class RotateNode extends TempNode { + + constructor( positionNode, rotationNode ) { + + super(); + + this.positionNode = positionNode; + this.rotationNode = rotationNode; + + } + + getNodeType( builder ) { + + return this.positionNode.getNodeType( builder ); + + } + + setup( builder ) { + + const { rotationNode, positionNode } = this; + + const nodeType = this.getNodeType( builder ); + + if ( nodeType === 'vec2' ) { + + const cosAngle = rotationNode.cos(); + const sinAngle = rotationNode.sin(); + + const rotationMatrix = mat2( + cosAngle, sinAngle, + sinAngle.negate(), cosAngle + ); + + return rotationMatrix.mul( positionNode ); + + } else { + + const rotation = rotationNode; + const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) ); + + return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz; + + } + + } + +} + +const rotate = nodeProxy( RotateNode ); + +addNodeElement( 'rotate', rotate ); + +addNodeClass( 'RotateNode', RotateNode ); + +class SpriteSheetUVNode extends Node { + + constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { + + super( 'vec2' ); + + this.countNode = countNode; + this.uvNode = uvNode; + this.frameNode = frameNode; + + } + + setup() { + + const { frameNode, uvNode, countNode } = this; + + const { width, height } = countNode; + + const frameNum = frameNode.mod( width.mul( height ) ).floor(); + + const column = frameNum.mod( width ); + const row = height.sub( frameNum.add( 1 ).div( width ).ceil() ); + + const scale = countNode.reciprocal(); + const uvFrameOffset = vec2( column, row ); + + return uvNode.add( uvFrameOffset ).mul( scale ); + + } + +} + +const spritesheetUV = nodeProxy( SpriteSheetUVNode ); + +addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode ); + +class StorageArrayElementNode extends ArrayElementNode { + + constructor( storageBufferNode, indexNode ) { + + super( storageBufferNode, indexNode ); + + this.isStorageArrayElementNode = true; + + } + + set storageBufferNode( value ) { + + this.node = value; + + } + + get storageBufferNode() { + + return this.node; + + } + + setup( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + if ( ! this.node.instanceIndex && this.node.bufferObject === true ) { + + builder.setupPBO( this.node ); + + } + + } + + return super.setup( builder ); + + } + + generate( builder, output ) { + + let snippet; + + const isAssignContext = builder.context.assign; + + // + + if ( builder.isAvailable( 'storageBuffer' ) === false ) { + + const { node } = this; + + if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) { + + snippet = builder.generatePBO( this ); + + } else { + + snippet = node.build( builder ); + + } + + } else { + + snippet = super.generate( builder ); + + } + + if ( isAssignContext !== true ) { + + const type = this.getNodeType( builder ); + + snippet = builder.format( snippet, type, output ); + + } + + return snippet; + + } + +} + +const storageElement = nodeProxy( StorageArrayElementNode ); + +addNodeElement( 'storageElement', storageElement ); + +addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode ); + +class TriplanarTexturesNode extends Node { + + constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { + + super( 'vec4' ); + + this.textureXNode = textureXNode; + this.textureYNode = textureYNode; + this.textureZNode = textureZNode; + + this.scaleNode = scaleNode; + + this.positionNode = positionNode; + 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 ); + + } + +} + +const triplanarTextures = nodeProxy( TriplanarTexturesNode ); +const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); + +addNodeElement( 'triplanarTexture', triplanarTexture ); + +addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode ); + +const _reflectorPlane = new Plane(); +const _normal = new Vector3(); +const _reflectorWorldPosition = new Vector3(); +const _cameraWorldPosition = new Vector3(); +const _rotationMatrix = new Matrix4(); +const _lookAtPosition = new Vector3( 0, 0, - 1 ); +const clipPlane = new Vector4(); + +const _view = new Vector3(); +const _target = new Vector3(); +const _q = new Vector4(); + +const _size$1 = new Vector2(); + +const _defaultRT = new RenderTarget(); +const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y ); + +let _inReflector = false; + +class ReflectorNode extends TextureNode { + + constructor( parameters = {} ) { + + super( _defaultRT.texture, _defaultUV ); - if ( scope === PackingNode.DIRECTION_TO_COLOR ) { + const { + target = new Object3D(), + resolution = 1, + generateMipmaps = false, + bounces = true + } = parameters; - result = node.mul( 0.5 ).add( 0.5 ); + // - } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) { + this.target = target; + this.resolution = resolution; + this.generateMipmaps = generateMipmaps; + this.bounces = bounces; - result = node.mul( 2.0 ).sub( 1 ); + this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME; - } + this.virtualCameras = new WeakMap(); + this.renderTargets = new WeakMap(); - return result; } -} + _updateResolution( renderTarget, renderer ) { -PackingNode.DIRECTION_TO_COLOR = 'directionToColor'; -PackingNode.COLOR_TO_DIRECTION = 'colorToDirection'; + const resolution = this.resolution; -const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR ); -const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION ); + renderer.getDrawingBufferSize( _size$1 ); -addNodeElement( 'directionToColor', directionToColor ); -addNodeElement( 'colorToDirection', colorToDirection ); + renderTarget.setSize( Math.round( _size$1.width * resolution ), Math.round( _size$1.height * resolution ) ); -addNodeClass( 'PackingNode', PackingNode ); + } -class RemapNode extends Node { + setup( builder ) { - constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) { + this._updateResolution( _defaultRT, builder.renderer ); - super(); + return super.setup( builder ); - this.node = node; - this.inLowNode = inLowNode; - this.inHighNode = inHighNode; - this.outLowNode = outLowNode; - this.outHighNode = outHighNode; + } - this.doClamp = true; + getTextureNode() { + + return this.textureNode; } - setup() { + getVirtualCamera( camera ) { - const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this; + let virtualCamera = this.virtualCameras.get( camera ); - let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) ); + if ( virtualCamera === undefined ) { - if ( doClamp === true ) t = t.clamp(); + virtualCamera = camera.clone(); - return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode ); + this.virtualCameras.set( camera, virtualCamera ); - } + } -} + return virtualCamera; -const remap = nodeProxy( RemapNode, null, null, { doClamp: false } ); -const remapClamp = nodeProxy( RemapNode ); + } -addNodeElement( 'remap', remap ); -addNodeElement( 'remapClamp', remapClamp ); + getRenderTarget( camera ) { -addNodeClass( 'RemapNode', RemapNode ); + let renderTarget = this.renderTargets.get( camera ); -class RotateUVNode extends TempNode { + if ( renderTarget === undefined ) { - constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) { + renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } ); - super( 'vec2' ); + if ( this.generateMipmaps === true ) { - this.uvNode = uvNode; - this.rotationNode = rotationNode; - this.centerNode = centerNode; + renderTarget.texture.minFilter = LinearMipMapLinearFilter; + renderTarget.texture.generateMipmaps = true; - } + } - setup() { + this.renderTargets.set( camera, renderTarget ); - const { uvNode, rotationNode, centerNode } = this; + } - const cosAngle = rotationNode.cos(); - const sinAngle = rotationNode.sin(); + return renderTarget; - const vector = uvNode.sub( centerNode ); + } - const rotatedVector = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( vector )? - vec2( cosAngle, sinAngle ).dot( vector ), - vec2( sinAngle.negate(), cosAngle ).dot( vector ) - ); + updateBefore( frame ) { - return rotatedVector.add( centerNode ); + if ( this.bounces === false && _inReflector ) return false; - } + _inReflector = true; -} + const { scene, camera, renderer, material } = frame; + const { target } = this; -const rotateUV = nodeProxy( RotateUVNode ); + const virtualCamera = this.getVirtualCamera( camera ); + const renderTarget = this.getRenderTarget( virtualCamera ); -addNodeElement( 'rotateUV', rotateUV ); + renderer.getDrawingBufferSize( _size$1 ); -addNodeClass( 'RotateUVNode', RotateUVNode ); + this._updateResolution( renderTarget, renderer ); -class SpriteSheetUVNode extends Node { + // - constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) { + _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld ); + _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); - super( 'vec2' ); + _rotationMatrix.extractRotation( target.matrixWorld ); - this.countNode = countNode; - this.uvNode = uvNode; - this.frameNode = frameNode; + _normal.set( 0, 0, 1 ); + _normal.applyMatrix4( _rotationMatrix ); - } + _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition ); - setup() { + // Avoid rendering when reflector is facing away - const { frameNode, uvNode, countNode } = this; + if ( _view.dot( _normal ) > 0 ) return; - const { width, height } = countNode; + _view.reflect( _normal ).negate(); + _view.add( _reflectorWorldPosition ); - const frameNum = frameNode.mod( width.mul( height ) ).floor(); + _rotationMatrix.extractRotation( camera.matrixWorld ); - const column = frameNum.mod( width ); - const row = height.sub( frameNum.add( 1 ).div( width ).ceil() ); + _lookAtPosition.set( 0, 0, - 1 ); + _lookAtPosition.applyMatrix4( _rotationMatrix ); + _lookAtPosition.add( _cameraWorldPosition ); - const scale = countNode.reciprocal(); - const uvFrameOffset = vec2( column, row ); + _target.subVectors( _reflectorWorldPosition, _lookAtPosition ); + _target.reflect( _normal ).negate(); + _target.add( _reflectorWorldPosition ); - return uvNode.add( uvFrameOffset ).mul( scale ); + // - } + virtualCamera.coordinateSystem = camera.coordinateSystem; + virtualCamera.position.copy( _view ); + virtualCamera.up.set( 0, 1, 0 ); + virtualCamera.up.applyMatrix4( _rotationMatrix ); + virtualCamera.up.reflect( _normal ); + virtualCamera.lookAt( _target ); -} + virtualCamera.near = camera.near; + virtualCamera.far = camera.far; -const spritesheetUV = nodeProxy( SpriteSheetUVNode ); + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); -addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode ); + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition ); + _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); -class TriplanarTexturesNode extends Node { + clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant ); - constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) { + const projectionMatrix = virtualCamera.projectionMatrix; - super( 'vec4' ); + _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; + _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; + _q.z = - 1.0; + _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; - this.textureXNode = textureXNode; - this.textureYNode = textureYNode; - this.textureZNode = textureZNode; + // Calculate the scaled plane vector + clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) ); - this.scaleNode = scaleNode; + const clipBias = 0; - this.positionNode = positionNode; - this.normalNode = normalNode; + // Replacing the third row of the projection matrix + projectionMatrix.elements[ 2 ] = clipPlane.x; + projectionMatrix.elements[ 6 ] = clipPlane.y; + projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias; + projectionMatrix.elements[ 14 ] = clipPlane.w; - } + // - setup() { + this.value = renderTarget.texture; - const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this; + material.visible = false; - // Ref: https://github.com/keijiro/StandardTriplanar + const currentRenderTarget = renderer.getRenderTarget(); - // Blending factor of triplanar mapping - let bf = normalNode.abs().normalize(); - bf = bf.div( bf.dot( vec3( 1.0 ) ) ); + renderer.setRenderTarget( renderTarget ); - // Triplanar mapping - const tx = positionNode.yz.mul( scaleNode ); - const ty = positionNode.zx.mul( scaleNode ); - const tz = positionNode.xy.mul( scaleNode ); + renderer.render( scene, virtualCamera ); - // Base color - const textureX = textureXNode.value; - const textureY = textureYNode !== null ? textureYNode.value : textureX; - const textureZ = textureZNode !== null ? textureZNode.value : textureX; + renderer.setRenderTarget( currentRenderTarget ); - const cx = texture( textureX, tx ).mul( bf.x ); - const cy = texture( textureY, ty ).mul( bf.y ); - const cz = texture( textureZ, tz ).mul( bf.z ); + material.visible = true; - return add( cx, cy, cz ); + _inReflector = false; } } -const triplanarTextures = nodeProxy( TriplanarTexturesNode ); -const triplanarTexture = ( ...params ) => triplanarTextures( ...params ); - -addNodeElement( 'triplanarTexture', triplanarTexture ); - -addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode ); +const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) ); class BitangentNode extends Node { @@ -11529,6 +12716,11 @@ const transformedBitangentWorld = normalize( transformedBitangentView.transformD addNodeClass( 'BitangentNode', BitangentNode ); +const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); + +const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/; +const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) ); + class VertexColorNode extends AttributeNode { constructor( index = 0 ) { @@ -11752,6 +12944,11 @@ class StorageBufferNode extends BufferNode { this.isStorageBufferNode = true; + this.bufferObject = false; + + this._attribute = null; + this._varying = null; + } getInputType( /*builder*/ ) { @@ -11760,9 +12957,46 @@ class StorageBufferNode extends BufferNode { } + element( indexNode ) { + + return storageElement( this, indexNode ); + + } + + setBufferObject( value ) { + + this.bufferObject = value; + + return this; + + } + + generate( builder ) { + + if ( builder.isAvailable( 'storageBuffer' ) ) return super.generate( builder ); + + const nodeType = this.getNodeType( builder ); + + if ( this._attribute === null ) { + + this._attribute = bufferAttribute( this.value ); + this._varying = varying( this._attribute ); + + } + + + const output = this._varying.build( builder, nodeType ); + + builder.registerTransform( output, this._attribute ); + + return output; + + } + } const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) ); +const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) ); addNodeClass( 'StorageBufferNode', StorageBufferNode ); @@ -11778,15 +13012,68 @@ class TextureStoreNode extends TextureNode { } - getNodeType( /*builder*/ ) { + getInputType( /*builder*/ ) { + + return 'storageTexture'; + + } + + setup( builder ) { + + super.setup( builder ); + + const properties = builder.getNodeProperties( this ); + properties.storeNode = this.storeNode; + + } + + generate( builder, output ) { + + let snippet; + + if ( this.storeNode !== null ) { + + snippet = this.generateStore( builder ); + + } else { + + snippet = super.generate( builder, output ); + + } + + return snippet; + + } + + generateStore( builder ) { + + const properties = builder.getNodeProperties( this ); + + const { uvNode, storeNode } = properties; + + const textureProperty = super.generate( builder, 'property' ); + const uvSnippet = uvNode.build( builder, 'uvec2' ); + const storeSnippet = storeNode.build( builder, 'vec4' ); + + const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet ); - return 'void'; + builder.addLineFlowCode( snippet ); } } -const textureStore = nodeProxy( TextureStoreNode ); +const textureStoreBase = nodeProxy( TextureStoreNode ); + +const textureStore = ( value, uvNode, storeNode ) => { + + const node = textureStoreBase( value, uvNode, storeNode ); + + if ( storeNode !== null ) node.append(); + + return node; + +}; addNodeClass( 'TextureStoreNode', TextureStoreNode ); @@ -11820,6 +13107,13 @@ const BurnNode = tslFn( ( { base, blend } ) => { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'burnColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const DodgeNode = tslFn( ( { base, blend } ) => { @@ -11828,6 +13122,13 @@ const DodgeNode = tslFn( ( { base, blend } ) => { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'dodgeColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const ScreenNode = tslFn( ( { base, blend } ) => { @@ -11836,14 +13137,29 @@ const ScreenNode = tslFn( ( { base, blend } ) => { return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'screenColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); const OverlayNode = tslFn( ( { base, blend } ) => { const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() ); + //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) ); return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) ); +} ).setLayout( { + name: 'overlayColor', + type: 'vec3', + inputs: [ + { name: 'base', type: 'vec3' }, + { name: 'blend', type: 'vec3' } + ] } ); class BlendModeNode extends TempNode { @@ -11907,29 +13223,6 @@ addNodeElement( 'screen', screen ); addNodeClass( 'BlendModeNode', BlendModeNode ); -class FrontFacingNode extends Node { - - constructor() { - - super( 'bool' ); - - this.isFrontFacingNode = true; - - } - - generate( builder ) { - - return builder.getFrontFacing(); - - } - -} - -const frontFacing = nodeImmutable( FrontFacingNode ); -const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 ); - -addNodeClass( 'FrontFacingNode', FrontFacingNode ); - // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf @@ -12099,9 +13392,12 @@ const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE ); const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 ); const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma ); +const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) ); + addNodeElement( 'saturation', saturation ); addNodeElement( 'vibrance', vibrance ); addNodeElement( 'hue', hue ); +addNodeElement( 'threshold', threshold ); addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode ); @@ -12192,8 +13488,6 @@ class NormalMapNode extends TempNode { const normalMap = nodeProxy( NormalMapNode ); -const TBNViewMatrix = mat3( tangentView, bitangentView, normalView ); - addNodeElement( 'normalMap', normalMap ); addNodeClass( 'NormalMapNode', NormalMapNode ); @@ -12291,16 +13585,57 @@ const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => { color = ACESOutputMat.mul( color ); - // Clamp to [0, 1] - return color.clamp(); + // Clamp to [0, 1] + return color.clamp(); + +} ); + + + +const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); +const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); + +const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => { + + const x = vec3( x_immutable ).toVar(); + const x2 = vec3( x.mul( x ) ).toVar(); + const x4 = vec3( x2.mul( x2 ) ).toVar(); + + return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) ); + +} ); + +const AGXToneMappingNode = tslFn( ( { color, exposure } ) => { + + const colortone = vec3( color ).toVar(); + const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); + const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); + const AgxMinEv = float( - 12.47393 ); + const AgxMaxEv = float( 4.026069 ); + colortone.mulAssign( exposure ); + colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) ); + colortone.assign( AgXInsetMatrix.mul( colortone ) ); + colortone.assign( max$1( colortone, 1e-10 ) ); + colortone.assign( log2( colortone ) ); + colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + colortone.assign( agxDefaultContrastApprox( colortone ) ); + colortone.assign( AgXOutsetMatrix.mul( colortone ) ); + colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) ); + colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) ); + colortone.assign( clamp( colortone, 0.0, 1.0 ) ); + + return colortone; } ); + const toneMappingLib = { [ LinearToneMapping ]: LinearToneMappingNode, [ ReinhardToneMapping ]: ReinhardToneMappingNode, [ CineonToneMapping ]: OptimizedCineonToneMappingNode, - [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode + [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode, + [ AgXToneMapping ]: AGXToneMappingNode }; class ToneMappingNode extends TempNode { @@ -12357,19 +13692,19 @@ const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingN addNodeClass( 'ToneMappingNode', ToneMappingNode ); -let sharedFramebuffer = null; +let _sharedFramebuffer = null; class ViewportSharedTextureNode extends ViewportTextureNode { constructor( uvNode = viewportTopLeft, levelNode = null ) { - if ( sharedFramebuffer === null ) { + if ( _sharedFramebuffer === null ) { - sharedFramebuffer = new FramebufferTexture(); + _sharedFramebuffer = new FramebufferTexture(); } - super( uvNode, levelNode, sharedFramebuffer ); + super( uvNode, levelNode, _sharedFramebuffer ); } @@ -12381,6 +13716,179 @@ addNodeElement( 'viewportSharedTexture', viewportSharedTexture ); addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode ); +class PassTextureNode extends TextureNode { + + constructor( passNode, texture ) { + + super( texture ); + + this.passNode = passNode; + + this.setUpdateMatrix( false ); + + } + + setup( builder ) { + + this.passNode.build( builder ); + + return super.setup( builder ); + + } + + clone() { + + return new this.constructor( this.passNode, this.value ); + + } + +} + +class PassNode extends TempNode { + + constructor( scope, scene, camera ) { + + super( 'vec4' ); + + this.scope = scope; + this.scene = scene; + this.camera = camera; + + this._pixelRatio = 1; + this._width = 1; + this._height = 1; + + const depthTexture = new DepthTexture(); + depthTexture.isRenderTargetTexture = true; + //depthTexture.type = FloatType; + depthTexture.name = 'PostProcessingDepth'; + + const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); + renderTarget.texture.name = 'PostProcessing'; + renderTarget.depthTexture = depthTexture; + + this.renderTarget = renderTarget; + + this.updateBeforeType = NodeUpdateType.FRAME; + + this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); + this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); + + this._depthNode = null; + this._cameraNear = uniform( 0 ); + this._cameraFar = uniform( 0 ); + + this.isPassNode = true; + + } + + isGlobal() { + + return true; + + } + + getTextureNode() { + + return this._textureNode; + + } + + getTextureDepthNode() { + + return this._depthTextureNode; + + } + + getDepthNode() { + + if ( this._depthNode === null ) { + + const cameraNear = this._cameraNear; + const cameraFar = this._cameraFar; + + this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + + } + + return this._depthNode; + + } + + setup() { + + return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + + } + + updateBefore( frame ) { + + const { renderer } = frame; + const { scene, camera } = this; + + this._pixelRatio = renderer.getPixelRatio(); + + const size = renderer.getSize( new Vector2() ); + + this.setSize( size.width, size.height ); + + const currentToneMapping = renderer.toneMapping; + const currentToneMappingNode = renderer.toneMappingNode; + const currentRenderTarget = renderer.getRenderTarget(); + + this._cameraNear.value = camera.near; + this._cameraFar.value = camera.far; + + renderer.toneMapping = NoToneMapping; + renderer.toneMappingNode = null; + renderer.setRenderTarget( this.renderTarget ); + + renderer.render( scene, camera ); + + renderer.toneMapping = currentToneMapping; + renderer.toneMappingNode = currentToneMappingNode; + renderer.setRenderTarget( currentRenderTarget ); + + } + + setSize( width, height ) { + + this._width = width; + this._height = height; + + const effectiveWidth = this._width * this._pixelRatio; + const effectiveHeight = this._height * this._pixelRatio; + + this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + + } + + setPixelRatio( pixelRatio ) { + + this._pixelRatio = pixelRatio; + + this.setSize( this._width, this._height ); + + } + + dispose() { + + this.renderTarget.dispose(); + + } + + +} + +PassNode.COLOR = 'color'; +PassNode.DEPTH = 'depth'; + +const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); +const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) ); +const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); + +addNodeClass( 'PassNode', PassNode ); + // Helper for passes that need to fill the viewport with a single quad. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); @@ -12418,9 +13926,9 @@ class QuadMesh { } - render( renderer ) { + async renderAsync( renderer ) { - renderer.render( this._mesh, _camera ); + await renderer.renderAsync( this._mesh, _camera ); } @@ -12436,6 +13944,12 @@ class QuadMesh { } + get render() { + + return this.renderAsync; + + } + } // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that @@ -12448,7 +13962,7 @@ class GaussianBlurNode extends TempNode { constructor( textureNode, sigma = 2 ) { - super( textureNode ); + super( 'vec4' ); this.textureNode = textureNode; this.sigma = sigma; @@ -12463,6 +13977,8 @@ class GaussianBlurNode extends TempNode { this._verticalRT = new RenderTarget(); this._verticalRT.texture.name = 'GaussianBlurNode.vertical'; + this._textureNode = texturePass( this, this._verticalRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; this.resolution = new Vector2( 1, 1 ); @@ -12495,6 +14011,11 @@ class GaussianBlurNode extends TempNode { this.setSize( map.image.width, map.image.height ); + const textureType = map.type; + + this._horizontalRT.texture.type = textureType; + this._verticalRT.texture.type = textureType; + // horizontal renderer.setRenderTarget( this._horizontalRT ); @@ -12519,6 +14040,12 @@ class GaussianBlurNode extends TempNode { } + getTextureNode() { + + return this._textureNode; + + } + setup( builder ) { const textureNode = this.textureNode; @@ -12567,7 +14094,7 @@ class GaussianBlurNode extends TempNode { // - const material = this._material || ( this._material = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const material = this._material || ( this._material = builder.createNodeMaterial() ); material.fragmentNode = blur(); // @@ -12577,7 +14104,7 @@ class GaussianBlurNode extends TempNode { // - return texture( this._verticalRT.texture ); + return this._textureNode; } @@ -12619,10 +14146,18 @@ class AfterImageNode extends TempNode { this._oldRT = new RenderTarget(); this._oldRT.texture.name = 'AfterImageNode.old'; + this._textureNode = texturePass( this, this._compRT.texture ); + this.updateBeforeType = NodeUpdateType.RENDER; } + getTextureNode() { + + return this._textureNode; + + } + setSize( width, height ) { this._compRT.setSize( width, height ); @@ -12635,6 +14170,12 @@ class AfterImageNode extends TempNode { const { renderer } = frame; const textureNode = this.textureNode; + const map = textureNode.value; + + const textureType = map.type; + + this._compRT.texture.type = textureType; + this._oldRT.texture.type = textureType; const currentRenderTarget = renderer.getRenderTarget(); const currentTexture = textureNode.value; @@ -12651,7 +14192,6 @@ class AfterImageNode extends TempNode { this._compRT = temp; // set size before swapping fails - const map = currentTexture; this.setSize( map.image.width, map.image.height ); renderer.setRenderTarget( currentRenderTarget ); @@ -12699,7 +14239,7 @@ class AfterImageNode extends TempNode { // - const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial( 'MeshBasicNodeMaterial' ) ); + const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() ); materialComposed.fragmentNode = afterImg(); quadMeshComp.material = materialComposed; @@ -12711,7 +14251,7 @@ class AfterImageNode extends TempNode { // - return texture( this._compRT.texture ); + return this._textureNode; } @@ -12721,75 +14261,29 @@ const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( addNodeElement( 'afterImage', afterImage ); -class PassTextureNode extends TextureNode { - - constructor( passNode, texture ) { - - super( texture ); - - this.passNode = passNode; - - this.setUpdateMatrix( false ); - - } - - setup( builder ) { - - this.passNode.build( builder ); - - return super.setup( builder ); - - } - - clone() { - - return new this.constructor( this.passNode, this.value ); - - } - -} +const quadMesh = new QuadMesh(); -class PassNode extends TempNode { +class AnamorphicNode extends TempNode { - constructor( scope, scene, camera ) { + constructor( textureNode, tresholdNode, scaleNode, samples ) { super( 'vec4' ); - this.scope = scope; - this.scene = scene; - this.camera = camera; - - this._pixelRatio = 1; - this._width = 1; - this._height = 1; - - const depthTexture = new DepthTexture(); - depthTexture.isRenderTargetTexture = true; - depthTexture.type = FloatType; - depthTexture.name = 'PostProcessingDepth'; - - const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } ); - renderTarget.texture.name = 'PostProcessing'; - renderTarget.depthTexture = depthTexture; - - this.renderTarget = renderTarget; - - this.updateBeforeType = NodeUpdateType.FRAME; - - this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) ); - this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) ); - - this._depthNode = null; - this._cameraNear = uniform( 0 ); - this._cameraFar = uniform( 0 ); + this.textureNode = textureNode; + this.tresholdNode = tresholdNode; + this.scaleNode = scaleNode; + this.colorNode = vec3( 0.1, 0.0, 1.0 ); + this.samples = samples; + this.resolution = new Vector2( 1, 1 ); - this.isPassNode = true; + this._renderTarget = new RenderTarget(); + this._renderTarget.texture.name = 'anamorphic'; - } + this._invSize = uniform( new Vector2() ); - isGlobal() { + this._textureNode = texturePass( this, this._renderTarget.texture ); - return true; + this.updateBeforeType = NodeUpdateType.RENDER; } @@ -12799,99 +14293,106 @@ class PassNode extends TempNode { } - getTextureDepthNode() { + setSize( width, height ) { - return this._depthTextureNode; + this._invSize.value.set( 1 / width, 1 / height ); + + width = Math.max( Math.round( width * this.resolution.x ), 1 ); + height = Math.max( Math.round( height * this.resolution.y ), 1 ); + + this._renderTarget.setSize( width, height ); } - getDepthNode() { + updateBefore( frame ) { - if ( this._depthNode === null ) { + const { renderer } = frame; - const cameraNear = this._cameraNear; - const cameraFar = this._cameraFar; + const textureNode = this.textureNode; + const map = textureNode.value; - this._depthNode = viewZToOrthographicDepth( perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar ), cameraNear, cameraFar ); + this._renderTarget.texture.type = map.type; - } + const currentRenderTarget = renderer.getRenderTarget(); + const currentTexture = textureNode.value; - return this._depthNode; + quadMesh.material = this._material; - } + this.setSize( map.image.width, map.image.height ); - setup() { + // render - return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getDepthNode(); + renderer.setRenderTarget( this._renderTarget ); + + quadMesh.render( renderer ); + + // restore + + renderer.setRenderTarget( currentRenderTarget ); + textureNode.value = currentTexture; } - updateBefore( frame ) { + setup( builder ) { - const { renderer } = frame; - const { scene, camera } = this; + const textureNode = this.textureNode; - this._pixelRatio = renderer.getPixelRatio(); + if ( textureNode.isTextureNode !== true ) { - const size = renderer.getSize( new Vector2() ); + return vec4(); - this.setSize( size.width, size.height ); + } - const currentToneMapping = renderer.toneMapping; - const currentToneMappingNode = renderer.toneMappingNode; - const currentRenderTarget = renderer.getRenderTarget(); + // - this._cameraNear.value = camera.near; - this._cameraFar.value = camera.far; + const uvNode = textureNode.uvNode || uv(); - renderer.toneMapping = NoToneMapping; - renderer.toneMappingNode = null; - renderer.setRenderTarget( this.renderTarget ); + const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } ); - renderer.render( scene, camera ); + const anamorph = tslFn( () => { - renderer.toneMapping = currentToneMapping; - renderer.toneMappingNode = currentToneMappingNode; - renderer.setRenderTarget( currentRenderTarget ); + const samples = this.samples; + const halfSamples = Math.floor( samples / 2 ); - } + const total = vec3( 0 ).toVar(); - setSize( width, height ) { + loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => { - this._width = width; - this._height = height; + const softness = float( i ).abs().div( halfSamples ).oneMinus(); - const effectiveWidth = this._width * this._pixelRatio; - const effectiveHeight = this._height * this._pixelRatio; + const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y ); + const color = sampleTexture( uv ); + const pass = threshold( color, this.tresholdNode ).mul( softness ); - this.renderTarget.setSize( effectiveWidth, effectiveHeight ); + total.addAssign( pass ); - } + } ); - setPixelRatio( pixelRatio ) { + return total.mul( this.colorNode ); - this._pixelRatio = pixelRatio; + } ); - this.setSize( this._width, this._height ); + // - } + const material = this._material || ( this._material = builder.createNodeMaterial() ); + material.fragmentNode = anamorph(); - dispose() { + // - this.renderTarget.dispose(); + const properties = builder.getNodeProperties( this ); + properties.textureNode = textureNode; - } + // + return this._textureNode; -} + } -PassNode.COLOR = 'color'; -PassNode.DEPTH = 'depth'; +} -const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) ); -const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) ); +const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ), nodeObject( threshold ), nodeObject( scale ), samples ) ); -addNodeClass( 'PassNode', PassNode ); +addNodeElement( 'anamorphic', anamorphic ); class FunctionCallNode extends TempNode { @@ -13643,7 +15144,7 @@ class FogNode extends Node { mixAssign( outputNode ) { - return this.mix( outputNode, this.colorNode ); + return mix( outputNode, this.colorNode, this ); } @@ -16173,13 +17674,7 @@ class SpriteNodeMaterial extends NodeMaterial { const rotation = float( rotationNode || materialRotation ); - const cosAngle = rotation.cos(); - const sinAngle = rotation.sin(); - - const rotatedPosition = vec2( // @TODO: Maybe we can create mat2 and write something like rotationMatrix.mul( alignedPosition )? - vec2( cosAngle, sinAngle.negate() ).dot( alignedPosition ), - vec2( sinAngle, cosAngle ).dot( alignedPosition ) - ); + const rotatedPosition = alignedPosition.rotate( rotation ); mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw ); @@ -18384,6 +19879,8 @@ class RenderContext { this.width = 0; this.height = 0; + this.isRenderContext = true; + } } @@ -18408,19 +19905,8 @@ class RenderContexts { } else { - let format, count; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - format = renderTarget.texture[ 0 ].format; - count = renderTarget.texture.length; - - } else { - - format = renderTarget.texture.format; - count = 1; - - } + const format = renderTarget.texture.format; + const count = renderTarget.count; attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`; @@ -18462,10 +19948,11 @@ const _size = new Vector3(); class Textures extends DataMap { - constructor( backend, info ) { + constructor( renderer, backend, info ) { super(); + this.renderer = renderer; this.backend = backend; this.info = info; @@ -18478,19 +19965,8 @@ class Textures extends DataMap { const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples; const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} ); - let texture, textures; - - if ( renderTarget.isWebGLMultipleRenderTargets ) { - - textures = renderTarget.texture; - texture = renderTarget.texture[ 0 ]; - - } else { - - textures = [ renderTarget.texture ]; - texture = renderTarget.texture; - - } + const texture = renderTarget.texture; + const textures = renderTarget.textures; const size = this.getSize( texture ); @@ -18503,8 +19979,8 @@ class Textures extends DataMap { if ( depthTexture === undefined ) { depthTexture = new DepthTexture(); - depthTexture.format = DepthStencilFormat; - depthTexture.type = UnsignedInt248Type; + depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat; + depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; depthTexture.image.width = mipWidth; depthTexture.image.height = mipHeight; @@ -18528,6 +20004,7 @@ class Textures extends DataMap { renderTargetData.depthTexture = depthTexture; renderTargetData.depth = renderTarget.depthBuffer; renderTargetData.stencil = renderTarget.stencilBuffer; + renderTargetData.renderTarget = renderTarget; if ( renderTargetData.sampleCount !== sampleCount ) { @@ -18609,6 +20086,25 @@ class Textures extends DataMap { // + if ( texture.isFramebufferTexture ) { + + const renderer = this.renderer; + const renderTarget = renderer.getRenderTarget(); + + if ( renderTarget ) { + + texture.type = renderTarget.texture.type; + + } else { + + texture.type = UnsignedByteType; + + } + + } + + // + const { width, height, depth } = this.getSize( texture ); options.width = width; @@ -18662,7 +20158,7 @@ class Textures extends DataMap { } - backend.updateTexture( texture, options ); + if ( texture.source.dataReady === true ) backend.updateTexture( texture, options ); if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture ); @@ -18863,7 +20359,7 @@ class Background extends DataMap { const backgroundMeshNode = context( vec4( backgroundNode ), { // @TODO: Add Texture2D support using node context getUV: () => normalWorld, - getTextureLevel: () => backgroundBlurriness + getTextureLevel: ( textureNode ) => backgroundBlurriness.mul( maxMipLevel( textureNode ) ) } ).mul( backgroundIntensity ); let viewProj = modelViewProjection(); @@ -18939,11 +20435,12 @@ class Background extends DataMap { class NodeBuilderState { - constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes ) { + constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, transforms = [] ) { this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; this.computeShader = computeShader; + this.transforms = transforms; this.nodeAttributes = nodeAttributes; this.bindings = bindings; @@ -19089,6 +20586,7 @@ class Nodes extends DataMap { nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene ); nodeBuilder.fogNode = this.getFogNode( renderObject.scene ); nodeBuilder.toneMappingNode = this.getToneMappingNode(); + nodeBuilder.clippingContext = renderObject.clippingContext; nodeBuilder.build(); nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); @@ -19139,7 +20637,7 @@ class Nodes extends DataMap { nodeBuilderState = this._createNodeBuilderState( nodeBuilder ); - computeData.nodeBuilderState = nodeBuilder; + computeData.nodeBuilderState = nodeBuilderState; } @@ -19156,7 +20654,8 @@ class Nodes extends DataMap { nodeBuilder.getAttributesArray(), nodeBuilder.getBindings(), nodeBuilder.updateNodes, - nodeBuilder.updateBeforeNodes + nodeBuilder.updateBeforeNodes, + nodeBuilder.transforms ); } @@ -19499,6 +20998,8 @@ class Renderer { this.depth = true; this.stencil = true; + this.clippingPlanes = []; + this.info = new Info(); // internals @@ -19542,9 +21043,13 @@ class Renderer { this._renderObjectFunction = null; this._currentRenderObjectFunction = null; + this._handleObjectFunction = this._renderObjectDirect; + this._initialized = false; this._initPromise = null; + this._compilationPromises = null; + // backwards compatibility this.shadowMap = { @@ -19560,70 +21065,210 @@ class Renderer { async init() { - if ( this._initialized ) { + if ( this._initialized ) { + + throw new Error( 'Renderer: Backend has already been initialized.' ); + + } + + if ( this._initPromise !== null ) { + + return this._initPromise; + + } + + this._initPromise = new Promise( async ( resolve, reject ) => { + + const backend = this.backend; + + try { + + await backend.init( this ); + + } catch ( error ) { + + reject( error ); + return; + + } + + this._nodes = new Nodes( this, backend ); + this._animation = new Animation( this._nodes, this.info ); + this._attributes = new Attributes( backend ); + this._background = new Background( this, this._nodes ); + this._geometries = new Geometries( this._attributes, this.info ); + this._textures = new Textures( this, backend, this.info ); + this._pipelines = new Pipelines( backend, this._nodes ); + this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); + this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); + this._renderLists = new RenderLists(); + this._renderContexts = new RenderContexts(); + + // + + this._initialized = true; + + resolve(); + + } ); + + return this._initPromise; + + } + + get coordinateSystem() { + + return this.backend.coordinateSystem; + + } + + async compileAsync( scene, camera, targetScene = null ) { + + if ( this._initialized === false ) await this.init(); + + // preserve render tree + + const nodeFrame = this._nodes.nodeFrame; + + const previousRenderId = nodeFrame.renderId; + const previousRenderContext = this._currentRenderContext; + const previousRenderObjectFunction = this._currentRenderObjectFunction; + const previousCompilationPromises = this._compilationPromises; + + // + + const sceneRef = ( scene.isScene === true ) ? scene : _scene; + + if ( targetScene === null ) targetScene = scene; + + const renderTarget = this._renderTarget; + const renderContext = this._renderContexts.get( targetScene, camera, renderTarget ); + const activeMipmapLevel = this._activeMipmapLevel; + + const compilationPromises = []; + + this._currentRenderContext = renderContext; + this._currentRenderObjectFunction = this.renderObject; + + this._handleObjectFunction = this._createObjectPipeline; + + this._compilationPromises = compilationPromises; + + nodeFrame.renderId ++; + + // + + nodeFrame.update(); + + // + + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; + + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); + + // + + sceneRef.onBeforeRender( this, scene, camera, renderTarget ); + + // + + const renderList = this._renderLists.get( scene, camera ); + renderList.begin(); + + this._projectObject( scene, camera, 0, renderList ); + + // include lights from target scene + if ( targetScene !== scene ) { + + targetScene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + renderList.pushLight( object ); + + } + + } ); + + } + + renderList.finish(); + + // + + if ( renderTarget !== null ) { + + this._textures.updateRenderTarget( renderTarget, activeMipmapLevel ); + + const renderTargetData = this._textures.get( renderTarget ); + + renderContext.textures = renderTargetData.textures; + renderContext.depthTexture = renderTargetData.depthTexture; + + } else { - throw new Error( 'Renderer: Backend has already been initialized.' ); + renderContext.textures = null; + renderContext.depthTexture = null; } - if ( this._initPromise !== null ) { + // - return this._initPromise; + this._nodes.updateScene( sceneRef ); - } + // - this._initPromise = new Promise( async ( resolve, reject ) => { + this._background.update( sceneRef, renderList, renderContext ); - const backend = this.backend; + // process render lists - try { + const opaqueObjects = renderList.opaque; + const transparentObjects = renderList.transparent; + const lightsNode = renderList.lightsNode; - await backend.init( this ); + if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode ); + if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode ); - } catch ( error ) { + // restore render tree - reject( error ); - return; + nodeFrame.renderId = previousRenderId; - } + this._currentRenderContext = previousRenderContext; + this._currentRenderObjectFunction = previousRenderObjectFunction; + this._compilationPromises = previousCompilationPromises; - this._nodes = new Nodes( this, backend ); - this._animation = new Animation( this._nodes, this.info ); - this._attributes = new Attributes( backend ); - this._background = new Background( this, this._nodes ); - this._geometries = new Geometries( this._attributes, this.info ); - this._textures = new Textures( backend, this.info ); - this._pipelines = new Pipelines( backend, this._nodes ); - this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info ); - this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info ); - this._renderLists = new RenderLists(); - this._renderContexts = new RenderContexts(); + this._handleObjectFunction = this._renderObjectDirect; - // + // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete - this._initialized = true; + await Promise.all( compilationPromises ); - resolve(); + } - } ); + async renderAsync( scene, camera ) { - return this._initPromise; + if ( this._initialized === false ) await this.init(); + + const renderContext = this._renderContext( scene, camera ); + + await this.backend.resolveTimestampAsync( renderContext, 'render' ); } - get coordinateSystem() { + render( scene, camera ) { - return this.backend.coordinateSystem; + if ( this._initialized === false ) { + return; - } + } - async compile( /*scene, camera*/ ) { + this._renderContext( scene, camera ); } - async render( scene, camera ) { - - if ( this._initialized === false ) await this.init(); + _renderContext( scene, camera ) { // preserve render tree @@ -19705,8 +21350,8 @@ class Renderer { renderContext.scissorValue.width >>= activeMipmapLevel; renderContext.scissorValue.height >>= activeMipmapLevel; - renderContext.depth = this.depth; - renderContext.stencil = this.stencil; + if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext(); + renderContext.clippingContext.updateGlobal( this, camera ); // @@ -19743,6 +21388,8 @@ class Renderer { renderContext.width = renderTargetData.width; renderContext.height = renderTargetData.height; renderContext.renderTarget = renderTarget; + renderContext.depth = renderTarget.depthBuffer; + renderContext.stencil = renderTarget.stencilBuffer; } else { @@ -19750,6 +21397,8 @@ class Renderer { renderContext.depthTexture = null; renderContext.width = this.domElement.width; renderContext.height = this.domElement.height; + renderContext.depth = this.depth; + renderContext.stencil = this.stencil; } @@ -19795,6 +21444,10 @@ class Renderer { sceneRef.onAfterRender( this, scene, camera, renderTarget ); + // + + return renderContext; + } getMaxAnisotropy() { @@ -19955,6 +21608,8 @@ class Renderer { this._scissorTest = boolean; + this.backend.setScissorTest( boolean ); + } getViewport( target ) { @@ -20058,19 +21713,45 @@ class Renderer { clearColor() { - this.clear( true, false, false ); + return this.clear( true, false, false ); } clearDepth() { - this.clear( false, true, false ); + return this.clear( false, true, false ); } clearStencil() { - this.clear( false, false, true ); + return this.clear( false, false, true ); + + } + + async clearAsync( color = true, depth = true, stencil = true ) { + + if ( this._initialized === false ) await this.init(); + + this.clear( color, depth, stencil ); + + } + + clearColorAsync() { + + return this.clearAsync( true, false, false ); + + } + + clearDepthAsync() { + + return this.clearAsync( false, true, false ); + + } + + clearStencilAsync() { + + return this.clearAsync( false, false, true ); } @@ -20134,7 +21815,7 @@ class Renderer { } - async compute( computeNodes ) { + async computeAsync( computeNodes ) { if ( this._initialized === false ) await this.init(); @@ -20146,10 +21827,12 @@ class Renderer { this.info.calls ++; this.info.compute.calls ++; + this.info.compute.computeCalls ++; nodeFrame.renderId = this.info.calls; // + if ( this.info.autoReset === true ) this.info.resetCompute(); const backend = this.backend; const pipelines = this._pipelines; @@ -20201,12 +21884,20 @@ class Renderer { backend.finishCompute( computeNodes ); + await this.backend.resolveTimestampAsync( computeNodes, 'compute' ); + // nodeFrame.renderId = previousRenderId; } + hasFeatureAsync( name ) { + + return this.backend.hasFeatureAsync( name ); + + } + hasFeature( name ) { return this.backend.hasFeature( name ); @@ -20380,6 +22071,7 @@ class Renderer { renderObject( object, scene, camera, geometry, material, group, lightsNode ) { let overridePositionNode; + let overrideFragmentNode; // @@ -20401,6 +22093,45 @@ class Renderer { } + if ( overrideMaterial.isShadowNodeMaterial ) { + + overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide; + + if ( material.shadowNode && material.shadowNode.isNode ) { + + overrideFragmentNode = overrideMaterial.fragmentNode; + overrideMaterial.fragmentNode = material.shadowNode; + + } + + if ( this.localClippingEnabled ) { + + if ( material.clipShadows ) { + + if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) { + + overrideMaterial.clippingPlanes = material.clippingPlanes; + overrideMaterial.needsUpdate = true; + + } + + if ( overrideMaterial.clipIntersection !== material.clipIntersection ) { + + overrideMaterial.clipIntersection = material.clipIntersection; + + } + + } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) { + + overrideMaterial.clippingPlanes = null; + overrideMaterial.needsUpdate = true; + + } + + } + + } + material = overrideMaterial; } @@ -20410,16 +22141,16 @@ class Renderer { if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { material.side = BackSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id material.side = FrontSide; - this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id + this._handleObjectFunction( object, material, scene, camera, lightsNode ); // use default pass id material.side = DoubleSide; } else { - this._renderObjectDirect( object, material, scene, camera, lightsNode ); + this._handleObjectFunction( object, material, scene, camera, lightsNode ); } @@ -20431,6 +22162,12 @@ class Renderer { } + if ( overrideFragmentNode !== undefined ) { + + scene.overrideMaterial.fragmentNode = overrideFragmentNode; + + } + // object.onAfterRender( this, scene, camera, geometry, material, group ); @@ -20463,6 +22200,36 @@ class Renderer { } + _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) { + + const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId ); + + // + + this._nodes.updateBefore( renderObject ); + + // + + this._nodes.updateForRender( renderObject ); + this._geometries.updateForRender( renderObject ); + this._bindings.updateForRender( renderObject ); + + this._pipelines.getForRender( renderObject, this._compilationPromises ); + + } + + get compute() { + + return this.computeAsync; + + } + + get compile() { + + return this.compileAsync; + + } + } class Binding { @@ -20497,24 +22264,6 @@ function getFloatLength( floatLength ) { } -function getVectorLength( count, vectorLength = 4 ) { - - const strideLength = getStrideLength( vectorLength ); - - const floatLength = strideLength * count; - - return getFloatLength( floatLength ); - -} - -function getStrideLength( vectorLength ) { - - const strideLength = 4; - - return vectorLength + ( ( strideLength - ( vectorLength % strideLength ) ) % strideLength ); - -} - class Buffer extends Binding { constructor( name, buffer = null ) { @@ -20561,6 +22310,26 @@ class UniformBuffer extends Buffer { } +let _id$2 = 0; + +class NodeUniformBuffer extends UniformBuffer { + + constructor( nodeUniform ) { + + super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + +} + class UniformsGroup extends UniformBuffer { constructor( name ) { @@ -20623,6 +22392,8 @@ class UniformsGroup extends UniformBuffer { const uniform = this.uniforms[ i ]; + const { boundary, itemSize } = uniform; + // offset within a single chunk in bytes const chunkOffset = offset % GPU_CHUNK_BYTES; @@ -20630,23 +22401,23 @@ class UniformsGroup extends UniformBuffer { // conformance tests - if ( chunkOffset !== 0 && ( remainingSizeInChunk - uniform.boundary ) < 0 ) { + if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) { // check for chunk overflow offset += ( GPU_CHUNK_BYTES - chunkOffset ); - } else if ( chunkOffset % uniform.boundary !== 0 ) { + } else if ( chunkOffset % boundary !== 0 ) { // check for correct alignment - offset += ( chunkOffset % uniform.boundary ); + offset += ( chunkOffset % boundary ); } uniform.offset = ( offset / this.bytesPerElement ); - offset += ( uniform.itemSize * this.bytesPerElement ); + offset += ( itemSize * this.bytesPerElement ); } @@ -20987,7 +22758,8 @@ class NodeSampledCubeTexture extends NodeSampledTexture { const glslMethods = { [ MathNode.ATAN2 ]: 'atan', - textureDimensions: 'textureSize' + textureDimensions: 'textureSize', + equals: 'equal' }; const precisionLib = { @@ -20997,7 +22769,8 @@ const precisionLib = { }; const supports$1 = { - instance: true + instance: true, + swizzleAssign: true }; const defaultPrecisions = ` @@ -21014,6 +22787,7 @@ class GLSLNodeBuilder extends NodeBuilder { super( object, renderer, new GLSLNodeParser(), scene ); this.uniformGroups = {}; + this.transforms = []; } @@ -21061,6 +22835,130 @@ ${ flowData.code } } + setupPBO( storageBufferNode ) { + + const attribute = storageBufferNode.value; + + if ( attribute.pbo === undefined ) { + + const originalArray = attribute.array; + const numElements = attribute.count * attribute.itemSize; + + const { itemSize } = attribute; + let format = RedFormat; + + if ( itemSize === 2 ) { + + format = RGFormat; + + } else if ( itemSize === 3 ) { + + format = 6407; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization + + } else if ( itemSize === 4 ) { + + format = RGBAFormat; + + } + + const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) ); + let height = Math.ceil( ( numElements / itemSize ) / width ); + if ( width * height * itemSize < numElements ) height ++; // Ensure enough space + + const newSize = width * height * itemSize; + + const newArray = new Float32Array( newSize ); + + newArray.set( originalArray, 0 ); + + attribute.array = newArray; + + const pboTexture = new DataTexture( attribute.array, width, height, format, FloatType ); + pboTexture.needsUpdate = true; + pboTexture.isPBOTexture = true; + + const pbo = new UniformNode( pboTexture ); + pbo.setPrecision( 'high' ); + + attribute.pboNode = pbo; + attribute.pbo = pbo.value; + + this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + + } + + } + + generatePBO( storageArrayElementNode ) { + + const { node, indexNode } = storageArrayElementNode; + const attribute = node.value; + + if ( this.renderer.backend.has( attribute ) ) { + + const attributeData = this.renderer.backend.get( attribute ); + attributeData.pbo = attribute.pbo; + + } + + + const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label ); + const textureName = this.getPropertyName( nodeUniform ); + + indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y + const indexSnippet = indexNode.build( this, 'uint' ); + + const elementNodeData = this.getDataFromNode( storageArrayElementNode ); + + let propertyName = elementNodeData.propertyName; + + if ( propertyName === undefined ) { + + // property element + + const nodeVar = this.getVarFromNode( storageArrayElementNode ); + + propertyName = this.getPropertyName( nodeVar ); + + // property size + + const bufferNodeData = this.getDataFromNode( node ); + + let propertySizeName = bufferNodeData.propertySizeName; + + if ( propertySizeName === undefined ) { + + propertySizeName = propertyName + 'Size'; + + this.getVarFromNode( node, propertySizeName, 'uint' ); + + this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` ); + + bufferNodeData.propertySizeName = propertySizeName; + + } + + // + + const { itemSize } = attribute; + + const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize ); + const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`; + + const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' ); + + // + + this.addLineFlowCode( `${ propertyName } = ${ snippet + channel }` ); + + elementNodeData.propertyName = propertyName; + + } + + return propertyName; + + } + generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) { if ( depthSnippet ) { @@ -21253,7 +23151,7 @@ ${ flowData.code } let snippet = ''; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { const attributes = this.getAttributesArray(); @@ -21320,10 +23218,11 @@ ${ flowData.code } const varyings = this.varyings; - if ( shaderStage === 'vertex' ) { + if ( shaderStage === 'vertex' || shaderStage === 'compute' ) { for ( const varying of varyings ) { + if ( shaderStage === 'compute' ) varying.needsInterpolation = true; const type = varying.type; const flat = type === 'int' || type === 'uint' ? 'flat ' : ''; @@ -21380,18 +23279,43 @@ ${ flowData.code } return 'gl_FragDepth'; - } + } + + isAvailable( name ) { + + return supports$1[ name ] === true; + + } + + isFlipY() { + + return true; + + } + + registerTransform( varyingName, attributeNode ) { + + this.transforms.push( { varyingName, attributeNode } ); + + } + + getTransforms( /* shaderStage */ ) { + + const transforms = this.transforms; + + let snippet = ''; - isAvailable( name ) { + for ( let i = 0; i < transforms.length; i ++ ) { - return supports$1[ name ] === true; + const transform = transforms[ i ]; - } + const attributeName = this.getPropertyName( transform.attributeNode ); + snippet += `${ transform.varyingName } = ${ attributeName };\n\t`; - isFlipY() { + } - return true; + return snippet; } @@ -21430,6 +23354,9 @@ void main() { // vars ${shaderData.vars} + // transforms + ${shaderData.transforms} + // flow ${shaderData.flow} @@ -21532,6 +23459,7 @@ void main() { stageData.vars = this.getVars( shaderStage ); stageData.structs = this.getStructs( shaderStage ); stageData.codes = this.getCodes( shaderStage ); + stageData.transforms = this.getTransforms( shaderStage ); stageData.flow = flow; } @@ -21541,6 +23469,10 @@ void main() { this.vertexShader = this._getGLSLVertexCode( shadersData.vertex ); this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment ); + } else { + + this.computeShader = this._getGLSLVertexCode( shadersData.compute ); + } } @@ -21568,11 +23500,11 @@ void main() { } else if ( type === 'buffer' ) { - node.name = `NodeBuffer_${node.id}`; - - const buffer = new UniformBuffer( node.name, node.value ); + node.name = `NodeBuffer_${ node.id }`; + uniformNode.name = `buffer${ node.id }`; - uniformNode.name = `buffer${node.id}`; + const buffer = new NodeUniformBuffer( node ); + buffer.name = node.name; this.bindings[ shaderStage ].push( buffer ); @@ -21703,6 +23635,10 @@ class Backend { // utils + resolveTimestampAsync( renderContext, type ) { } + + hasFeatureAsync( name ) { } // return Boolean + hasFeature( name ) { } // return Boolean getInstanceCount( renderObject ) { @@ -21729,6 +23665,8 @@ class Backend { } + setScissorTest( boolean ) { } + getClearColor() { const renderer = this.renderer; @@ -21785,6 +23723,12 @@ class Backend { } + has( object ) { + + return this.data.has( object ); + + } + delete( object ) { this.data.delete( object ); @@ -21793,6 +23737,52 @@ class Backend { } +let _id$1 = 0; + +class DualAttributeData { + + constructor( attributeData, dualBuffer ) { + + this.buffers = [ attributeData.bufferGPU, dualBuffer ]; + this.type = attributeData.type; + this.bufferType = attributeData.bufferType; + this.pbo = attributeData.pbo; + this.byteLength = attributeData.byteLength; + this.bytesPerElement = attributeData.BYTES_PER_ELEMENT; + this.version = attributeData.version; + this.isInteger = attributeData.isInteger; + this.activeBufferIndex = 0; + this.baseId = attributeData.id; + + } + + + get id() { + + return `${ this.baseId }|${ this.activeBufferIndex }`; + + } + + get bufferGPU() { + + return this.buffers[ this.activeBufferIndex ]; + + } + + get transformBuffer() { + + return this.buffers[ this.activeBufferIndex ^ 1 ]; + + } + + switchBuffers() { + + this.activeBufferIndex ^= 1; + + } + +} + class WebGLAttributeUtils { constructor( backend ) { @@ -21816,11 +23806,7 @@ class WebGLAttributeUtils { if ( bufferGPU === undefined ) { - bufferGPU = gl.createBuffer(); - - gl.bindBuffer( bufferType, bufferGPU ); - gl.bufferData( bufferType, array, usage ); - gl.bindBuffer( bufferType, null ); + bufferGPU = this._createBuffer( gl, bufferType, array, usage ); bufferData.bufferGPU = bufferGPU; bufferData.bufferType = bufferType; @@ -21878,13 +23864,27 @@ class WebGLAttributeUtils { } - backend.set( attribute, { + let attributeData = { bufferGPU, + bufferType, type, + byteLength: array.byteLength, bytesPerElement: array.BYTES_PER_ELEMENT, version: attribute.version, - isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType - } ); + pbo: attribute.pbo, + isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType, + id: _id$1 ++ + }; + + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) { + + // create buffer for tranform feedback use + const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage ); + attributeData = new DualAttributeData( attributeData, bufferGPUDual ); + + } + + backend.set( attribute, attributeData ); } @@ -21978,6 +23978,18 @@ class WebGLAttributeUtils { } + _createBuffer( gl, bufferType, array, usage ) { + + const bufferGPU = gl.createBuffer(); + + gl.bindBuffer( bufferType, bufferGPU ); + gl.bufferData( bufferType, array, usage ); + gl.bindBuffer( bufferType, null ); + + return bufferGPU; + + } + } let initialized$1 = false, equationToGL, factorToGL; @@ -22735,6 +24747,7 @@ class WebGLUtils { } if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === gl.RGB ) return gl.RGB; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization if ( p === RGBAFormat ) return gl.RGBA; if ( p === LuminanceFormat ) return gl.LUMINANCE; if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA; @@ -23114,6 +25127,17 @@ class WebGLTextureUtils { } + if ( glFormat === gl.RGB ) { + + if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F; + if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F; + if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8; + if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565; + if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1; + if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4; + + } + if ( glFormat === gl.RGBA ) { if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F; @@ -23151,7 +25175,9 @@ class WebGLTextureUtils { setTextureParameters( textureType, texture ) { - const { gl, extensions } = this; + const { gl, extensions, backend } = this; + + const { currentAnisotropy } = backend.get( texture ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); @@ -23166,7 +25192,7 @@ class WebGLTextureUtils { // follow WebGPU backend mapping for texture filtering - const minFilter = texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; + const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter; gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] ); @@ -23179,13 +25205,17 @@ class WebGLTextureUtils { if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { - //extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - if ( texture.magFilter === NearestFilter ) return; if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 - if ( texture.anisotropy > 1 /*|| properties.get( texture ).__currentAnisotropy*/ ) ; + if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) ); + backend.get( texture ).currentAnisotropy = texture.anisotropy; + + } } @@ -23263,6 +25293,41 @@ class WebGLTextureUtils { } + copyBufferToTexture( buffer, texture ) { + + const { gl, backend } = this; + + const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture ); + + const { width, height } = texture.source.data; + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer ); + + backend.state.bindTexture( glTextureType, textureGPU ); + + gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false ); + gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false ); + gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 ); + + gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null ); + + backend.state.unbindTexture(); + // debug + // const framebuffer = gl.createFramebuffer(); + // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer ); + // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 ); + + // const readout = new Float32Array( width * height * 4 ); + + // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ); + // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ); + + // gl.readPixels( 0, 0, width, height, altFormat, altType, readout ); + // gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + // console.log( readout ); + + } + updateTexture( texture, options ) { const { gl } = this; @@ -23452,21 +25517,25 @@ class WebGLTextureUtils { const width = texture.image.width; const height = texture.image.height; - state.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); - if ( texture.isDepthTexture ) { - const fb = gl.createFramebuffer(); + let mask = gl.DEPTH_BUFFER_BIT; + + if ( renderContext.stencil ) { + + mask |= gl.STENCIL_BUFFER_BIT; + + } - gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); + const fb = gl.createFramebuffer(); + state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb ); gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, textureGPU, 0 ); - gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST ); + gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST ); gl.deleteFramebuffer( fb ); - } else { state.bindTexture( gl.TEXTURE_2D, textureGPU ); @@ -23586,10 +25655,11 @@ class WebGLTextureUtils { if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array; if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array; - if ( glType === gl.UNSIGNED_INT ) return Uint32Array; - if ( glType === gl.UNSIGNED_FLOAT ) return Float32Array; + if ( glType === gl.FLOAT ) return Float32Array; + + throw new Error( `Unsupported WebGL type: ${glType}` ); } @@ -23718,7 +25788,12 @@ class WebGLBackend extends Backend { this.state = new WebGLState( this ); this.utils = new WebGLUtils( this ); + this.vaoCache = {}; + this.transformFeedbackCache = {}; + this.discard = false; + this.extensions.get( 'EXT_color_buffer_float' ); + this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' ); this._currentContext = null; } @@ -23755,7 +25830,7 @@ class WebGLBackend extends Backend { this._setFramebuffer( renderContext ); - this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext ); + this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false ); // if ( renderContext.viewport ) { @@ -23768,6 +25843,14 @@ class WebGLBackend extends Backend { } + if ( renderContext.scissor ) { + + const { x, y, width, height } = renderContext.scissorValue; + + gl.scissor( x, y, width, height ); + + } + const occlusionQueryCount = renderContext.occlusionQueryCount; if ( occlusionQueryCount > 0 ) { @@ -23960,7 +26043,23 @@ class WebGLBackend extends Backend { } - clear( color, depth, stencil, descriptor = null ) { + setScissorTest( boolean ) { + + const gl = this.gl; + + if ( boolean ) { + + gl.enable( gl.SCISSOR_TEST ); + + } else { + + gl.disable( gl.SCISSOR_TEST ); + + } + + } + + clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) { const { gl } = this; @@ -23983,7 +26082,7 @@ class WebGLBackend extends Backend { if ( clear !== 0 ) { - const clearColor = descriptor.clearColorValue; + const clearColor = descriptor.clearColorValue || this.getClearColor(); if ( depth ) this.state.setDepthMask( true ); @@ -23994,6 +26093,8 @@ class WebGLBackend extends Backend { } else { + if ( setFrameBuffer ) this._setFramebuffer( descriptor ); + if ( color ) { for ( let i = 0; i < descriptor.textures.length; i ++ ) { @@ -24026,20 +26127,95 @@ class WebGLBackend extends Backend { beginCompute( /*computeGroup*/ ) { + const gl = this.gl; + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + } - compute( /*computeGroup, computeNode, bindings, pipeline*/ ) { + compute( computeGroup, computeNode, bindings, pipeline ) { + + const gl = this.gl; + + if ( ! this.discard ) { + + // required here to handle async behaviour of render.compute() + gl.enable( gl.RASTERIZER_DISCARD ); + this.discard = true; + + } + + const { programGPU, transformBuffers, attributes } = this.get( pipeline ); + + const vaoKey = this._getVaoKey( null, attributes ); + + const vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + this._createVao( null, attributes ); + + } else { + + gl.bindVertexArray( vaoGPU ); + + } + + gl.useProgram( programGPU ); + + this._bindUniforms( bindings ); + + const transformFeedbackGPU = this._getTransformFeedback( transformBuffers ); + + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); + gl.beginTransformFeedback( gl.POINTS ); + + if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) { + + gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count ); + + } else { + + gl.drawArrays( gl.POINTS, 0, computeNode.count ); + + } + + gl.endTransformFeedback(); + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); + + // switch active buffers + + for ( let i = 0; i < transformBuffers.length; i ++ ) { + + const dualAttributeData = transformBuffers[ i ]; + + if ( dualAttributeData.pbo ) { + + this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo ); + + } + + dualAttributeData.switchBuffers(); + + + } } finishCompute( /*computeGroup*/ ) { + const gl = this.gl; + + this.discard = false; + + gl.disable( gl.RASTERIZER_DISCARD ); + } draw( renderObject, info ) { const { pipeline, material, context } = renderObject; - const { programGPU, vaoGPU } = this.get( pipeline ); + const { programGPU } = this.get( pipeline ); const { gl, state } = this; @@ -24047,28 +26223,34 @@ class WebGLBackend extends Backend { // - const bindings = renderObject.getBindings(); + this._bindUniforms( renderObject.getBindings() ); - for ( const binding of bindings ) { + state.setMaterial( material ); - const bindingData = this.get( binding ); - const index = bindingData.index; + gl.useProgram( programGPU ); - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + // - gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); + let vaoGPU = renderObject.staticVao; - } else if ( binding.isSampledTexture ) { + if ( vaoGPU === undefined ) { - state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); + const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() ); + + vaoGPU = this.vaoCache[ vaoKey ]; + + if ( vaoGPU === undefined ) { + + let staticVao; + + ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) ); + + if ( staticVao ) renderObject.staticVao = vaoGPU; } } - state.setMaterial( material ); - - gl.useProgram( programGPU ); gl.bindVertexArray( vaoGPU ); // @@ -24150,7 +26332,6 @@ class WebGLBackend extends Backend { } - info.update( object, indexCount, 1 ); } else { @@ -24174,8 +26355,6 @@ class WebGLBackend extends Backend { } - - // gl.bindVertexArray( null ); @@ -24256,7 +26435,7 @@ class WebGLBackend extends Backend { const gl = this.gl; const { stage, code } = program; - const shader = stage === 'vertex' ? gl.createShader( gl.VERTEX_SHADER ) : gl.createShader( gl.FRAGMENT_SHADER ); + const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER ); gl.shaderSource( shader, code ); gl.compileShader( shader ); @@ -24271,7 +26450,7 @@ class WebGLBackend extends Backend { } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const gl = this.gl; const pipeline = renderObject.pipeline; @@ -24289,109 +26468,159 @@ class WebGLBackend extends Backend { gl.attachShader( programGPU, vertexShader ); gl.linkProgram( programGPU ); + this.set( pipeline, { + programGPU, + fragmentShader, + vertexShader + } ); + + if ( promises !== null && this.parallel ) { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + const parallel = this.parallel; + const checkStatus = () => { + + if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) { + + this._completeCompile( renderObject, pipeline ); + resolve(); + + } else { + + requestAnimationFrame( checkStatus ); + + } + + }; + + checkStatus(); + + } ); + + promises.push( p ); + + return; + + } + + this._completeCompile( renderObject, pipeline ); + + } + + _completeCompile( renderObject, pipeline ) { + + const gl = this.gl; + const pipelineData = this.get( pipeline ); + const { programGPU, fragmentShader, vertexShader } = pipelineData; + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; gl.useProgram( programGPU ); // Bindings - const bindings = renderObject.getBindings(); + this._setupBindings( renderObject.getBindings(), programGPU ); - for ( const binding of bindings ) { + // - const bindingData = this.get( binding ); - const index = bindingData.index; + this.set( pipeline, { + programGPU + } ); - if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + } - const location = gl.getUniformBlockIndex( programGPU, binding.name ); - gl.uniformBlockBinding( programGPU, location, index ); + createComputePipeline( computePipeline, bindings ) { - } else if ( binding.isSampledTexture ) { + const gl = this.gl; - const location = gl.getUniformLocation( programGPU, binding.name ); - gl.uniform1i( location, index ); + // Program - } + const fragmentProgram = { + stage: 'fragment', + code: '#version 300 es\nprecision highp float;\nvoid main() {}' + }; - } + this.createProgram( fragmentProgram ); - // VAO + const { computeProgram } = computePipeline; - const vaoGPU = gl.createVertexArray(); + const programGPU = gl.createProgram(); - const index = renderObject.getIndex(); - const attributes = renderObject.getAttributes(); + const fragmentShader = this.get( fragmentProgram ).shaderGPU; + const vertexShader = this.get( computeProgram ).shaderGPU; - gl.bindVertexArray( vaoGPU ); + const transforms = computeProgram.transforms; - if ( index !== null ) { + const transformVaryingNames = []; + const transformAttributeNodes = []; - const indexData = this.get( index ); + for ( let i = 0; i < transforms.length; i ++ ) { - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU ); + const transform = transforms[ i ]; + + transformVaryingNames.push( transform.varyingName ); + transformAttributeNodes.push( transform.attributeNode ); } - for ( let i = 0; i < attributes.length; i ++ ) { + gl.attachShader( programGPU, fragmentShader ); + gl.attachShader( programGPU, vertexShader ); - const attribute = attributes[ i ]; - const attributeData = this.get( attribute ); + gl.transformFeedbackVaryings( + programGPU, + transformVaryingNames, + gl.SEPARATE_ATTRIBS, + ); - gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU ); - gl.enableVertexAttribArray( i ); + gl.linkProgram( programGPU ); - let stride, offset; + if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) ; - if ( attribute.isInterleavedBufferAttribute === true ) { + gl.useProgram( programGPU ); - stride = attribute.data.stride * attributeData.bytesPerElement; - offset = attribute.offset * attributeData.bytesPerElement; + // Bindings - } else { + this.createBindings( bindings ); - stride = 0; - offset = 0; + this._setupBindings( bindings, programGPU ); - } + const attributeNodes = computeProgram.attributes; + const attributes = []; + const transformBuffers = []; - if ( attributeData.isInteger ) { + for ( let i = 0; i < attributeNodes.length; i ++ ) { - gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset ); + const attribute = attributeNodes[ i ].node.attribute; - } else { + attributes.push( attribute ); - gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset ); + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); - } + } - if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) { + for ( let i = 0; i < transformAttributeNodes.length; i ++ ) { - gl.vertexAttribDivisor( i, attribute.meshPerAttribute ); + const attribute = transformAttributeNodes[ i ].attribute; - } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) { + if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); - gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute ); + const attributeData = this.get( attribute ); - } + transformBuffers.push( attributeData ); } - gl.bindVertexArray( null ); - // - this.set( pipeline, { + this.set( computePipeline, { programGPU, - vaoGPU + transformBuffers, + attributes } ); } - createComputePipeline( /*computePipeline, bindings*/ ) { - - } - createBindings( bindings ) { this.updateBindings( bindings ); @@ -24466,13 +26695,17 @@ class WebGLBackend extends Backend { createAttribute( attribute ) { + if ( this.has( attribute ) ) return; + const gl = this.gl; this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER ); } - createStorageAttribute( /*attribute*/ ) { + createStorageAttribute( attribute ) { + + //console.warn( 'Abstract class.' ); } @@ -24494,6 +26727,12 @@ class WebGLBackend extends Backend { } + async hasFeatureAsync( name ) { + + return this.hasFeature( name ); + + } + hasFeature( name ) { const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name ); @@ -24677,6 +26916,197 @@ class WebGLBackend extends Backend { } + + _getVaoKey( index, attributes ) { + + let key = []; + + if ( index !== null ) { + + const indexData = this.get( index ); + + key += ':' + indexData.id; + + } + + for ( let i = 0; i < attributes.length; i ++ ) { + + const attributeData = this.get( attributes[ i ] ); + + key += ':' + attributeData.id; + + } + + return key; + + } + + _createVao( index, attributes ) { + + const { gl } = this; + + const vaoGPU = gl.createVertexArray(); + let key = ''; + + let staticVao = true; + + gl.bindVertexArray( vaoGPU ); + + if ( index !== null ) { + + const indexData = this.get( index ); + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU ); + + key += ':' + indexData.id; + + } + + for ( let i = 0; i < attributes.length; i ++ ) { + + const attribute = attributes[ i ]; + const attributeData = this.get( attribute ); + + key += ':' + attributeData.id; + + gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU ); + gl.enableVertexAttribArray( i ); + + if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false; + + let stride, offset; + + if ( attribute.isInterleavedBufferAttribute === true ) { + + stride = attribute.data.stride * attributeData.bytesPerElement; + offset = attribute.offset * attributeData.bytesPerElement; + + } else { + + stride = 0; + offset = 0; + + } + + if ( attributeData.isInteger ) { + + gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset ); + + } else { + + gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset ); + + } + + if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) { + + gl.vertexAttribDivisor( i, attribute.meshPerAttribute ); + + } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) { + + gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, null ); + + this.vaoCache[ key ] = vaoGPU; + + return { vaoGPU, staticVao }; + + } + + _getTransformFeedback( transformBuffers ) { + + let key = ''; + + for ( let i = 0; i < transformBuffers.length; i ++ ) { + + key += ':' + transformBuffers[ i ].id; + + } + + let transformFeedbackGPU = this.transformFeedbackCache[ key ]; + + if ( transformFeedbackGPU !== undefined ) { + + return transformFeedbackGPU; + + } + + const gl = this.gl; + + transformFeedbackGPU = gl.createTransformFeedback(); + + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU ); + + for ( let i = 0; i < transformBuffers.length; i ++ ) { + + const attributeData = transformBuffers[ i ]; + + gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer ); + + } + + gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null ); + + this.transformFeedbackCache[ key ] = transformFeedbackGPU; + + return transformFeedbackGPU; + + } + + + _setupBindings( bindings, programGPU ) { + + const gl = this.gl; + + for ( const binding of bindings ) { + + const bindingData = this.get( binding ); + const index = bindingData.index; + + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + + const location = gl.getUniformBlockIndex( programGPU, binding.name ); + gl.uniformBlockBinding( programGPU, location, index ); + + } else if ( binding.isSampledTexture ) { + + const location = gl.getUniformLocation( programGPU, binding.name ); + gl.uniform1i( location, index ); + + } + + } + + } + + _bindUniforms( bindings ) { + + const { gl, state } = this; + + for ( const binding of bindings ) { + + const bindingData = this.get( binding ); + const index = bindingData.index; + + if ( binding.isUniformsGroup || binding.isUniformBuffer ) { + + gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU ); + + } else if ( binding.isSampledTexture ) { + + state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index ); + + } + + } + + } + } const GPUPrimitiveTopology = { @@ -25006,6 +27436,26 @@ class StorageBuffer extends Buffer { } +let _id = 0; + +class NodeStorageBuffer extends StorageBuffer { + + constructor( nodeUniform ) { + + super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null ); + + this.nodeUniform = nodeUniform; + + } + + get buffer() { + + return this.nodeUniform.value; + + } + +} + class WebGPUTexturePassUtils { constructor( device ) { @@ -25596,13 +28046,13 @@ class WebGPUTextureUtils { if ( texture.isDataTexture || texture.isData3DTexture ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, false ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY ); } else if ( texture.isDataArrayTexture ) { for ( let i = 0; i < options.image.depth; i ++ ) { - this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, false, i ); + this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i ); } @@ -25643,6 +28093,9 @@ class WebGPUTextureUtils { const format = textureData.textureDescriptorGPU.format; const bytesPerTexel = this._getBytesPerTexel( format ); + let bytesPerRow = width * bytesPerTexel; + bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes + const readBuffer = device.createBuffer( { size: width * height * bytesPerTexel, @@ -25659,7 +28112,7 @@ class WebGPUTextureUtils { }, { buffer: readBuffer, - bytesPerRow: width * bytesPerTexel + bytesPerRow: bytesPerRow }, { width: width, @@ -25948,15 +28401,57 @@ class WebGPUTextureUtils { _getBytesPerTexel( format ) { - if ( format === GPUTextureFormat.R8Unorm ) return 1; - if ( format === GPUTextureFormat.R16Float ) return 2; - if ( format === GPUTextureFormat.RG8Unorm ) return 2; - if ( format === GPUTextureFormat.RG16Float ) return 4; - if ( format === GPUTextureFormat.R32Float ) return 4; - if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4; - if ( format === GPUTextureFormat.RG32Float ) return 8; - if ( format === GPUTextureFormat.RGBA16Float ) return 8; - if ( format === GPUTextureFormat.RGBA32Float ) return 16; + // 8-bit formats + if ( format === GPUTextureFormat.R8Unorm || + format === GPUTextureFormat.R8Snorm || + format === GPUTextureFormat.R8Uint || + format === GPUTextureFormat.R8Sint ) return 1; + + // 16-bit formats + if ( format === GPUTextureFormat.R16Uint || + format === GPUTextureFormat.R16Sint || + format === GPUTextureFormat.R16Float || + format === GPUTextureFormat.RG8Unorm || + format === GPUTextureFormat.RG8Snorm || + format === GPUTextureFormat.RG8Uint || + format === GPUTextureFormat.RG8Sint ) return 2; + + // 32-bit formats + if ( format === GPUTextureFormat.R32Uint || + format === GPUTextureFormat.R32Sint || + format === GPUTextureFormat.R32Float || + format === GPUTextureFormat.RG16Uint || + format === GPUTextureFormat.RG16Sint || + format === GPUTextureFormat.RG16Float || + format === GPUTextureFormat.RGBA8Unorm || + format === GPUTextureFormat.RGBA8UnormSRGB || + format === GPUTextureFormat.RGBA8Snorm || + format === GPUTextureFormat.RGBA8Uint || + format === GPUTextureFormat.RGBA8Sint || + format === GPUTextureFormat.BGRA8Unorm || + format === GPUTextureFormat.BGRA8UnormSRGB || + // Packed 32-bit formats + format === GPUTextureFormat.RGB9E5UFloat || + format === GPUTextureFormat.RGB10A2Unorm || + format === GPUTextureFormat.RG11B10UFloat || + format === GPUTextureFormat.Depth32Float || + format === GPUTextureFormat.Depth24Plus || + format === GPUTextureFormat.Depth24PlusStencil8 || + format === GPUTextureFormat.Depth32FloatStencil8 ) return 4; + + // 64-bit formats + if ( format === GPUTextureFormat.RG32Uint || + format === GPUTextureFormat.RG32Sint || + format === GPUTextureFormat.RG32Float || + format === GPUTextureFormat.RGBA16Uint || + format === GPUTextureFormat.RGBA16Sint || + format === GPUTextureFormat.RGBA16Float ) return 8; + + // 128-bit formats + if ( format === GPUTextureFormat.RGBA32Uint || + format === GPUTextureFormat.RGBA32Sint || + format === GPUTextureFormat.RGBA32Float ) return 16; + } @@ -25982,6 +28477,9 @@ class WebGPUTextureUtils { if ( format === GPUTextureFormat.RG16Sint ) return Int16Array; if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array; if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array; + if ( format === GPUTextureFormat.R16Float ) return Float32Array; + if ( format === GPUTextureFormat.RG16Float ) return Float32Array; + if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array; if ( format === GPUTextureFormat.R32Uint ) return Uint32Array; @@ -25994,6 +28492,17 @@ class WebGPUTextureUtils { if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array; if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array; + if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array; + if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array; + if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array; + if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array; + if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array; + + if ( format === GPUTextureFormat.Depth32Float ) return Float32Array; + if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array; + if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array; + if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array; + } _getDimension( texture ) { @@ -26024,7 +28533,7 @@ function getFormat( texture, device = null ) { let formatGPU; - if ( /*texture.isRenderTargetTexture === true ||*/ texture.isFramebufferTexture === true ) { + if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) { formatGPU = GPUTextureFormat.BGRA8Unorm; @@ -26333,7 +28842,7 @@ class WGSLNodeParser extends NodeParser { } // GPUShaderStage is not defined in browsers not supporting WebGPU -const GPUShaderStage = window.GPUShaderStage; +const GPUShaderStage = self.GPUShaderStage; const gpuShaderStageLib = { 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1, @@ -26342,7 +28851,8 @@ const gpuShaderStageLib = { }; const supports = { - instance: true + instance: true, + storageBuffer: true }; const wgslFnOpLib = { @@ -26371,6 +28881,11 @@ const wgslTypeLib = { uvec4: 'vec4', bvec4: 'vec4', + mat2: 'mat2x2', + imat2: 'mat2x2', + umat2: 'mat2x2', + bmat2: 'mat2x2', + mat3: 'mat3x3', imat3: 'mat3x3', umat3: 'mat3x3', @@ -26389,6 +28904,10 @@ const wgslMethods = { mod_vec2: 'threejs_mod_vec2', mod_vec3: 'threejs_mod_vec3', mod_vec4: 'threejs_mod_vec4', + equals_bool: 'threejs_equals_bool', + equals_bvec2: 'threejs_equals_bvec2', + equals_bvec3: 'threejs_equals_bvec3', + equals_bvec4: 'threejs_equals_bvec4', lessThanEqual: 'threejs_lessThanEqual', greaterThan: 'threejs_greaterThan', inversesqrt: 'inverseSqrt', @@ -26421,6 +28940,10 @@ fn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 { mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ), mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ), mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ), + equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ), + equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }' ), + equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }' ), + equals_bvec4: new CodeNode( 'fn threejs_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: new CodeNode( ` fn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 { @@ -26520,6 +29043,12 @@ class WGSLNodeBuilder extends NodeBuilder { } + generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) { + + return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`; + + } + isUnfilterable( texture ) { return texture.isDataTexture === true && texture.type === FloatType; @@ -26591,7 +29120,7 @@ class WGSLNodeBuilder extends NodeBuilder { const name = node.name; const type = node.type; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { return name; @@ -26644,11 +29173,11 @@ class WGSLNodeBuilder extends NodeBuilder { const bindings = this.bindings[ shaderStage ]; - if ( type === 'texture' || type === 'cubeTexture' ) { + if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) { let texture = null; - if ( type === 'texture' ) { + if ( type === 'texture' || type === 'storageTexture' ) { texture = new NodeSampledTexture( uniformNode.name, uniformNode.node ); @@ -26680,8 +29209,8 @@ class WGSLNodeBuilder extends NodeBuilder { } else if ( type === 'buffer' || type === 'storageBuffer' ) { - const bufferClass = type === 'storageBuffer' ? StorageBuffer : UniformBuffer; - const buffer = new bufferClass( 'NodeBuffer_' + node.id, node.value ); + const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer; + const buffer = new bufferClass( node ); buffer.setVisibility( gpuShaderStageLib[ shaderStage ] ); bindings.push( buffer ); @@ -26708,31 +29237,9 @@ class WGSLNodeBuilder extends NodeBuilder { } - if ( node.isArrayUniformNode === true ) { - - uniformGPU = []; - - for ( const uniformNode of node.nodes ) { - - const uniformNodeGPU = this.getNodeUniform( uniformNode, type ); - - // fit bounds to buffer - uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize ); - uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize ); - - uniformsGroup.addUniform( uniformNodeGPU ); - - uniformGPU.push( uniformNodeGPU ); - - } - - } else { - - uniformGPU = this.getNodeUniform( uniformNode, type ); - - uniformsGroup.addUniform( uniformGPU ); + uniformGPU = this.getNodeUniform( uniformNode, type ); - } + uniformsGroup.addUniform( uniformGPU ); } @@ -27031,7 +29538,7 @@ ${ flowData.code } for ( const uniform of uniforms ) { - if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' ) { + if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) { const texture = uniform.node.value; @@ -27099,21 +29606,11 @@ ${ flowData.code } const groupName = uniform.groupNode.name; const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = { - index: index ++, - snippets: [] - } ); - - if ( Array.isArray( uniform.value ) === true ) { - - const length = uniform.value.length; - - group.snippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` ); - - } else { - - group.snippets.push( `\t${uniform.name} : ${ vectorType}` ); + index: index ++, + snippets: [] + } ); - } + group.snippets.push( `\t${ uniform.name } : ${ vectorType }` ); } @@ -27528,7 +30025,21 @@ class WebGPUAttributeUtils { const device = backend.device; - const array = bufferAttribute.array; + let array = bufferAttribute.array; + + if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) { + + bufferAttribute.itemSize = 4; + array = new array.constructor( bufferAttribute.count * 4 ); + + for ( let i = 0; i < bufferAttribute.count; i ++ ) { + + array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 ); + + } + + } + const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441 buffer = device.createBuffer( { @@ -27998,7 +30509,7 @@ class WebGPUPipelineUtils { } - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { const { object, material, geometry, pipeline } = renderObject; const { vertexProgram, fragmentProgram } = pipeline; @@ -28092,7 +30603,7 @@ class WebGPUPipelineUtils { } - pipelineData.pipeline = device.createRenderPipeline( { + const pipelineDescriptor = { vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ), fragment: Object.assign( {}, fragmentModule, { targets } ), primitive: primitiveState, @@ -28112,7 +30623,28 @@ class WebGPUPipelineUtils { layout: device.createPipelineLayout( { bindGroupLayouts: [ bindingsData.layout ] } ) - } ); + }; + + if ( promises === null ) { + + pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor ); + + } else { + + const p = new Promise( ( resolve /*, reject*/ ) => { + + device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => { + + pipelineData.pipeline = pipeline; + resolve(); + + } ); + + } ); + + promises.push( p ); + + } } @@ -28523,16 +31055,6 @@ class WebGPUPipelineUtils { import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js'; //*/ -// statics - -let _staticAdapter = null; - -if ( navigator.gpu !== undefined ) { - - _staticAdapter = await navigator.gpu.requestAdapter(); - -} - // class WebGPUBackend extends Backend { @@ -28560,10 +31082,13 @@ class WebGPUBackend extends Backend { this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits; + this.trackTimestamp = ( parameters.trackTimestamp === true ); + this.adapter = null; this.device = null; this.context = null; this.colorBuffer = null; + this.defaultRenderPassdescriptor = null; this.utils = new WebGPUUtils( this ); this.attributeUtils = new WebGPUAttributeUtils( this ); @@ -28654,60 +31179,88 @@ class WebGPUBackend extends Backend { } - beginRender( renderContext ) { + _getDefaultRenderPassDescriptor() { - const renderContextData = this.get( renderContext ); + let descriptor = this.defaultRenderPassdescriptor; - const device = this.device; - const occlusionQueryCount = renderContext.occlusionQueryCount; + const antialias = this.parameters.antialias; - let occlusionQuerySet; + if ( descriptor === null ) { - if ( occlusionQueryCount > 0 ) { + const renderer = this.renderer; - if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); - if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + descriptor = { + colorAttachments: [ { + view: null + } ], + depthStencilAttachment: { + view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() + } + }; - // Get a reference to the array of objects with queries. The renderContextData property - // can be changed by another render pass before the buffer.mapAsyc() completes. - renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; - renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; - renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + const colorAttachment = descriptor.colorAttachments[ 0 ]; - // + if ( antialias === true ) { - occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + colorAttachment.view = this.colorBuffer.createView(); - renderContextData.occlusionQuerySet = occlusionQuerySet; - renderContextData.occlusionQueryIndex = 0; - renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + } else { - renderContextData.lastOcclusionObject = null; + colorAttachment.resolveTarget = undefined; - } + } - const descriptor = { - colorAttachments: [ { - view: null - } ], - depthStencilAttachment: { - view: null - }, - occlusionQuerySet - }; + this.defaultRenderPassdescriptor = descriptor; + + } const colorAttachment = descriptor.colorAttachments[ 0 ]; - const depthStencilAttachment = descriptor.depthStencilAttachment; - const antialias = this.parameters.antialias; + if ( antialias === true ) { - if ( renderContext.textures !== null ) { + colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - const textures = renderContext.textures; + } else { - descriptor.colorAttachments = []; + colorAttachment.view = this.context.getCurrentTexture().createView(); - const colorAttachments = descriptor.colorAttachments; + } + + return descriptor; + + } + + _getRenderPassDescriptor( renderContext ) { + + const renderTarget = renderContext.renderTarget; + const renderTargetData = this.get( renderTarget ); + + let descriptors = renderTargetData.descriptors; + + if ( descriptors === undefined ) { + + descriptors = []; + + renderTargetData.descriptors = descriptors; + + } + + if ( renderTargetData.width !== renderTarget.width || + renderTargetData.height !== renderTarget.height || + renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel || + renderTargetData.samples !== renderTarget.samples + ) { + + descriptors.length = 0; + + } + + let descriptor = descriptors[ renderContext.activeCubeFace ]; + + if ( descriptor === undefined ) { + + const textures = renderContext.textures; + const colorAttachments = []; for ( let i = 0; i < textures.length; i ++ ) { @@ -28745,32 +31298,78 @@ class WebGPUBackend extends Backend { const depthTextureData = this.get( renderContext.depthTexture ); - depthStencilAttachment.view = depthTextureData.texture.createView(); + const depthStencilAttachment = { + view: depthTextureData.texture.createView(), + }; - if ( renderContext.stencil && renderContext.depthTexture.format === DepthFormat ) { + descriptor = { + colorAttachments, + depthStencilAttachment + }; - renderContext.stencil = false; + descriptors[ renderContext.activeCubeFace ] = descriptor; - } + renderTargetData.width = renderTarget.width; + renderTargetData.height = renderTarget.height; + renderTargetData.samples = renderTarget.samples; + renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel; - } else { + } - if ( antialias === true ) { + return descriptor; - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); + } - } else { + beginRender( renderContext ) { - colorAttachment.view = this.context.getCurrentTexture().createView(); - colorAttachment.resolveTarget = undefined; + const renderContextData = this.get( renderContext ); - } + const device = this.device; + const occlusionQueryCount = renderContext.occlusionQueryCount; + + let occlusionQuerySet; + + if ( occlusionQueryCount > 0 ) { + + if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy(); + if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy(); + + // Get a reference to the array of objects with queries. The renderContextData property + // can be changed by another render pass before the buffer.mapAsyc() completes. + renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet; + renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer; + renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects; + + // + + occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } ); + + renderContextData.occlusionQuerySet = occlusionQuerySet; + renderContextData.occlusionQueryIndex = 0; + renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount ); + + renderContextData.lastOcclusionObject = null; + + } + + let descriptor; + + if ( renderContext.textures === null ) { + + descriptor = this._getDefaultRenderPassDescriptor(); - depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ).createView(); + } else { + + descriptor = this._getRenderPassDescriptor( renderContext ); } + this.initTimestampQuery( renderContext, descriptor ); + + descriptor.occlusionQuerySet = occlusionQuerySet; + + const depthStencilAttachment = descriptor.depthStencilAttachment; + if ( renderContext.textures !== null ) { const colorAttachments = descriptor.colorAttachments; @@ -28794,9 +31393,10 @@ class WebGPUBackend extends Backend { } - } else { + const colorAttachment = descriptor.colorAttachments[ 0 ]; + if ( renderContext.clearColor ) { colorAttachment.clearValue = renderContext.clearColorValue; @@ -28933,8 +31533,11 @@ class WebGPUBackend extends Backend { } + this.prepareTimestampBuffer( renderContext, renderContextData.encoder ); + this.device.queue.submit( [ renderContextData.encoder.finish() ] ); + // if ( renderContext.textures !== null ) { @@ -28985,7 +31588,7 @@ class WebGPUBackend extends Backend { const buffer = currentOcclusionQueryBuffer.getMappedRange(); const results = new BigUint64Array( buffer ); - for ( let i = 0; i < currentOcclusionQueryObjects.length; i++ ) { + for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) { if ( results[ i ] !== 0n ) { @@ -29006,7 +31609,7 @@ class WebGPUBackend extends Backend { updateViewport( renderContext ) { const { currentPass } = this.get( renderContext ); - let { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; + const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue; currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth ); @@ -29017,7 +31620,7 @@ class WebGPUBackend extends Backend { const device = this.device; const renderer = this.renderer; - const colorAttachments = []; + let colorAttachments = []; let depthStencilAttachment; let clearValue; @@ -29038,39 +31641,23 @@ class WebGPUBackend extends Backend { supportsDepth = renderer.depth; supportsStencil = renderer.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; + const descriptor = this._getDefaultRenderPassDescriptor(); if ( color ) { - const antialias = this.parameters.antialias; - - const colorAttachment = {}; - - if ( antialias === true ) { + colorAttachments = descriptor.colorAttachments; - colorAttachment.view = this.colorBuffer.createView(); - colorAttachment.resolveTarget = this.context.getCurrentTexture().createView(); - - } else { - - colorAttachment.view = this.context.getCurrentTexture().createView(); - - } + const colorAttachment = colorAttachments[ 0 ]; colorAttachment.clearValue = clearValue; colorAttachment.loadOp = GPULoadOp.Clear; colorAttachment.storeOp = GPUStoreOp.Store; - colorAttachments.push( colorAttachment ); - } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { - depthStencilAttachment = { - view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView() - }; + depthStencilAttachment = descriptor.depthStencilAttachment; } @@ -29079,9 +31666,6 @@ class WebGPUBackend extends Backend { supportsDepth = renderTargetData.depth; supportsStencil = renderTargetData.stencil; - depth = depth && supportsDepth; - stencil = stencil && supportsStencil; - if ( color ) { for ( const texture of renderTargetData.textures ) { @@ -29115,7 +31699,7 @@ class WebGPUBackend extends Backend { } - if ( depth || stencil ) { + if ( supportsDepth || supportsStencil ) { const depthTextureData = this.get( renderTargetData.depthTexture ); @@ -29129,7 +31713,7 @@ class WebGPUBackend extends Backend { // - if ( depthStencilAttachment !== undefined ) { + if ( supportsDepth ) { if ( depth ) { @@ -29144,7 +31728,11 @@ class WebGPUBackend extends Backend { } - // + } + + // + + if ( supportsStencil ) { if ( stencil ) { @@ -29181,8 +31769,14 @@ class WebGPUBackend extends Backend { const groupGPU = this.get( computeGroup ); - groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( {} ); - groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass(); + + const descriptor = {}; + + this.initTimestampQuery( computeGroup, descriptor ); + + groupGPU.cmdEncoderGPU = this.device.createCommandEncoder(); + + groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor ); } @@ -29209,6 +31803,9 @@ class WebGPUBackend extends Backend { const groupData = this.get( computeGroup ); groupData.passEncoderGPU.end(); + + this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU ); + this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] ); } @@ -29285,7 +31882,7 @@ class WebGPUBackend extends Backend { // occlusion queries - handle multiple consecutive draw calls for an object - if ( contextData.occlusionQuerySet !== undefined ) { + if ( contextData.occlusionQuerySet !== undefined ) { const lastObject = contextData.lastOcclusionObject; @@ -29369,7 +31966,8 @@ class WebGPUBackend extends Backend { data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage || data.sampleCount !== sampleCount || data.colorSpace !== colorSpace || data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat || - data.primitiveTopology !== primitiveTopology + data.primitiveTopology !== primitiveTopology || + data.clippingContextVersion !== renderObject.clippingContextVersion ) { data.material = material; data.materialVersion = material.version; @@ -29387,6 +31985,7 @@ class WebGPUBackend extends Backend { data.colorFormat = colorFormat; data.depthStencilFormat = depthStencilFormat; data.primitiveTopology = primitiveTopology; + data.clippingContextVersion = renderObject.clippingContextVersion; needsUpdate = true; @@ -29415,7 +32014,8 @@ class WebGPUBackend extends Backend { material.side, utils.getSampleCount( renderContext ), utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ), - utils.getPrimitiveTopology( object, material ) + utils.getPrimitiveTopology( object, material ), + renderObject.clippingContextVersion ].join(); } @@ -29470,6 +32070,87 @@ class WebGPUBackend extends Backend { } + + initTimestampQuery( renderContext, descriptor ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + if ( ! renderContextData.timeStampQuerySet ) { + + // Create a GPUQuerySet which holds 2 timestamp query results: one for the + // beginning and one for the end of compute pass execution. + const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } ); + + const timestampWrites = { + querySet: timeStampQuerySet, + beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins. + endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends. + }; + Object.assign( descriptor, { + timestampWrites, + } ); + renderContextData.timeStampQuerySet = timeStampQuerySet; + + } + + } + + // timestamp utils + + prepareTimestampBuffer( renderContext, encoder ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + const size = 2 * BigInt64Array.BYTES_PER_ELEMENT; + const resolveBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC, + } ); + + const resultBuffer = this.device.createBuffer( { + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + } ); + + encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 ); + encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size ); + + renderContextData.currentTimestampQueryBuffer = resultBuffer; + + } + + async resolveTimestampAsync( renderContext, type = 'render' ) { + + if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return; + + const renderContextData = this.get( renderContext ); + + // handle timestamp query results + + const { currentTimestampQueryBuffer } = renderContextData; + + if ( currentTimestampQueryBuffer ) { + + renderContextData.currentTimestampQueryBuffer = null; + + await currentTimestampQueryBuffer.mapAsync( GPUMapMode.READ ); + + const times = new BigUint64Array( currentTimestampQueryBuffer.getMappedRange() ); + + const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000; + // console.log( `Compute ${type} duration: ${Number( times[ 1 ] - times[ 0 ] ) / 1000000}ms` ); + this.renderer.info.updateTimestamp( type, duration ); + + currentTimestampQueryBuffer.unmap(); + + } + + } + // node builder createNodeBuilder( object, renderer, scene = null ) { @@ -29499,9 +32180,9 @@ class WebGPUBackend extends Backend { // pipelines - createRenderPipeline( renderObject ) { + createRenderPipeline( renderObject, promises ) { - this.pipelineUtils.createRenderPipeline( renderObject ); + this.pipelineUtils.createRenderPipeline( renderObject, promises ); } @@ -29568,7 +32249,8 @@ class WebGPUBackend extends Backend { updateSize() { this.colorBuffer = this.textureUtils.getColorBuffer(); - + this.defaultRenderPassdescriptor = null; + } // utils public @@ -29579,9 +32261,9 @@ class WebGPUBackend extends Backend { } - hasFeature( name ) { + async hasFeatureAsync( name ) { - const adapter = this.adapter || _staticAdapter; + const adapter = this.adapter || await WebGPU.getStaticAdapter(); // @@ -29589,6 +32271,18 @@ class WebGPUBackend extends Backend { } + hasFeature( name ) { + + if ( ! this.adapter ) { + + return false; + + } + + return this.adapter.features.has( name ); + + } + copyFramebufferToTexture( texture, renderContext ) { const renderContextData = this.get( renderContext ); @@ -29597,18 +32291,40 @@ class WebGPUBackend extends Backend { let sourceGPU = null; - if ( texture.isFramebufferTexture ) { + if ( renderContext.renderTarget ) { + + if ( texture.isDepthTexture ) { + + sourceGPU = this.get( renderContext.depthTexture ).texture; + + } else { + + sourceGPU = this.get( renderContext.textures[ 0 ] ).texture; - sourceGPU = this.context.getCurrentTexture(); + } + + } else { + + if ( texture.isDepthTexture ) { - } else if ( texture.isDepthTexture ) { + sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); - sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ); + } else { + + sourceGPU = this.context.getCurrentTexture(); + + } } const destinationGPU = this.get( texture ).texture; + if ( sourceGPU.format !== destinationGPU.format ) { + + return; + + } + renderContextData.currentPass.end(); encoder.copyTextureToTexture( @@ -29658,7 +32374,11 @@ class WebGPURenderer extends Renderer { let BackendClass; - if ( WebGPU.isAvailable() ) { + if ( parameters.forceWebGL ) { + + BackendClass = WebGLBackend; + + } else if ( WebGPU.isAvailable() ) { BackendClass = WebGPUBackend; @@ -29857,4 +32577,4 @@ class WebGPUVideoAnimation { } } -export { AONode, AfterImageNode, AmbientLightNode, AnalyticLightNode, ArrayElementNode, ArrayUniformNode, AssignNode, AttributeNode, BRDF_GGX, BRDF_Lambert, BitangentNode, BlendModeNode, BufferAttributeNode, BufferNode, BumpMapNode, BypassNode, CacheNode, CameraNode, CheckerNode, CodeNode, ColorAdjustmentNode, ColorSpaceNode, ComputeNode, CondNode, ConstNode, ContextNode, ConvertNode, CubeTextureNode, DFGApprox, D_GGX, DirectionalLightNode, DiscardNode, EPSILON, EnvironmentNode, EquirectUVNode, ExpressionNode, F_Schlick, FogExp2Node, FogNode, FogRangeNode, FrontFacingNode, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GaussianBlurNode, HashNode, HemisphereLightNode, IESSpotLightNode, INFINITY, If, IndexNode, InstanceNode, InstancedPointsNodeMaterial, JoinNode, LightNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicNodeMaterial, LineDashedNodeMaterial, LoopNode, MatcapUVNode, MaterialNode, MaterialReferenceNode, MathNode, MaxMipLevelNode, MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshNormalNodeMaterial, MeshPhongNodeMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardNodeMaterial, ModelNode, ModelViewProjectionNode, MorphNode, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalMapNode, NormalNode, Object3DNode, OperatorNode, OscNode, OutputStructNode, PackingNode, ParameterNode, PassNode, PhongLightingModel, PhysicalLightingModel, PointLightNode, PointUVNode, PointsNodeMaterial, PositionNode, PosterizeNode, PropertyNode, RangeNode, ReferenceNode, ReflectVectorNode, RemapNode, RotateUVNode, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderNode, SkinningNode, SpecularMIPLevelNode, SplitNode, SpotLightNode, SpriteNodeMaterial, SpriteSheetUVNode, StackNode, StorageBufferNode, TBNViewMatrix, TangentNode, TempNode, TextureBicubicNode, TextureNode, TextureStoreNode, TimerNode, ToneMappingNode, TriplanarTexturesNode, UVNode, UniformGroupNode, UniformNode, UserDataNode, V_GGX_SmithCorrelated, VarNode, VaryingNode, VertexColorNode, VideoAnimation, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, WebGPU, WebGPUGLRenderer, WebGPURenderer, WebGPUVideoAnimation, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, and, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, bitAnd, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, degrees, densityFog, depth, depthPass, depthPixel, depthTexture, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dot, dynamicBufferAttribute, element, equal, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lessThan, lessThanEqual, lightNodes, lightTargetDirection, lightingContext, lights, linearToColorSpace, linearTosRGB, log, log2, loop, lumaCoeffs, luminance, mat3, mat4, matcapUV, materialAlphaTest, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecularColor, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, morph, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parameter, pass, perspectiveDepthToViewZ, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, range, rangeFog, reciprocal, reference, referenceIndex, reflect, reflectVector, refract, remainder, remap, remapClamp, renderGroup, rotateUV, roughness, round, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shader, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, skinning, smoothstep, specularColor, specularMIPLevel, split, spritesheetUV, sqrt, stack, step, storage, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, textureBicubic, textureLoad, textureStore, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat3, umat4, uniform, uniformGroup, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor }; +export { AONode, AfterImageNode, AmbientLightNode, AnalyticLightNode, AnamorphicNode, ArrayElementNode, AssignNode, AttributeNode, BRDF_GGX, BRDF_Lambert, BitangentNode, BlendModeNode, Break, BufferAttributeNode, BufferNode, BumpMapNode, BypassNode, CacheNode, CameraNode, CheckerNode, CodeNode, ColorAdjustmentNode, ColorSpaceNode, ComputeNode, CondNode, ConstNode, ContextNode, Continue, ConvertNode, CubeTextureNode, DFGApprox, D_GGX, DirectionalLightNode, DiscardNode, EPSILON, EnvironmentNode, EquirectUVNode, ExpressionNode, F_Schlick, FogExp2Node, FogNode, FogRangeNode, FrontFacingNode, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GaussianBlurNode, HashNode, HemisphereLightNode, IESSpotLightNode, INFINITY, If, IndexNode, InstanceNode, InstancedPointsNodeMaterial, JoinNode, LightNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicNodeMaterial, LineDashedNodeMaterial, LoopNode, MatcapUVNode, MaterialNode, MaterialReferenceNode, MathNode, MaxMipLevelNode, MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshNormalNodeMaterial, MeshPhongNodeMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardNodeMaterial, ModelNode, ModelViewProjectionNode, MorphNode, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalMapNode, NormalNode, Object3DNode, OperatorNode, OscNode, OutputStructNode, PI, PI2, PackingNode, ParameterNode, PassNode, PhongLightingModel, PhysicalLightingModel, PointLightNode, PointUVNode, PointsNodeMaterial, PositionNode, PosterizeNode, PropertyNode, RangeNode, ReferenceNode, ReflectVectorNode, ReflectorNode, RemapNode, RotateNode, RotateUVNode, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderNode, SkinningNode, SpecularMIPLevelNode, SplitNode, SpotLightNode, SpriteNodeMaterial, SpriteSheetUVNode, StackNode, StorageArrayElementNode, StorageBufferNode, TBNViewMatrix, TangentNode, TempNode, TextureBicubicNode, TextureNode, TextureStoreNode, TimerNode, ToneMappingNode, TriplanarTexturesNode, UVNode, UniformGroupNode, UniformNode, UniformsNode, UserDataNode, V_GGX_SmithCorrelated, VarNode, VaryingNode, VertexColorNode, VideoAnimation, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, WebGPU, WebGPUGLRenderer, WebGPURenderer, WebGPUVideoAnimation, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, all, anamorphic, and, any, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bmat2, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, degrees, densityFog, depth, depthPass, depthPixel, depthTexture, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dot, dynamicBufferAttribute, element, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat2, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, lightsNode, linearToColorSpace, linearTosRGB, log, log2, loop, lumaCoeffs, luminance, mat2, mat3, mat4, matcapUV, materialAlphaTest, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecularColor, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, morphReference, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, pcurve, perspectiveDepthToViewZ, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflector, refract, remainder, remap, remapClamp, renderGroup, rotate, rotateUV, roughness, round, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shader, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, smoothstep, specularColor, specularMIPLevel, split, spritesheetUV, sqrt, stack, step, storage, storageObject, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, textureBicubic, textureLoad, textureStore, threshold, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat2, umat3, umat4, uniform, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor }; diff --git a/build/webgpu-renderer.module.min.js b/build/webgpu-renderer.module.min.js index 12c9a48..8e8bf34 100644 --- a/build/webgpu-renderer.module.min.js +++ b/build/webgpu-renderer.module.min.js @@ -3,4 +3,4 @@ * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ -import{DynamicDrawUsage as e,Uint32BufferAttribute as t,Uint16BufferAttribute as s,Color as r,Vector2 as i,Vector3 as n,Vector4 as o,Matrix3 as a,Matrix4 as u,EventDispatcher as l,MathUtils as d,LinearSRGBColorSpace as c,SRGBColorSpace as h,StaticDrawUsage as p,InterleavedBuffer as g,InterleavedBufferAttribute as m,InstancedInterleavedBuffer as f,DataArrayTexture as T,FloatType as x,WebGPUCoordinateSystem as y,DepthTexture as b,NearestFilter as N,LessCompare as _,FramebufferTexture as v,LinearMipmapLinearFilter as S,NearestMipmapNearestFilter as A,UnsignedIntType as R,DepthFormat as E,ShaderMaterial as C,NoColorSpace as w,Material as M,WebGLCubeRenderTarget as F,BoxGeometry as B,BackSide as O,NoBlending as L,Mesh as U,Scene as I,LinearFilter as D,CubeCamera as P,RenderTarget as V,sRGBEncoding as G,LinearEncoding as k,Float16BufferAttribute as z,REVISION as $,TangentSpaceNormalMap as H,ObjectSpaceNormalMap as W,NoToneMapping as j,LinearToneMapping as X,ReinhardToneMapping as q,CineonToneMapping as Y,ACESFilmicToneMapping as K,OrthographicCamera as Q,BufferGeometry as Z,Float32BufferAttribute as J,HalfFloatType as ee,PointLight as te,DirectionalLight as se,SpotLight as re,AmbientLight as ie,HemisphereLight as ne,Loader as oe,FileLoader as ae,PointsMaterial as ue,LineBasicMaterial as le,LineDashedMaterial as de,MeshNormalMaterial as ce,MeshBasicMaterial as he,MeshLambertMaterial as pe,MeshPhongMaterial as ge,MeshStandardMaterial as me,MeshPhysicalMaterial as fe,SpriteMaterial as Te,MaterialLoader as xe,ObjectLoader as ye,DepthStencilFormat as be,UnsignedInt248Type as Ne,EquirectangularReflectionMapping as _e,EquirectangularRefractionMapping as ve,CubeReflectionMapping as Se,CubeRefractionMapping as Ae,SphereGeometry as Re,Frustum as Ee,DoubleSide as Ce,FrontSide as we,IntType as Me,createCanvasElement as Fe,AddEquation as Be,SubtractEquation as Oe,ReverseSubtractEquation as Le,ZeroFactor as Ue,OneFactor as Ie,SrcColorFactor as De,SrcAlphaFactor as Pe,SrcAlphaSaturateFactor as Ve,DstColorFactor as Ge,DstAlphaFactor as ke,OneMinusSrcColorFactor as ze,OneMinusSrcAlphaFactor as $e,OneMinusDstColorFactor as He,OneMinusDstAlphaFactor as We,CullFaceNone as je,CullFaceBack as Xe,CullFaceFront as qe,CustomBlending as Ye,MultiplyBlending as Ke,SubtractiveBlending as Qe,AdditiveBlending as Ze,NormalBlending as Je,NotEqualDepth as et,GreaterDepth as tt,GreaterEqualDepth as st,EqualDepth as rt,LessEqualDepth as it,LessDepth as nt,AlwaysDepth as ot,NeverDepth as at,UnsignedByteType as ut,UnsignedShort4444Type as lt,UnsignedShort5551Type as dt,ByteType as ct,ShortType as ht,UnsignedShortType as pt,AlphaFormat as gt,RGBAFormat as mt,LuminanceFormat as ft,LuminanceAlphaFormat as Tt,RedFormat as xt,RedIntegerFormat as yt,RGFormat as bt,RGIntegerFormat as Nt,RGBAIntegerFormat as _t,RGB_S3TC_DXT1_Format as vt,RGBA_S3TC_DXT1_Format as St,RGBA_S3TC_DXT3_Format as At,RGBA_S3TC_DXT5_Format as Rt,RGB_PVRTC_4BPPV1_Format as Et,RGB_PVRTC_2BPPV1_Format as Ct,RGBA_PVRTC_4BPPV1_Format as wt,RGBA_PVRTC_2BPPV1_Format as Mt,RGB_ETC1_Format as Ft,RGB_ETC2_Format as Bt,RGBA_ETC2_EAC_Format as Ot,RGBA_ASTC_4x4_Format as Lt,RGBA_ASTC_5x4_Format as Ut,RGBA_ASTC_5x5_Format as It,RGBA_ASTC_6x5_Format as Dt,RGBA_ASTC_6x6_Format as Pt,RGBA_ASTC_8x5_Format as Vt,RGBA_ASTC_8x6_Format as Gt,RGBA_ASTC_8x8_Format as kt,RGBA_ASTC_10x5_Format as zt,RGBA_ASTC_10x6_Format as $t,RGBA_ASTC_10x8_Format as Ht,RGBA_ASTC_10x10_Format as Wt,RGBA_ASTC_12x10_Format as jt,RGBA_ASTC_12x12_Format as Xt,RGBA_BPTC_Format as qt,RED_RGTC1_Format as Yt,SIGNED_RED_RGTC1_Format as Kt,RED_GREEN_RGTC2_Format as Qt,SIGNED_RED_GREEN_RGTC2_Format as Zt,RepeatWrapping as Jt,ClampToEdgeWrapping as es,MirroredRepeatWrapping as ts,NearestMipmapLinearFilter as ss,LinearMipmapNearestFilter as rs,NeverCompare as is,AlwaysCompare as ns,LessEqualCompare as os,EqualCompare as as,GreaterEqualCompare as us,GreaterCompare as ls,NotEqualCompare as ds,WebGLCoordinateSystem as cs,Texture as hs,CubeTexture as ps,NotEqualStencilFunc as gs,GreaterStencilFunc as ms,GreaterEqualStencilFunc as fs,EqualStencilFunc as Ts,LessEqualStencilFunc as xs,LessStencilFunc as ys,AlwaysStencilFunc as bs,NeverStencilFunc as Ns,DecrementWrapStencilOp as _s,IncrementWrapStencilOp as vs,DecrementStencilOp as Ss,IncrementStencilOp as As,InvertStencilOp as Rs,ReplaceStencilOp as Es,ZeroStencilOp as Cs,KeepStencilOp as ws,MaxEquation as Ms,MinEquation as Fs}from"three";void 0===window.GPUShaderStage&&(window.GPUShaderStage={VERTEX:1,FRAGMENT:2,COMPUTE:4});let Bs=!1;if(void 0!==navigator.gpu){null!==await navigator.gpu.requestAdapter()&&(Bs=!0)}class Os{static isAvailable(){return Bs}static getErrorMessage(){const e=document.createElement("div");return e.id="webgpumessage",e.style.fontFamily="monospace",e.style.fontSize="13px",e.style.fontWeight="normal",e.style.textAlign="center",e.style.background="#fff",e.style.color="#000",e.style.padding="1.5em",e.style.maxWidth="400px",e.style.margin="5em auto 0",e.innerHTML='Your browser does not support WebGPU yet',e}}class Ls{constructor(e,t){this.nodes=e,this.info=t,this.animationLoop=null,this.requestId=null,this._init()}_init(){const e=(t,s)=>{this.requestId=self.requestAnimationFrame(e),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this.animationLoop&&this.animationLoop(t,s)};e()}dispose(){self.cancelAnimationFrame(this.requestId)}setAnimationLoop(e){this.animationLoop=e}}class Us{constructor(){this.weakMap=new WeakMap}get(e){if(Array.isArray(e)){let t=this.weakMap;for(let s=0;s{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],r=new Set;for(const i of e){const e=i.node&&i.node.attribute?i.node.attribute:t.getAttribute(i.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;r.add(n)}return this.attributes=s,this.vertexBuffers=Array.from(r.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const e in t){if(/^(is[A-Z])|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;let r=t[e];if(null!==r){const e=typeof r;"number"===e?r=0!==r?"1":"0":"object"===e&&(r="{}")}s+=r+","}return e.skeleton&&(s+=e.skeleton.uuid+","),e.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),s}get needsUpdate(){return this.initialNodesCacheKey!==this.getNodesCacheKey()}getNodesCacheKey(){return this._nodes.getCacheKey(this.scene,this.lightsNode)}getCacheKey(){return this.getMaterialCacheKey()+","+this.getNodesCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}class Ps{constructor(e,t,s,r,i,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=r,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,s,r,i,n,o){const a=this.getChainMap(o),u=[e,t,n,i];let l=a.get(u);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,r,i,n,o),a.set(u,l)):(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,s,r,i,n,o)):l.version=t.version),l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Us)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,r,i,n,o,a,u,l){const d=this.getChainMap(l),c=new Ds(e,t,s,r,i,n,o,a,u);return c.onDispose=()=>{this.pipelines.delete(c),this.bindings.delete(c),this.nodes.delete(c),d.delete(c.getChainArray())},c}}class Vs{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const Gs=1,ks=2,zs=4,$s=16;class Hs extends Vs{constructor(e){super(),this.backend=e}delete(e){void 0!==super.delete(e)&&this.backend.destroyAttribute(e)}update(t,s){const r=this.get(t);if(void 0===r.version)s===Gs?this.backend.createAttribute(t):s===ks?this.backend.createIndexAttribute(t):s===zs&&this.backend.createStorageAttribute(t),r.version=this._getBufferAttribute(t).version;else{const s=this._getBufferAttribute(t);(r.version=0;--t)if(e[t]>=65535)return!0;return!1}(r)?t:s)(r,1);return o.version=Ws(e),o}class Xs extends Vs{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const r=t.index,i=e.getAttributes();null!==r&&this.attributes.delete(r);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",s)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)this.updateAttribute(e,Gs);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,ks)}updateAttribute(e,t){const s=this.info.render.calls;this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndex(e){const{geometry:t,material:s}=e;let r=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=js(t),e.set(t,s)):s.version!==Ws(t)&&(this.attributes.delete(s),s=js(t),e.set(t,s)),r=s}return r}}class qs{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,drawCalls:0,triangles:0,points:0,lines:0},this.compute={calls:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine&&(this.render.lines+=s*(t-1))}reset(){this.render.drawCalls=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.memory.geometries=0,this.memory.textures=0}}class Ys{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Ks extends Ys{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Qs extends Ys{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Zs=0;class Js{constructor(e,t){this.id=Zs++,this.code=e,this.stage=t,this.usedTimes=0}}class er extends Vs{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),o=new Js(n.computeShader,"compute"),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let u=this.caches.get(a);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(e),u=this._getComputePipeline(e,o,a,t)),u.usedTimes++,o.usedTimes++,r.version=e.version,r.pipeline=u}return r.pipeline}getForRender(e){const{backend:t}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const r=s.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const i=e.getNodeBuilderState();let n=this.programs.vertex.get(i.vertexShader);void 0===n&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),n=new Js(i.vertexShader,"vertex"),this.programs.vertex.set(i.vertexShader,n),t.createProgram(n));let o=this.programs.fragment.get(i.fragmentShader);void 0===o&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),o=new Js(i.fragmentShader,"fragment"),this.programs.fragment.set(i.fragmentShader,o),t.createProgram(o));const a=this._getRenderCacheKey(e,n,o);let u=this.caches.get(a);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,n,o,a)):e.pipeline=u,u.usedTimes++,n.usedTimes++,o.usedTimes++,s.pipeline=u}return s.pipeline}delete(e){const t=this.get(e).pipeline;t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,r){s=s||this._getComputeCacheKey(e,t);let i=this.caches.get(s);return void 0===i&&(i=new Qs(s,t),this.caches.set(s,i),this.backend.createComputePipeline(i,r)),i}_getRenderPipeline(e,t,s,r){r=r||this._getRenderCacheKey(e,t,s);let i=this.caches.get(r);return void 0===i&&(i=new Ks(r,t,s),this.caches.set(r,i),e.pipeline=i,this.backend.createRenderPipeline(e)),i}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class tr extends Vs{constructor(e,t,s,r,i,n){super(),this.backend=e,this.textures=s,this.pipelines=i,this.attributes=r,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),s=this.get(e);return s.bindings!==t&&(s.bindings=t,this._init(t),this.backend.createBindings(t)),s.bindings}getForCompute(e){const t=this.get(e);if(void 0===t.bindings){const s=this.nodes.getForCompute(e).bindings.compute;t.bindings=s,this._init(s),this.backend.createBindings(s)}return t.bindings}updateForCompute(e){this._update(e,this.getForCompute(e))}updateForRender(e){this._update(e,this.getForRender(e))}_init(e){for(const t of e)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute;this.attributes.update(e,zs)}}_update(e,t){const{backend:s}=this;let r=!1;for(const e of t){if(e.isNodeUniformsGroup){if(!this.nodes.updateGroup(e))continue}if(e.isUniformBuffer){e.update()&&s.updateBinding(e)}else if(e.isSampledTexture){const t=e.texture;e.needsBindingsUpdate&&(r=!0);if(e.update()&&this.textures.updateTexture(e.texture),!0===t.isStorageTexture){const s=this.get(t);!0===e.store?s.needsMipmap=!0:!0===t.generateMipmaps&&this.textures.needsMipmaps(t)&&!0===s.needsMipmap&&(this.backend.generateMipmaps(t),s.needsMipmap=!1)}}}if(!0===r){const s=this.pipelines.getForRender(e);this.backend.updateBindings(t,s)}}}const sr={VERTEX:"vertex",FRAGMENT:"fragment"},rr={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},ir={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX3:"mat3",MATRIX4:"mat4"},nr=["fragment","vertex"],or=["setup","analyze","generate"],ar=[...nr,"compute"],ur=["x","y","z","w"];function lr(e){let t="{";!0===e.isNode&&(t+=e.id);for(const{property:s,childNode:r}of dr(e))t+=","+s.slice(0,-4)+":"+r.getCacheKey();return t+="}",t}function*dr(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const r=e[s];if(!0===Array.isArray(r))for(let e=0;ee.charCodeAt(0))).buffer}var mr=Object.freeze({__proto__:null,getCacheKey:lr,getNodeChildren:dr,getValueType:cr,getValueFromType:hr,arrayBufferToBase64:pr,base64ToArrayBuffer:gr});const fr=new Map;let Tr=0;class xr extends l{constructor(e=null){super(),this.nodeType=e,this.updateType=rr.NONE,this.updateBeforeType=rr.NONE,this.uuid=d.generateUUID(),this.isNode=!0,Object.defineProperty(this,"id",{value:Tr++})}get type(){return this.constructor.type}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return!1}*getChildren(){for(const{childNode:e}of dr(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(){return lr(this)}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}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);for(const e of this.getChildren())t["_node"+e.id]=e;return null}construct(e){return this.setup(e)}analyze(e){const t=e.getDataFromNode(this);if(t.dependenciesCount=void 0===t.dependenciesCount?1:t.dependenciesCount+1,1===t.dependenciesCount){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){}update(){}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let r=null;const i=e.getBuildStage();if("setup"===i){const t=e.getNodeProperties(this);if(!0!==t.initialized||!1===e.context.tempRead){const s=e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length!==s&&(t.outputNode=e.stack);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}else if("analyze"===i)this.analyze(e);else if("generate"===i){if(1===this.generate.length){const s=this.getNodeType(e),i=e.getDataFromNode(this);r=i.snippet,void 0===r&&(r=this.generate(e)||"",i.snippet=r),r=e.format(r,s,t)}else r=this.generate(e,t)||""}return e.removeChain(this),r}getSerializeChildren(){return dr(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:r,index:i,childNode:n}of t)void 0!==i?(void 0===s[r]&&(s[r]=Number.isInteger(i)?[]:{}),s[r][i]=n.toJSON(e.meta).uuid):s[r]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const r=[];for(const i of e.inputNodes[s])r.push(t[i]);this[s]=r}else if("object"==typeof e.inputNodes[s]){const r={};for(const i in e.inputNodes[s]){const n=e.inputNodes[s][i];r[i]=t[n]}this[s]=r}else{const r=e.inputNodes[s];this[s]=t[r]}}}toJSON(e){const{uuid:t,type:s}=this,r=void 0===e||"string"==typeof e;r&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const s in e){const r=e[s];delete r.metadata,t.push(r)}return t}if(void 0===i&&(i={uuid:t,type:s,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==r&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),r){const t=n(e.textures),s=n(e.images),r=n(e.nodes);t.length>0&&(i.textures=t),s.length>0&&(i.images=s),r.length>0&&(i.nodes=r)}return i}}function yr(e,t){if("function"!=typeof t||!e)throw new Error(`Node class ${e} is not a class`);fr.has(e)||(fr.set(e,t),t.type=e)}function br(e){const t=fr.get(e);if(void 0!==t)return new t}class Nr extends xr{constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?cr(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=cr(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=pr(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?hr(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){}}yr("InputNode",Nr);class _r extends xr{constructor(e,t=!1){super("string"),this.name=e,this.version=0,this.shared=t,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}}const vr=e=>new _r(e),Sr=e=>new _r(e,!0),Ar=Sr("frame"),Rr=Sr("render"),Er=vr("object");yr("UniformGroupNode",_r);class Cr extends xr{constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getNodeType(e)}generate(e){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}yr("ArrayElementNode",Cr);class wr extends xr{constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const r of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(r)||(s=r);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,r=this.getNodeType(e),i=s.build(e,r);return e.format(i,r,t)}}yr("ConvertNode",wr);class Mr extends xr{constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).dependenciesCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(!1!==e.context.tempRead&&void 0!==r.propertyName)return e.format(r.propertyName,s,t);if(!1!==e.context.tempWrite&&"void"!==s&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${i}`),r.snippet=i,r.propertyName=o,e.format(r.propertyName,s,t)}}return super.build(e,t)}}yr("TempNode",Mr);class Fr extends Mr{constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,s)=>t+e.getTypeLength(s.getNodeType(e))),0))}generate(e,t){const s=this.getNodeType(e),r=this.nodes,i=e.getPrimitiveType(s),n=[];for(const t of r){let s=t.build(e);const r=e.getPrimitiveType(t.getNodeType(e));r!==i&&(s=e.format(s,r,i)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}yr("JoinNode",Fr);const Br=ur.join("");class Or extends xr{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(ur.indexOf(t)+1,e);return e}getPrimitiveType(e){return e.getPrimitiveType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getPrimitiveType(e))}generate(e,t){const s=this.node,r=e.getTypeLength(s.getNodeType(e));let i=null;if(r>1){let n=null;this.getVectorLength()>=r&&(n=e.getTypeFromLength(this.getVectorLength(),this.getPrimitiveType(e)));const o=s.build(e,n);i=this.components.length===r&&this.components===Br.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else i=s.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}yr("SplitNode",Or);class Lr extends Mr{constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:r}=this,i=this.getNodeType(e),n=e.getTypeFromLength(s.length),o=r.build(e,n),a=t.build(e,i),u=e.getTypeLength(i),l=[];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"),Gr={setup(e,t){const s=t.shift();return e(di(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Ir.assign(s,...e),s);if(Dr.has(t)){const r=Dr.get(t);return e.isStackNode?(...e)=>s.add(r(...e)):(...e)=>r(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Dr.has(t.slice(0,t.length-6))){const r=Dr.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],r(...e)):(...e)=>s.assign(r(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Vr(t),li(new Or(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=(t=Vr(t.slice(3).toLowerCase())).split("").sort().join(""),s=>li(new Lr(e,t,s));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),li(new Or(e,t));if(!0===/^\d+$/.test(t))return li(new Cr(s,new Ur(Number(t),"uint")))}return Reflect.get(e,t,s)},set:(e,t,s,r)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,r):(r[t].assign(s),!0)},kr=new WeakMap,zr=new WeakMap,$r=function(e,t=null){for(const s in e)e[s]=li(e[s],t);return e},Hr=function(e,t=null){const s=e.length;for(let r=0;rli(null!==r?Object.assign(e,r):e);return null===t?(...t)=>i(new e(...ci(t))):null!==s?(s=li(s),(...r)=>i(new e(t,...ci(r),s))):(...s)=>i(new e(t,...ci(s)))},jr=function(e,...t){return li(new e(...ci(t)))};class Xr extends xr{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){const{outputNode:t}=e.getNodeProperties(this);return t?t.getNodeType(e):super.getNodeType(e)}call(e){const{shaderNode:t,inputNodes:s}=this;if(t.layout){let r=zr.get(e.constructor);void 0===r&&(r=new WeakMap,zr.set(e.constructor,r));let i=r.get(t);return void 0===i&&(i=li(e.buildFunctionNode(t)),r.set(t,i)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(i),li(i.call(s))}const r=t.jsFunc,i=null!==s?r(s,e.stack,e):r(e.stack,e);return li(i)}setup(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);return null===s?this.call(e).build(e,t):super.generate(e,t)}}class qr extends xr{constructor(e){super(),this.jsFunc=e,this.layout=null}get isArrayInput(){return/^\((\s+)?\[/.test(this.jsFunc.toString())}setLayout(e){return this.layout=e,this}call(e=null){return di(e),li(new Xr(this,e))}setup(){return this.call()}}const Yr=[!1,!0],Kr=[0,1,2,3],Qr=[-1,-2],Zr=[.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],Jr=new Map;for(const e of Yr)Jr.set(e,new Ur(e));const ei=new Map;for(const e of Kr)ei.set(e,new Ur(e,"uint"));const ti=new Map([...ei].map((e=>new Ur(e.value,"int"))));for(const e of Qr)ti.set(e,new Ur(e,"int"));const si=new Map([...ti].map((e=>new Ur(e.value))));for(const e of Zr)si.set(e,new Ur(e));for(const e of Zr)si.set(-e,new Ur(-e));const ri={bool:Jr,uint:ei,ints:ti,float:si},ii=new Map([...Jr,...si]),ni=(e,t)=>ii.has(e)?ii.get(e):!0===e.isNode?e:new Ur(e,t),oi=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[hr(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return li(t.get(s[0]));if(1===s.length){const t=ni(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?li(t):li(new wr(t,e))}const r=s.map((e=>ni(e)));return li(new Fr(r,e))}},ai=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function ui(e){return new Proxy(new qr(e),Gr)}const li=(e,t=null)=>function(e,t=null){const s=cr(e);if("node"===s){let t=kr.get(e);return void 0===t&&(t=new Proxy(e,Gr),kr.set(e,t),kr.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?li(ni(e,t)):"shader"===s?mi(e):e}(e,t),di=(e,t=null)=>new $r(e,t),ci=(e,t=null)=>new Hr(e,t),hi=(...e)=>new Wr(...e),pi=(...e)=>new jr(...e),gi=e=>new ui(e),mi=e=>{const t=new ui(e),s=(...e)=>{let s;return di(e),s=e[0]&&e[0].isNode?[...e]:e[0],t.call(s)};return s.shaderNode=t,s.setLayout=e=>(t.setLayout(e),s),s};yr("ShaderNode",ui);const fi=e=>{Ir=e},Ti=()=>Ir,xi=(...e)=>Ir.if(...e);function yi(e){return Ir&&Ir.add(e),e}Pr("append",yi);const bi=new oi("color"),Ni=new oi("float",ri.float),_i=new oi("int",ri.int),vi=new oi("uint",ri.uint),Si=new oi("bool",ri.bool),Ai=new oi("vec2"),Ri=new oi("ivec2"),Ei=new oi("uvec2"),Ci=new oi("bvec2"),wi=new oi("vec3"),Mi=new oi("ivec3"),Fi=new oi("uvec3"),Bi=new oi("bvec3"),Oi=new oi("vec4"),Li=new oi("ivec4"),Ui=new oi("uvec4"),Ii=new oi("bvec4"),Di=new oi("mat3"),Pi=new oi("imat3"),Vi=new oi("umat3"),Gi=new oi("bmat3"),ki=new oi("mat4"),zi=new oi("imat4"),$i=new oi("umat4"),Hi=new oi("bmat4"),Wi=(e="")=>li(new Ur(e,"string")),ji=e=>li(new Ur(e,"ArrayBuffer"));Pr("color",bi),Pr("float",Ni),Pr("int",_i),Pr("uint",vi),Pr("bool",Si),Pr("vec2",Ai),Pr("ivec2",Ri),Pr("uvec2",Ei),Pr("bvec2",Ci),Pr("vec3",wi),Pr("ivec3",Mi),Pr("uvec3",Fi),Pr("bvec3",Bi),Pr("vec4",Oi),Pr("ivec4",Li),Pr("uvec4",Ui),Pr("bvec4",Ii),Pr("mat3",Di),Pr("imat3",Pi),Pr("umat3",Vi),Pr("bmat3",Gi),Pr("mat4",ki),Pr("imat4",zi),Pr("umat4",$i),Pr("bmat4",Hi),Pr("string",Wi),Pr("arrayBuffer",ji);const Xi=hi(Cr),qi=(e,t)=>li(new wr(li(e),t)),Yi=(e,t)=>li(new Or(li(e),t));Pr("element",Xi),Pr("convert",qi);class Ki extends Nr{constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.groupNode=Er}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}generate(e,t){const s=this.getNodeType(e),r=this.getUniformHash(e);let i=e.getNodeFromHash(r);void 0===i&&(e.setHashNode(this,r),i=this);const n=i.getInputType(e),o=e.getUniformFromNode(i,n,e.shaderStage,e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const Qi=(e,t)=>{const s=ai(t||e),r=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return li(new Ki(r,s))};yr("UniformNode",Ki);class Zi extends Ki{constructor(e=[]){super(),this.isArrayUniformNode=!0,this.nodes=e}getNodeType(e){return this.nodes[0].getNodeType(e)}}yr("ArrayUniformNode",Zi);class Ji extends Mr{constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}generate(e,t){const s=this.targetNode,r=this.sourceNode,i=s.getNodeType(e),n=s.build(e),o=`${n} = ${r.build(e,i)}`;if("void"!==t){return"void"===r.getNodeType(e)?(e.addLineFlowCode(o),n):e.format(o,i,t)}e.addLineFlowCode(o)}}const en=hi(Ji);yr("AssignNode",Ji),Pr("assign",en);class tn extends xr{constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{name:t,node:s}=this,r=this.getNodeType(e),i=e.getVaryingFromNode(this,t,r);i.needsInterpolation||(i.needsInterpolation="fragment"===e.shaderStage);const n=e.getPropertyName(i,sr.VERTEX);return e.flowNodeFromShaderStage(sr.VERTEX,s,r,n),e.getPropertyName(i)}}const sn=hi(tn);Pr("varying",sn),yr("VaryingNode",tn);class rn extends xr{constructor(e,t=null){super(t),this._attributeName=e}isGlobal(){return!0}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=super.getNodeType(e);if(null===t){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const r=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(r)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const r=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(r),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,s);return sn(this).build(e,s)}return e.generateConst(s)}}const nn=(e,t)=>li(new rn(e,t));yr("AttributeNode",rn);class on extends xr{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.outputNode.build(e)}}const an=hi(on);Pr("bypass",an),yr("BypassNode",on);let un=0;class ln{constructor(){this.id=un++,this.nodesData=new WeakMap}getNodeData(e){return this.nodesData.get(e)}setNodeData(e,t){this.nodesData.set(e,t)}}class dn extends xr{constructor(e,t=new ln){super(),this.isCacheNode=!0,this.node=e,this.cache=t}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const s=e.getCache(),r=this.cache||e.globalCache;e.setCache(r);const i=this.node.build(e,...t);return e.setCache(s),i}}const cn=hi(dn);Pr("cache",cn),Pr("globalCache",(e=>cn(e,null))),yr("CacheNode",dn);class hn extends xr{constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.context=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.context});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.context});const r=this.node.build(e,t);return e.setContext(s),r}}const pn=hi(hn),gn=(e,t)=>pn(e,{label:t});Pr("context",pn),Pr("label",gn),yr("ContextNode",hn);class mn extends xr{constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let r,i;if(s===mn.VERTEX)r=e.getVertexIndex();else{if(s!==mn.INSTANCE)throw new Error("THREE.IndexNode: Unknown scope: "+s);r=e.getInstanceIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=r;else{i=sn(this).build(e,t)}return i}}mn.VERTEX="vertex",mn.INSTANCE="instance";const fn=pi(mn,mn.VERTEX),Tn=pi(mn,mn.INSTANCE);yr("IndexNode",mn);class xn{start(){}finish(){}direct(){}indirectDiffuse(){}indirectSpecular(){}ambientOcclusion(){}}class yn extends xr{constructor(e,t=null){super(),this.node=e,this.name=t,this.isVarNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,r=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),i=e.getPropertyName(r),n=t.build(e,r.type);return e.addLineFlowCode(`${i} = ${n}`),i}}const bn=hi(yn);Pr("temp",bn),Pr("toVar",((...e)=>bn(...e).append())),yr("VarNode",yn);class Nn{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class _n{constructor(e,t,s,r=void 0){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf(),this.needsUpdate=r}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class vn{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class Sn extends vn{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class An{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}class Rn{constructor(){this.keywords=[],this.nodes=[],this.keywordsCallback={}}getNode(e){let t=this.nodes[e];return void 0===t&&void 0!==this.keywordsCallback[e]&&(t=this.keywordsCallback[e](e),this.nodes[e]=t),t}addKeyword(e,t){return this.keywords.push(e),this.keywordsCallback[e]=t,this}parse(e){const t=this.keywords,s=new RegExp(`\\b${t.join("\\b|\\b")}\\b`,"g"),r=e.match(s),i=[];if(null!==r)for(const e of r){const t=this.getNode(e);void 0!==t&&-1===i.indexOf(t)&&i.push(t)}return i}include(e,t){const s=this.parse(t);for(const t of s)t.build(e)}}class En extends xr{constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Cn=(e,t)=>li(new En(e,t)),wn=(e,t)=>li(new En(e,t,!0)),Mn=pi(En,"vec4","DiffuseColor"),Fn=pi(En,"float","Roughness"),Bn=pi(En,"float","Metalness"),On=pi(En,"float","Clearcoat"),Ln=pi(En,"float","ClearcoatRoughness"),Un=pi(En,"vec3","Sheen"),In=pi(En,"float","SheenRoughness"),Dn=pi(En,"float","Iridescence"),Pn=pi(En,"float","IridescenceIOR"),Vn=pi(En,"float","IridescenceThickness"),Gn=pi(En,"color","SpecularColor"),kn=pi(En,"float","Shininess"),zn=pi(En,"vec4","Output"),$n=pi(En,"float","dashSize"),Hn=pi(En,"float","gapSize"),Wn=pi(En,"float","pointWidth");yr("PropertyNode",En);class jn extends En{constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const Xn=(e,t)=>li(new jn(e,t));yr("ParameterNode",jn);class qn extends xr{constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const Yn=hi(qn),Kn=(e,t)=>Yn(e,t,"js"),Qn=(e,t)=>Yn(e,t,"wgsl"),Zn=(e,t)=>Yn(e,t,"glsl");yr("CodeNode",qn);class Jn extends qn{constructor(e="",t=[],s=""){super(e,t,s),this.keywords={}}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),r=s.name,i=s.type,n=e.getCodeFromNode(this,i);""!==r&&(n.name=r);const o=e.getPropertyName(n);let a=this.getNodeFunction(e).getCode(o);const u=this.keywords,l=Object.keys(u);if(l.length>0)for(const t of l){const s=new RegExp(`\\b${t}\\b`,"g"),r=u[t].build(e,"property");a=a.replace(s,r)}return n.code=a+"\n","property"===t?o:e.format(`${o}()`,i,t)}}const eo=(e,t=[],s="")=>{for(let e=0;er.call(...e);return i.functionNode=r,i},to=(e,t)=>eo(e,t,"glsl"),so=(e,t)=>eo(e,t,"wgsl");yr("FunctionNode",Jn);class ro extends rn{constructor(e=0){super(null,"vec2"),this.isUVNode=!0,this.index=e}getAttributeName(){const e=this.index;return"uv"+(e>0?e:"")}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const io=(...e)=>li(new ro(...e));yr("UVNode",ro);class no extends xr{constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),r=this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${r} )`,this.getNodeType(e),t)}}const oo=hi(no);Pr("textureSize",oo),yr("TextureSizeNode",no);class ao extends Mr{constructor(e,t,s,...r){if(super(),this.op=e,r.length>0){let t=s;for(let s=0;s>"===s||"<<"===s)return e.getIntegerType(n);if("=="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,r=this.aNode,i=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=r.getNodeType(e),a=i.getNodeType(e),"<"===s||">"===s||"<="===s||">="===s||"=="===s?e.isVector(o)?a=o:o=a="float":">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):a=n):o=a=n;const u=r.build(e,o),l=i.build(e,a),d=e.getTypeLength(t),c=e.getFunctionOperator(s);return"void"!==t?"<"===s&&d>1?e.format(`${e.getMethod("lessThan")}( ${u}, ${l} )`,n,t):"<="===s&&d>1?e.format(`${e.getMethod("lessThanEqual")}( ${u}, ${l} )`,n,t):">"===s&&d>1?e.format(`${e.getMethod("greaterThan")}( ${u}, ${l} )`,n,t):">="===s&&d>1?e.format(`${e.getMethod("greaterThanEqual")}( ${u}, ${l} )`,n,t):c?e.format(`${c}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${s} ${l} )`,n,t):"void"!==o?c?e.format(`${c}( ${u}, ${l} )`,n,t):e.format(`${u} ${s} ${l}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const uo=hi(ao,"+"),lo=hi(ao,"-"),co=hi(ao,"*"),ho=hi(ao,"/"),po=hi(ao,"%"),go=hi(ao,"=="),mo=hi(ao,"!="),fo=hi(ao,"<"),To=hi(ao,">"),xo=hi(ao,"<="),yo=hi(ao,">="),bo=hi(ao,"&&"),No=hi(ao,"||"),_o=hi(ao,"^^"),vo=hi(ao,"&"),So=hi(ao,"|"),Ao=hi(ao,"^"),Ro=hi(ao,"<<"),Eo=hi(ao,">>");Pr("add",uo),Pr("sub",lo),Pr("mul",co),Pr("div",ho),Pr("remainder",po),Pr("equal",go),Pr("notEqual",mo),Pr("lessThan",fo),Pr("greaterThan",To),Pr("lessThanEqual",xo),Pr("greaterThanEqual",yo),Pr("and",bo),Pr("or",No),Pr("xor",_o),Pr("bitAnd",vo),Pr("bitOr",So),Pr("bitXor",Ao),Pr("shiftLeft",Ro),Pr("shiftRight",Eo),yr("OperatorNode",ao);class Co extends Mr{constructor(e,t,s=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=r}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(r)?0:e.getTypeLength(r);return i>n&&i>o?t:n>o?s:o>i?r:t}getNodeType(e){const t=this.method;return t===Co.LENGTH||t===Co.DISTANCE||t===Co.DOT?"float":t===Co.CROSS?"vec3":t===Co.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,r=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,u=!0===e.renderer.isWebGLRenderer;if(s===Co.TRANSFORM_DIRECTION){let s=n,r=o;e.isMatrix(s.getNodeType(e))?r=Oi(wi(r),0):s=Oi(wi(s),0);const i=co(s,r).xyz;return ko(i).build(e,t)}if(s===Co.NEGATE)return e.format("( - "+n.build(e,i)+" )",r,t);if(s===Co.ONE_MINUS)return lo(1,n).build(e,t);if(s===Co.RECIPROCAL)return ho(1,n).build(e,t);if(s===Co.DIFFERENCE)return Yo(lo(n,o)).build(e,t);{const l=[];return s===Co.CROSS||s===Co.MOD?l.push(n.build(e,r),o.build(e,r)):s===Co.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),o.build(e,i)):u&&(s===Co.MIN||s===Co.MAX)||s===Co.MOD?l.push(n.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):s===Co.REFRACT?l.push(n.build(e,i),o.build(e,i),a.build(e,"float")):s===Co.MIX?l.push(n.build(e,i),o.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)):(l.push(n.build(e,i)),null!==o&&l.push(o.build(e,i)),null!==a&&l.push(a.build(e,i))),e.format(`${e.getMethod(s,r)}( ${l.join(", ")} )`,r,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Co.RADIANS="radians",Co.DEGREES="degrees",Co.EXP="exp",Co.EXP2="exp2",Co.LOG="log",Co.LOG2="log2",Co.SQRT="sqrt",Co.INVERSE_SQRT="inversesqrt",Co.FLOOR="floor",Co.CEIL="ceil",Co.NORMALIZE="normalize",Co.FRACT="fract",Co.SIN="sin",Co.COS="cos",Co.TAN="tan",Co.ASIN="asin",Co.ACOS="acos",Co.ATAN="atan",Co.ABS="abs",Co.SIGN="sign",Co.LENGTH="length",Co.NEGATE="negate",Co.ONE_MINUS="oneMinus",Co.DFDX="dFdx",Co.DFDY="dFdy",Co.ROUND="round",Co.RECIPROCAL="reciprocal",Co.TRUNC="trunc",Co.FWIDTH="fwidth",Co.BITCAST="bitcast",Co.ATAN2="atan2",Co.MIN="min",Co.MAX="max",Co.MOD="mod",Co.STEP="step",Co.REFLECT="reflect",Co.DISTANCE="distance",Co.DIFFERENCE="difference",Co.DOT="dot",Co.CROSS="cross",Co.POW="pow",Co.TRANSFORM_DIRECTION="transformDirection",Co.MIX="mix",Co.CLAMP="clamp",Co.REFRACT="refract",Co.SMOOTHSTEP="smoothstep",Co.FACEFORWARD="faceforward";const wo=Ni(1e-6),Mo=Ni(1e6),Fo=hi(Co,Co.RADIANS),Bo=hi(Co,Co.DEGREES),Oo=hi(Co,Co.EXP),Lo=hi(Co,Co.EXP2),Uo=hi(Co,Co.LOG),Io=hi(Co,Co.LOG2),Do=hi(Co,Co.SQRT),Po=hi(Co,Co.INVERSE_SQRT),Vo=hi(Co,Co.FLOOR),Go=hi(Co,Co.CEIL),ko=hi(Co,Co.NORMALIZE),zo=hi(Co,Co.FRACT),$o=hi(Co,Co.SIN),Ho=hi(Co,Co.COS),Wo=hi(Co,Co.TAN),jo=hi(Co,Co.ASIN),Xo=hi(Co,Co.ACOS),qo=hi(Co,Co.ATAN),Yo=hi(Co,Co.ABS),Ko=hi(Co,Co.SIGN),Qo=hi(Co,Co.LENGTH),Zo=hi(Co,Co.NEGATE),Jo=hi(Co,Co.ONE_MINUS),ea=hi(Co,Co.DFDX),ta=hi(Co,Co.DFDY),sa=hi(Co,Co.ROUND),ra=hi(Co,Co.RECIPROCAL),ia=hi(Co,Co.TRUNC),na=hi(Co,Co.FWIDTH),oa=hi(Co,Co.BITCAST),aa=hi(Co,Co.ATAN2),ua=hi(Co,Co.MIN),la=hi(Co,Co.MAX),da=hi(Co,Co.MOD),ca=hi(Co,Co.STEP),ha=hi(Co,Co.REFLECT),pa=hi(Co,Co.DISTANCE),ga=hi(Co,Co.DIFFERENCE),ma=hi(Co,Co.DOT),fa=hi(Co,Co.CROSS),Ta=hi(Co,Co.POW),xa=hi(Co,Co.POW,2),ya=hi(Co,Co.POW,3),ba=hi(Co,Co.POW,4),Na=hi(Co,Co.TRANSFORM_DIRECTION),_a=e=>co(Ko(e),Ta(Yo(e),1/3)),va=hi(Co,Co.MIX),Sa=(e,t=0,s=1)=>li(new Co(Co.CLAMP,li(e),li(t),li(s))),Aa=e=>Sa(e),Ra=hi(Co,Co.REFRACT),Ea=hi(Co,Co.SMOOTHSTEP),Ca=hi(Co,Co.FACEFORWARD);Pr("radians",Fo),Pr("degrees",Bo),Pr("exp",Oo),Pr("exp2",Lo),Pr("log",Uo),Pr("log2",Io),Pr("sqrt",Do),Pr("inverseSqrt",Po),Pr("floor",Vo),Pr("ceil",Go),Pr("normalize",ko),Pr("fract",zo),Pr("sin",$o),Pr("cos",Ho),Pr("tan",Wo),Pr("asin",jo),Pr("acos",Xo),Pr("atan",qo),Pr("abs",Yo),Pr("sign",Ko),Pr("length",Qo),Pr("negate",Zo),Pr("oneMinus",Jo),Pr("dFdx",ea),Pr("dFdy",ta),Pr("round",sa),Pr("reciprocal",ra),Pr("trunc",ia),Pr("fwidth",na),Pr("atan2",aa),Pr("min",ua),Pr("max",la),Pr("mod",da),Pr("step",ca),Pr("reflect",ha),Pr("distance",pa),Pr("dot",ma),Pr("cross",fa),Pr("pow",Ta),Pr("pow2",xa),Pr("pow3",ya),Pr("pow4",ba),Pr("transformDirection",Na),Pr("mix",((e,t,s)=>va(t,s,e))),Pr("clamp",Sa),Pr("refract",Ra),Pr("smoothstep",((e,t,s)=>Ea(t,s,e))),Pr("faceForward",Ca),Pr("difference",ga),Pr("saturate",Aa),Pr("cbrt",_a),yr("MathNode",Co);const wa=mi((e=>{const{value:t}=e,{rgb:s}=t,r=s.mul(.9478672986).add(.0521327014).pow(2.4),i=s.mul(.0773993808),n=s.lessThanEqual(.04045),o=va(r,i,n);return Oi(o,t.a)})),Ma=mi((e=>{const{value:t}=e,{rgb:s}=t,r=s.pow(.41666).mul(1.055).sub(.055),i=s.mul(12.92),n=s.lessThanEqual(.0031308),o=va(r,i,n);return Oi(o,t.a)})),Fa=e=>{let t=null;return e===c?t="Linear":e===h&&(t="sRGB"),t},Ba=(e,t)=>Fa(e)+"To"+Fa(t);class Oa extends Mr{constructor(e,t){super("vec4"),this.method=e,this.node=t}setup(){const{method:e,node:t}=this;return e===Oa.LINEAR_TO_LINEAR?t:La[e]({value:t})}}Oa.LINEAR_TO_LINEAR="LinearToLinear",Oa.LINEAR_TO_sRGB="LinearTosRGB",Oa.sRGB_TO_LINEAR="sRGBToLinear";const La={[Oa.LINEAR_TO_sRGB]:Ma,[Oa.sRGB_TO_LINEAR]:wa},Ua=(e,t)=>li(new Oa(Ba(c,t),li(e))),Ia=(e,t)=>li(new Oa(Ba(t,c),li(e))),Da=hi(Oa,Oa.LINEAR_TO_sRGB),Pa=hi(Oa,Oa.sRGB_TO_LINEAR);Pr("linearTosRGB",Da),Pr("sRGBToLinear",Pa),Pr("linearToColorSpace",Ua),Pr("colorSpaceToLinear",Ia),yr("ColorSpaceNode",Oa);class Va extends xr{constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),r=this.snippet;if("void"!==s)return e.format(`( ${r} )`,s,t);e.addLineFlowCode(r)}}const Ga=hi(Va);yr("ExpressionNode",Va);class ka extends Ki{constructor(e){super(0),this.textureNode=e,this.updateType=rr.FRAME}get texture(){return this.textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const za=hi(ka);yr("MaxMipLevelNode",ka);class $a extends Ki{constructor(e,t=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.compareNode=null,this.depthNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=rr.NONE,this.setUpdateMatrix(null===t)}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":"vec4"}getInputType(){return"texture"}getDefaultUV(){return io(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){const t=this.value;return Qi(t.matrix).mul(wi(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?rr.FRAME:rr.NONE,this}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture&&!0!==s.isDepthTexture||(t=t.setY(t.y.oneMinus())),t}setup(e){const t=e.getNodeProperties(this);let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),null!==r&&void 0!==e.context.getTextureLevelAlgorithm&&(r=e.context.getTextureLevelAlgorithm(this,r)),t.uvNode=s,t.levelNode=r,t.compareNode=this.compareNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,r,i,n){const o=this.value;let a;return a=r?e.generateTextureLevel(o,t,s,r,i):n?e.generateTextureCompare(o,t,s,n,i):!1===this.sampler?e.generateTextureLoad(o,t,s,i):e.generateTexture(o,t,s,i),a}generate(e,t){const s=e.getNodeProperties(this),r=this.value;if(!r||!0!==r.isTexture)throw new Error("TextureNode: Need a three.js texture.");const i=super.generate(e,"property");if("sampler"===t)return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:r,compareNode:a,depthNode:u}=s,l=this.generateUV(e,t),d=r?r.build(e,"float"):null,c=u?u.build(e,"int"):null,h=a?a.build(e,"float"):null,p=e.getVarFromNode(this);o=e.getPropertyName(p);const g=this.generateSnippet(e,i,l,d,c,h);e.addLineFlowCode(`${o} = ${g}`),!1!==e.context.tempWrite&&(n.snippet=g,n.propertyName=o)}let a=o;const u=this.getNodeType(e);return e.needsColorSpaceToLinear(r)&&(a=Ia(Ga(a,u),r.colorSpace).setup(e).build(e,u)),e.format(a,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=e,li(t)}blur(e){const t=this.clone();return t.levelNode=e.mul(za(t)),li(t)}level(e){const t=this.clone();return t.levelNode=e,t}size(e){return oo(this,e)}compare(e){const t=this.clone();return t.compareNode=li(e),li(t)}depth(e){const t=this.clone();return t.depthNode=li(e),li(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value]}update(){const e=this.value;!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e}}const Ha=hi($a),Wa=(...e)=>Ha(...e).setSampler(!1),ja=e=>(!0===e.isNode?e:Ha(e)).convert("sampler");Pr("texture",Ha),yr("TextureNode",$a);class Xa extends xr{constructor(e,t,s=null){super(),this.property=e,this.index=null,this.uniformType=t,this.object=s,this.reference=null,this.node=null,this.updateType=rr.OBJECT,this.setNodeType(t)}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setIndex(e){return this.index=e,this}getIndex(){return this.index}setNodeType(e){let t=null;t="texture"===e?Ha(null):Qi(e),this.node=t}getNodeType(e){return this.node.getNodeType(e)}update(){let e=this.reference[this.property];null!==this.index&&(e=e[this.index]),this.node.value=e}setup(){return this.node}}const qa=(e,t,s)=>li(new Xa(e,t,s)),Ya=(e,t,s,r)=>li(new Xa(e,s,r).setIndex(t));yr("ReferenceNode",Xa);class Ka extends Xa{constructor(e,t,s=null){super(e,t,s),this.material=s}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}setup(e){const t=null!==this.material?this.material:e.material;return this.node.value=t[this.property],super.setup(e)}}const Qa=(e,t,s)=>li(new Ka(e,t,s));yr("MaterialReferenceNode",Ka);class Za extends xr{constructor(e=Za.VIEW_MATRIX,t=null){super(),this.scope=e,this.object3d=t,this.updateType=rr.OBJECT,this._uniformNode=new Ki(null)}getNodeType(){const e=this.scope;return e===Za.WORLD_MATRIX||e===Za.VIEW_MATRIX?"mat4":e===Za.NORMAL_MATRIX?"mat3":e===Za.POSITION||e===Za.VIEW_POSITION||e===Za.DIRECTION||e===Za.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,r=this.scope;if(r===Za.VIEW_MATRIX)s.value=t.modelViewMatrix;else if(r===Za.NORMAL_MATRIX)s.value=t.normalMatrix;else if(r===Za.WORLD_MATRIX)s.value=t.matrixWorld;else if(r===Za.POSITION)s.value=s.value||new n,s.value.setFromMatrixPosition(t.matrixWorld);else if(r===Za.SCALE)s.value=s.value||new n,s.value.setFromMatrixScale(t.matrixWorld);else if(r===Za.DIRECTION)s.value=s.value||new n,t.getWorldDirection(s.value);else if(r===Za.VIEW_POSITION){const r=e.camera;s.value=s.value||new n,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(r.matrixWorldInverse)}}generate(e){const t=this.scope;return t===Za.WORLD_MATRIX||t===Za.VIEW_MATRIX?this._uniformNode.nodeType="mat4":t===Za.NORMAL_MATRIX?this._uniformNode.nodeType="mat3":t!==Za.POSITION&&t!==Za.VIEW_POSITION&&t!==Za.DIRECTION&&t!==Za.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Za.VIEW_MATRIX="viewMatrix",Za.NORMAL_MATRIX="normalMatrix",Za.WORLD_MATRIX="worldMatrix",Za.POSITION="position",Za.SCALE="scale",Za.VIEW_POSITION="viewPosition",Za.DIRECTION="direction";const Ja=hi(Za,Za.DIRECTION),eu=hi(Za,Za.VIEW_MATRIX),tu=hi(Za,Za.NORMAL_MATRIX),su=hi(Za,Za.WORLD_MATRIX),ru=hi(Za,Za.POSITION),iu=hi(Za,Za.SCALE),nu=hi(Za,Za.VIEW_POSITION);yr("Object3DNode",Za);class ou extends Za{constructor(e=ou.POSITION){super(e),this.updateType=rr.RENDER}getNodeType(e){const t=this.scope;return t===ou.PROJECTION_MATRIX?"mat4":t===ou.NEAR||t===ou.FAR||t===ou.LOG_DEPTH?"float":super.getNodeType(e)}update(e){const t=e.camera,s=this._uniformNode,r=this.scope;r===ou.VIEW_MATRIX?s.value=t.matrixWorldInverse:r===ou.PROJECTION_MATRIX?s.value=t.projectionMatrix:r===ou.NEAR?s.value=t.near:r===ou.FAR?s.value=t.far:r===ou.LOG_DEPTH?s.value=2/(Math.log(t.far+1)/Math.LN2):(this.object3d=t,super.update(e))}generate(e){const t=this.scope;return t===ou.PROJECTION_MATRIX?this._uniformNode.nodeType="mat4":t!==ou.NEAR&&t!==ou.FAR&&t!==ou.LOG_DEPTH||(this._uniformNode.nodeType="float"),super.generate(e)}}ou.PROJECTION_MATRIX="projectionMatrix",ou.NEAR="near",ou.FAR="far",ou.LOG_DEPTH="logDepth";const au=gn(pi(ou,ou.PROJECTION_MATRIX),"projectionMatrix"),uu=pi(ou,ou.NEAR),lu=pi(ou,ou.FAR),du=pi(ou,ou.LOG_DEPTH),cu=pi(ou,ou.VIEW_MATRIX),hu=pi(ou,ou.NORMAL_MATRIX),pu=pi(ou,ou.WORLD_MATRIX),gu=pi(ou,ou.POSITION);yr("CameraNode",ou);class mu extends Za{constructor(e=mu.VIEW_MATRIX){super(e)}update(e){this.object3d=e.object,super.update(e)}}const fu=pi(mu,mu.DIRECTION),Tu=pi(mu,mu.VIEW_MATRIX).label("modelViewMatrix").temp("ModelViewMatrix"),xu=pi(mu,mu.NORMAL_MATRIX),yu=pi(mu,mu.WORLD_MATRIX),bu=pi(mu,mu.POSITION),Nu=pi(mu,mu.SCALE),_u=pi(mu,mu.VIEW_POSITION);yr("ModelNode",mu);class vu extends xr{constructor(e=vu.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`normal-${this.scope}`}generate(e){const t=this.scope;let s=null;if(t===vu.GEOMETRY)s=nn("normal","vec3");else if(t===vu.LOCAL)s=sn(Su);else if(t===vu.VIEW){const e=xu.mul(Au);s=ko(sn(e))}else if(t===vu.WORLD){const e=Ru.transformDirection(cu);s=ko(sn(e))}return s.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}vu.GEOMETRY="geometry",vu.LOCAL="local",vu.VIEW="view",vu.WORLD="world";const Su=pi(vu,vu.GEOMETRY),Au=pi(vu,vu.LOCAL).temp("Normal"),Ru=pi(vu,vu.VIEW),Eu=pi(vu,vu.WORLD),Cu=Cn("vec3","TransformedNormalView"),wu=Cu.transformDirection(cu).normalize(),Mu=Cn("vec3","TransformedClearcoatNormalView");yr("NormalNode",vu);const Fu=new Map;class Bu extends xr{constructor(e){super(),this.scope=e}getCache(e,t){let s=Fu.get(e);return void 0===s&&(s=Qa(e,t),Fu.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let r=null;if(s===Bu.COLOR){const e=this.getColor(s);r=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===Bu.OPACITY){const e=this.getFloat(s);r=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===Bu.SPECULAR_STRENGTH)r=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture(s).r:Ni(1);else if(s===Bu.ROUGHNESS){const e=this.getFloat(s);r=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===Bu.METALNESS){const e=this.getFloat(s);r=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===Bu.EMISSIVE){const e=this.getColor(s);r=t.emissiveMap&&!0===t.emissiveMap.isTexture?e.mul(this.getTexture(s)):e}else if(s===Bu.NORMAL)r=t.normalMap?this.getTexture("normal").normalMap(this.getCache("normalScale","vec2")):t.bumpMap?this.getTexture("bump").r.bumpMap(this.getFloat("bumpScale")):Ru;else if(s===Bu.CLEARCOAT){const e=this.getFloat(s);r=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Bu.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);r=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Bu.CLEARCOAT_NORMAL)r=t.clearcoatNormalMap?this.getTexture(s).normalMap(this.getCache(s+"Scale","vec2")):Ru;else if(s===Bu.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));r=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===Bu.SHEEN_ROUGHNESS){const e=this.getFloat(s);r=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,r=r.clamp(.07,1)}else if(s===Bu.IRIDESCENCE_THICKNESS){const e=qa(1,"float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=qa(0,"float",t.iridescenceThicknessRange);r=e.sub(i).mul(this.getTexture(s).g).add(i)}else r=e}else{const t=this.getNodeType(e);r=this.getCache(s,t)}return r}}Bu.ALPHA_TEST="alphaTest",Bu.COLOR="color",Bu.OPACITY="opacity",Bu.SHININESS="shininess",Bu.SPECULAR_COLOR="specular",Bu.SPECULAR_STRENGTH="specularStrength",Bu.REFLECTIVITY="reflectivity",Bu.ROUGHNESS="roughness",Bu.METALNESS="metalness",Bu.NORMAL="normal",Bu.CLEARCOAT="clearcoat",Bu.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Bu.CLEARCOAT_NORMAL="clearcoatNormal",Bu.EMISSIVE="emissive",Bu.ROTATION="rotation",Bu.SHEEN="sheen",Bu.SHEEN_ROUGHNESS="sheenRoughness",Bu.IRIDESCENCE="iridescence",Bu.IRIDESCENCE_IOR="iridescenceIOR",Bu.IRIDESCENCE_THICKNESS="iridescenceThickness",Bu.LINE_SCALE="scale",Bu.LINE_DASH_SIZE="dashSize",Bu.LINE_GAP_SIZE="gapSize",Bu.LINE_WIDTH="linewidth",Bu.LINE_DASH_OFFSET="dashOffset",Bu.POINT_WIDTH="pointWidth";const Ou=pi(Bu,Bu.ALPHA_TEST),Lu=pi(Bu,Bu.COLOR),Uu=pi(Bu,Bu.SHININESS),Iu=pi(Bu,Bu.EMISSIVE),Du=pi(Bu,Bu.OPACITY),Pu=pi(Bu,Bu.SPECULAR_COLOR),Vu=pi(Bu,Bu.SPECULAR_STRENGTH),Gu=pi(Bu,Bu.REFLECTIVITY),ku=pi(Bu,Bu.ROUGHNESS),zu=pi(Bu,Bu.METALNESS),$u=pi(Bu,Bu.NORMAL),Hu=pi(Bu,Bu.CLEARCOAT),Wu=pi(Bu,Bu.CLEARCOAT_ROUGHNESS),ju=pi(Bu,Bu.CLEARCOAT_NORMAL),Xu=pi(Bu,Bu.ROTATION),qu=pi(Bu,Bu.SHEEN),Yu=pi(Bu,Bu.SHEEN_ROUGHNESS),Ku=pi(Bu,Bu.IRIDESCENCE),Qu=pi(Bu,Bu.IRIDESCENCE_IOR),Zu=pi(Bu,Bu.IRIDESCENCE_THICKNESS),Ju=pi(Bu,Bu.LINE_SCALE),el=pi(Bu,Bu.LINE_DASH_SIZE),tl=pi(Bu,Bu.LINE_GAP_SIZE),sl=pi(Bu,Bu.LINE_WIDTH),rl=pi(Bu,Bu.LINE_DASH_OFFSET),il=pi(Bu,Bu.POINT_WIDTH);yr("MaterialNode",Bu);class nl extends xr{constructor(e=nl.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`position-${this.scope}`}generate(e){const t=this.scope;let s=null;if(t===nl.GEOMETRY)s=nn("position","vec3");else if(t===nl.LOCAL)s=sn(ol);else if(t===nl.WORLD){const e=yu.mul(al);s=sn(e)}else if(t===nl.VIEW){const e=Tu.mul(al);s=sn(e)}else if(t===nl.VIEW_DIRECTION){const e=dl.negate();s=ko(sn(e))}else if(t===nl.WORLD_DIRECTION){const e=al.transformDirection(yu);s=ko(sn(e))}return s.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}nl.GEOMETRY="geometry",nl.LOCAL="local",nl.WORLD="world",nl.WORLD_DIRECTION="worldDirection",nl.VIEW="view",nl.VIEW_DIRECTION="viewDirection";const ol=pi(nl,nl.GEOMETRY),al=pi(nl,nl.LOCAL).temp("Position"),ul=pi(nl,nl.WORLD),ll=pi(nl,nl.WORLD_DIRECTION),dl=pi(nl,nl.VIEW),cl=pi(nl,nl.VIEW_DIRECTION);yr("PositionNode",nl);class hl extends Mr{constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return sn(e.context.mvp);const t=this.positionNode||al;return au.mul(Tu).mul(t)}}const pl=hi(hl);yr("ModelViewProjectionNode",hl);class gl extends Nr{constructor(e,t=null,s=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=r,this.usage=p,this.instanced=!1,this.attribute=null,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),s=this.value,r=e.getTypeLength(t),i=this.bufferStride||r,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new g(s,i),a=new m(o,r,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),r=e.getPropertyName(s);let i=null;if("vertex"===e.shaderStage)i=r;else{i=sn(this).build(e,t)}return i}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this}setInstanced(e){return this.instanced=e,this}}const ml=(e,t,s,r)=>li(new gl(e,t,s,r)),fl=(t,s,r,i)=>ml(t,s,r,i).setUsage(e),Tl=(e,t,s,r)=>ml(e,t,s,r).setInstanced(!0),xl=(e,t,s,r)=>fl(e,t,s,r).setInstanced(!0);Pr("toAttribute",(e=>ml(e.value))),yr("BufferAttributeNode",gl);class yl extends xr{constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null}setup(){let t=this.instanceMatrixNode;if(null===t){const s=this.instanceMesh.instanceMatrix,r=new f(s.array,16,1),i=s.usage===e?xl:Tl,n=[i(r,"vec4",16,0),i(r,"vec4",16,4),i(r,"vec4",16,8),i(r,"vec4",16,12)];t=ki(...n),this.instanceMatrixNode=t}const s=t.mul(al).xyz,r=Di(t[0].xyz,t[1].xyz,t[2].xyz),i=Au.div(wi(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2]))),n=r.mul(i).xyz;al.assign(s),Au.assign(n)}}const bl=hi(yl);yr("InstanceNode",yl);class Nl extends Ki{constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getInputType(){return"buffer"}}const _l=(e,t,s)=>li(new Nl(e,t,s));yr("BufferNode",Nl);class vl extends xr{constructor(e=vl.LOCAL){super(),this.scope=e}getHash(){return`tangent-${this.scope}`}getNodeType(){return this.scope===vl.GEOMETRY?"vec4":"vec3"}generate(e){const t=this.scope;let s=null;if(t===vl.GEOMETRY)s=nn("tangent","vec4");else if(t===vl.LOCAL)s=sn(Sl.xyz);else if(t===vl.VIEW){const e=Tu.mul(Al).xyz;s=ko(sn(e))}else if(t===vl.WORLD){const e=Rl.transformDirection(cu);s=ko(sn(e))}return s.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}vl.GEOMETRY="geometry",vl.LOCAL="local",vl.VIEW="view",vl.WORLD="world";const Sl=pi(vl,vl.GEOMETRY),Al=pi(vl,vl.LOCAL),Rl=pi(vl,vl.VIEW),El=pi(vl,vl.WORLD),Cl=bn(Rl,"TransformedTangentView"),wl=ko(Cl.transformDirection(cu));yr("TangentNode",vl);class Ml extends xr{constructor(e){super("void"),this.skinnedMesh=e,this.updateType=rr.OBJECT,this.skinIndexNode=nn("skinIndex","uvec4"),this.skinWeightNode=nn("skinWeight","vec4"),this.bindMatrixNode=Qi(e.bindMatrix,"mat4"),this.bindMatrixInverseNode=Qi(e.bindMatrixInverse,"mat4"),this.boneMatricesNode=_l(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)}setup(e){const{skinIndexNode:t,skinWeightNode:s,bindMatrixNode:r,bindMatrixInverseNode:i,boneMatricesNode:n}=this,o=n.element(t.x),a=n.element(t.y),u=n.element(t.z),l=n.element(t.w),d=r.mul(al),c=uo(o.mul(s.x).mul(d),a.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d)),h=i.mul(c).xyz;let p=uo(s.x.mul(o),s.y.mul(a),s.z.mul(u),s.w.mul(l));p=i.mul(p).mul(r);const g=p.transformDirection(Au).xyz;al.assign(h),Au.assign(g),e.hasGeometryAttribute("tangent")&&Al.assign(g)}generate(e,t){if("void"!==t)return al.build(e,t)}update(){this.skinnedMesh.skeleton.update()}}const Fl=hi(Ml);yr("SkinningNode",Ml);const Bl=new WeakMap,Ol=new o,Ll=mi((({bufferMap:e,influence:t,stride:s,width:r,depth:i,offset:n})=>{const o=_i(fn).mul(s).add(n),a=o.div(r),u=o.sub(a.mul(r));return Wa(e,Ri(u,a)).depth(i).mul(t)}));class Ul extends xr{constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Qi(1),this.updateType=rr.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,r=void 0!==t.morphAttributes.normal,n=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,o=void 0!==n?n.length:0,{texture:a,stride:u,size:l}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,r=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,o=void 0!==n?n.length:0;let a=Bl.get(e);if(void 0===a||a.count!==o){void 0!==a&&a.texture.dispose();const n=e.morphAttributes.position||[],u=e.morphAttributes.normal||[],l=e.morphAttributes.color||[];let d=0;!0===t&&(d=1),!0===s&&(d=2),!0===r&&(d=3);let c=e.attributes.position.count*d,h=1;const p=4096;c>p&&(h=Math.ceil(c/p),c=p);const g=new Float32Array(c*h*4*o),m=new T(g,c,h,o);m.type=x,m.needsUpdate=!0;const f=4*d;for(let e=0;ee+t),0)}}const Il=hi(Ul);yr("MorphNode",Ul);class Dl extends xr{constructor(){super("vec3")}getHash(){return"reflectVector"}setup(){return cl.negate().reflect(Cu).transformDirection(cu)}}const Pl=pi(Dl);yr("ReflectVectorNode",Dl);class Vl extends $a{constructor(e,t=null,s=null){super(e,t,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){return Pl}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==y&&s.isRenderTargetTexture?t:wi(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const Gl=hi(Vl);Pr("cubeTexture",Gl),yr("CubeTextureNode",Vl);class kl extends xr{constructor(){super("vec3")}generate(){}}yr("LightingNode",kl);let zl=null;class $l extends kl{constructor(e=null){super(),this.updateType=rr.FRAME,this.light=e,this.rtt=null,this.shadowNode=null,this.color=new r,this._defaultColorNode=Qi(this.color),this.colorNode=this._defaultColorNode,this.isAnalyticLightNode=!0}getCacheKey(){return super.getCacheKey()+"-"+this.light.id+"-"+(this.light.castShadow?"1":"0")}getHash(){return this.light.uuid}setupShadow(e){let t=this.shadowNode;if(null===t){null===zl&&(zl=e.createNodeMaterial("MeshBasicNodeMaterial"));const s=this.light.shadow,r=e.getRenderTarget(s.mapSize.width,s.mapSize.height),i=new b;i.minFilter=N,i.magFilter=N,i.image.width=s.mapSize.width,i.image.height=s.mapSize.height,i.compareFunction=_,r.depthTexture=i,s.camera.updateProjectionMatrix();const n=qa("bias","float",s),o=qa("normalBias","float",s);let a=Qi(s.matrix).mul(ul.add(Eu.mul(o)));a=a.xyz.div(a.w);const u=a.x.greaterThanEqual(0).and(a.x.lessThanEqual(1)).and(a.y.greaterThanEqual(0)).and(a.y.lessThanEqual(1)).and(a.z.lessThanEqual(1));let l=a.z.add(n);e.renderer.coordinateSystem===y&&(l=l.mul(2).sub(1)),a=wi(a.x,a.y.oneMinus(),l);const d=(e,t,s)=>Ha(e,t).compare(s);t=d(i,a.xy,a.z),this.rtt=r,this.colorNode=this.colorNode.mul(u.mix(1,t)),this.shadowNode=t,this.updateBeforeType=rr.RENDER}}setup(e){this.light.castShadow?this.setupShadow(e):null!==this.shadowNode&&this.disposeShadow()}updateShadow(e){const{rtt:t,light:s}=this,{renderer:r,scene:i}=e,n=i.overrideMaterial;i.overrideMaterial=zl,t.setSize(s.shadow.mapSize.width,s.shadow.mapSize.height),s.shadow.updateMatrices(s);const o=r.getRenderTarget(),a=r.getRenderObjectFunction();r.setRenderObjectFunction(((e,...t)=>{!0===e.castShadow&&r.renderObject(e,...t)})),r.setRenderTarget(t),r.render(i,s.shadow.camera),r.setRenderTarget(o),r.setRenderObjectFunction(a),i.overrideMaterial=n}disposeShadow(){this.rtt.dispose(),this.shadowNode=null,this.rtt=null,this.colorNode=this._defaultColorNode}updateBefore(e){const{light:t}=this;t.castShadow&&this.updateShadow(e)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}yr("AnalyticLightNode",$l);const Hl=new WeakMap;class Wl extends xr{constructor(e=[]){super("vec3"),this.totalDiffuseNode=wi().temp("totalDiffuse"),this.totalSpecularNode=wi().temp("totalSpecular"),this.outgoingLightNode=wi().temp("outgoingLight"),this.lightNodes=e,this._hash=null}get hasLight(){return this.lightNodes.length>0}getHash(){if(null===this._hash){const e=[];for(const t of this.lightNodes)e.push(t.getHash());this._hash="lights-"+e.join(",")}return this._hash}setup(e){const t=e.context,s=t.lightingModel;let r=this.outgoingLightNode;if(s){const{lightNodes:i,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=r;const a=e.addStack();s.start(t,a,e);for(const t of i)t.build(e);s.indirectDiffuse(t,a,e),s.indirectSpecular(t,a,e),s.ambientOcclusion(t,a,e);const{backdrop:u,backdropAlpha:l}=t,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=t.reflectedLight;let g=d.add(h);null!==u&&(g=wi(null!==l?l.mix(g,u):u)),n.assign(g),o.assign(c.add(p)),r.assign(n.add(o)),s.finish(t,a,e),r=r.bypass(e.removeStack())}return r}_getLightNodeById(e){for(const t of this.lightNodes)if(t.isAnalyticLightNode&&t.light.id===e)return t;return null}fromLights(e=[]){const t=[];e=(e=>e.sort(((e,t)=>e.id-t.id)))(e);for(const s of e){let e=this._getLightNodeById(s.id);if(null===e){const t=s.constructor,r=Hl.has(t)?Hl.get(t):$l;e=li(new r(s))}t.push(e)}return this.lightNodes=t,this._hash=null,this}}const jl=e=>li((new Wl).fromLights(e)),Xl=hi(Wl);function ql(e,t){if(!Hl.has(e)){if("function"!=typeof e)throw new Error(`Light ${e.name} is not a class`);if("function"!=typeof t||!t.type)throw new Error(`Light node ${t.type} is not a class`);Hl.set(e,t)}}class Yl extends kl{constructor(e=null){super(),this.aoNode=e}setup(e){const t=this.aoNode.x.sub(1).mul(1).add(1);e.context.ambientOcclusion.mulAssign(t)}}yr("AONode",Yl);class Kl extends hn{constructor(e,t=null,s=null,r=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=r,this._context=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:wi().temp("directDiffuse"),directSpecular:wi().temp("directSpecular"),indirectDiffuse:wi().temp("indirectDiffuse"),indirectSpecular:wi().temp("indirectSpecular")};return{radiance:wi().temp("radiance"),irradiance:wi().temp("irradiance"),iblIrradiance:wi().temp("iblIrradiance"),ambientOcclusion:Ni(1).temp("ambientOcclusion"),reflectedLight:s,backdrop:e,backdropAlpha:t}}setup(e){return this.context=this._context||(this._context=this.getContext()),this.context.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Ql=hi(Kl);Pr("lightingContext",Ql),yr("LightingContextNode",Kl);class Zl extends Mr{constructor(e=ll){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.negate().clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Ai(t,s)}}const Jl=hi(Zl);yr("EquirectUVNode",Zl);class ed extends xr{constructor(e,t=null){super("float"),this.textureNode=e,this.roughnessNode=t}setup(){const{textureNode:e,roughnessNode:t}=this,s=za(e),r=t.mul(t).mul(Math.PI).div(t.add(1));return s.add(r.log2()).clamp(0,s)}}const td=hi(ed);yr("SpecularMIPLevelNode",ed);const sd=new WeakMap;class rd extends kl{constructor(e=null){super(),this.envNode=e}setup(e){let t=this.envNode;if(t.isTextureNode&&!0!==t.value.isCubeTexture){let s=sd.get(t.value);if(void 0===s){const r=t.value,i=e.renderer,n=e.getCubeRenderTarget(512).fromEquirectangularTexture(i,r);s=Gl(n.texture),sd.set(t.value,s)}t=s}const s=qa("envMapIntensity","float",e.material),r=pn(t,id(Fn,Cu)).mul(s),i=pn(t,nd(wu)).mul(Math.PI).mul(s),n=cn(r);e.context.radiance.addAssign(n),e.context.iblIrradiance.addAssign(i);const o=e.context.lightingModel.clearcoatRadiance;if(o){const e=pn(t,id(Ln,Mu)).mul(s),r=cn(e);o.addAssign(r)}}}const id=(e,t)=>{let s=null,r=null;return{getUV:i=>{let n=null;return null===s&&(s=cl.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(cu)),i.isCubeTextureNode?n=s:i.isTextureNode&&(null===r&&(r=Jl(s)),n=r),n},getTextureLevel:()=>e,getTextureLevelAlgorithm:(e,t)=>td(e,t)}},nd=e=>{let t=null;return{getUV:s=>{let r=null;return s.isCubeTextureNode?r=e:s.isTextureNode&&(null===t&&(t=Jl(e),t=Ai(t.x,t.y.oneMinus())),r=t),r},getTextureLevel:e=>za(e)}};let od,ad;yr("EnvironmentNode",rd);class ud extends xr{constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===ud.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=rr.NONE;return this.scope!==ud.RESOLUTION&&this.scope!==ud.VIEWPORT||(e=rr.FRAME),this.updateType=e,e}update({renderer:e}){this.scope===ud.VIEWPORT?e.getViewport(ad):e.getDrawingBufferSize(od)}setup(){const e=this.scope;if(e===ud.COORDINATE)return;let t=null;if(e===ud.RESOLUTION)t=Qi(od||(od=new i));else if(e===ud.VIEWPORT)t=Qi(ad||(ad=new o));else{t=ld.div(dd);let s=t.x,r=t.y;/bottom/i.test(e)&&(r=r.oneMinus()),/right/i.test(e)&&(s=s.oneMinus()),t=Ai(s,r)}return t}generate(e){if(this.scope===ud.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(dd).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}ud.COORDINATE="coordinate",ud.RESOLUTION="resolution",ud.VIEWPORT="viewport",ud.TOP_LEFT="topLeft",ud.BOTTOM_LEFT="bottomLeft",ud.TOP_RIGHT="topRight",ud.BOTTOM_RIGHT="bottomRight";const ld=pi(ud,ud.COORDINATE),dd=pi(ud,ud.RESOLUTION),cd=pi(ud,ud.VIEWPORT),hd=pi(ud,ud.TOP_LEFT),pd=pi(ud,ud.BOTTOM_LEFT),gd=pi(ud,ud.TOP_RIGHT),md=pi(ud,ud.BOTTOM_RIGHT);yr("ViewportNode",ud);const fd=new i;class Td extends $a{constructor(e=hd,t=null,s=null){null===s&&((s=new v).minFilter=S),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=rr.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(fd);const s=this.value;s.image.width===fd.width&&s.image.height===fd.height||(s.image.width=fd.width,s.image.height=fd.height,s.needsUpdate=!0);const r=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=r}clone(){return new this.constructor(this.uvNode,this.levelNode,this.value)}}const xd=hi(Td),yd=hi(Td,null,null,{generateMipmaps:!0});Pr("viewportTexture",xd),Pr("viewportMipTexture",yd),yr("ViewportTextureNode",Td);let bd=null;class Nd extends Td{constructor(e=hd,t=null){null===bd&&(bd=new b,bd.minFilter=A,bd.type=R,bd.format=E),super(e,t,bd)}}const _d=hi(Nd);Pr("viewportDepthTexture",_d),yr("ViewportDepthTextureNode",Nd);class vd extends xr{constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===vd.DEPTH_PIXEL?e.getFragDepth():super.generate(e)}setup(){const{scope:e}=this;let t=null;if(e===vd.DEPTH)t=Sd(dl.z,uu,lu);else if(e===vd.DEPTH_TEXTURE){const e=this.valueNode||_d(),s=Ed(e,uu,lu);t=Sd(s,uu,lu)}else e===vd.DEPTH_PIXEL&&null!==this.valueNode&&(t=Cd().assign(this.valueNode));return t}}const Sd=(e,t,s)=>e.add(t).div(t.sub(s)),Ad=(e,t,s)=>t.sub(s).mul(e).sub(t),Rd=(e,t,s)=>t.add(e).mul(s).div(t.sub(s).mul(e)),Ed=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s));vd.DEPTH="depth",vd.DEPTH_TEXTURE="depthTexture",vd.DEPTH_PIXEL="depthPixel";const Cd=hi(vd,vd.DEPTH_PIXEL),wd=pi(vd,vd.DEPTH),Md=hi(vd,vd.DEPTH_TEXTURE),Fd=pi(vd,vd.DEPTH_PIXEL);Fd.assign=e=>Cd(e),yr("ViewportDepthNode",vd);const Bd=new Map;class Od extends C{constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!0,this.normals=!0,this.colorSpaced=!0,this.lightsNode=null,this.envNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.positionNode=null,this.depthNode=null,this.outputNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+lr(this)}build(e){this.setup(e)}setup(e){let t;if(e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),e.addFlow("vertex",e.removeStack()),e.addStack(),null===this.fragmentNode){!0===this.depthWrite&&this.setupDepth(e),!0===this.normals&&this.setupNormal(e),this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);t=this.setupOutput(e,Oi(s,Mn.a)),zn.assign(t),null!==this.outputNode&&(t=this.outputNode)}else t=this.setupOutput(e,this.fragmentNode);e.stack.outputNode=t,e.addFlow("fragment",e.removeStack())}setupDepth(e){const{renderer:t}=e;let s=this.depthNode;if(null===s&&!0===t.logarithmicDepthBuffer){s=pl().w.add(1).log2().mul(du).mul(.5)}null!==s&&Fd.assign(s).append()}setupPosition(e){const{object:t}=e,s=t.geometry;e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Il(t).append(),!0===t.isSkinnedMesh&&Fl(t).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&!0===e.isAvailable("instance")&&bl(t).append(),null!==this.positionNode&&al.assign(this.positionNode);const r=pl();return e.context.vertex=e.removeStack(),e.context.mvp=r,r}setupDiffuseColor({geometry:e}){let t=this.colorNode?Oi(this.colorNode):Lu;!0===this.vertexColors&&e.hasAttribute("color")&&(t=Oi(t.xyz.mul(nn("color","vec3")),t.a)),Mn.assign(t);const s=this.opacityNode?Ni(this.opacityNode):Du;if(Mn.a.assign(Mn.a.mul(s)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?Ni(this.alphaTestNode):Ou;Mn.a.lessThanEqual(e).discard()}}setupVariants(){}setupNormal(){if(!0===this.flatShading){const e=dl.dFdx().cross(dl.dFdy()).normalize();Cu.assign(e)}else{const e=this.normalNode?wi(this.normalNode):$u;Cu.assign(e)}}getEnvNode(e){let t=null;return this.envNode?t=this.envNode:this.envMap?t=this.envMap.isCubeTexture?Gl(this.envMap):Ha(this.envMap):e.environmentNode&&(t=e.environmentNode),t}setupLights(e){const t=this.getEnvNode(e),s=[];t&&s.push(new rd(t)),e.material.aoMap&&s.push(new Yl(Ha(e.material.aoMap)));let r=this.lightsNode||e.lightsNode;return s.length>0&&(r=Xl([...r.lightNodes,...s])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:r,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=Mn.rgb;if(n&&!1!==n.hasLight){const t=this.setupLightingModel(e);o=Ql(n,t,s,r)}else null!==s&&(o=wi(null!==r?va(o,s,r):s));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(o=o.add(wi(i||Iu))),o}setupOutput(e,t){const s=e.renderer,r=e.toneMappingNode;if(!0===this.toneMapped&&r&&(t=Oi(r.context({color:t.rgb}),t.a)),!0===this.fog){const s=e.fogNode;s&&(t=Oi(s.mixAssign(t.rgb),t.a))}if(!0===this.colorSpaced){const e=s.currentColorSpace;e!==c&&e!==w&&(t=t.linearToColorSpace(e))}return t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.clone()))}Object.assign(this.defines,e.defines);const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const s=M.prototype.toJSON.call(this,e),r=dr(this);s.inputNodes={};for(const{property:t,childNode:i}of r)s.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const s in e){const r=e[s];delete r.metadata,t.push(r)}return t}if(t){const t=i(e.textures),r=i(e.images),n=i(e.nodes);t.length>0&&(s.textures=t),r.length>0&&(s.images=r),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.positionNode=e.positionNode,this.depthNode=e.depthNode,this.outputNode=e.outputNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}static fromMaterial(e){if(!0===e.isNodeMaterial)return e;const t=Ud(e.type.replace("Material","NodeMaterial"));if(void 0===t)throw new Error(`NodeMaterial: Material "${e.type}" is not compatible.`);for(const s in e)t[s]=e[s];return t}}function Ld(e,t){if("function"!=typeof t||!e)throw new Error(`Node material ${e} is not a class`);Bd.has(e)||(Bd.set(e,t),t.type=e)}function Ud(e){const t=Bd.get(e);if(void 0!==t)return new t}Ld("NodeMaterial",Od);class Id{constructor(e,t=null){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 Dd extends Id{constructor(e,t=0){super(e,t),this.isFloatUniform=!0,this.boundary=4,this.itemSize=1}}class Pd extends Id{constructor(e,t=new i){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Vd extends Id{constructor(e,t=new n){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Gd extends Id{constructor(e,t=new o){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class kd extends Id{constructor(e,t=new r){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class zd extends Id{constructor(e,t=new a){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class $d extends Id{constructor(e,t=new u){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Hd extends Dd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Wd extends Pd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class jd extends Vd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Xd extends Gd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class qd extends kd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Yd extends zd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Kd extends $d{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Qd extends xr{constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}generate(e){const t=this.getNodeType(e),s={tempWrite:!1},{ifNode:r,elseNode:i}=this,n="void"!==r.getNodeType(e)||i&&"void"!==i.getNodeType(e),o=n?Cn(t).build(e):"",a=pn(this.condNode).build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${a} ) {\n\n`).addFlowTab();let u=pn(this.ifNode,s).build(e,t);if(u=n?o+" = "+u+";":u,e.removeFlowTab().addFlowCode(e.tab+"\t"+u+"\n\n"+e.tab+"}"),null!==i){e.addFlowCode(" else {\n\n").addFlowTab();let r=pn(i,s).build(e,t);r=o?o+" = "+r+";":r,e.removeFlowTab().addFlowCode(e.tab+"\t"+r+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return o}}const Zd=hi(Qd);Pr("cond",Zd),yr("CondNode",Qd);class Jd extends xr{constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}if(e,t){const s=new ui(t);return this._currentCond=Zd(e,s),this.add(this._currentCond)}elseif(e,t){const s=new ui(t),r=Zd(e,s);return this._currentCond.elseNode=r,this._currentCond=r,this}else(e){return this._currentCond.elseNode=new ui(e),this}build(e,...t){const s=Ti();fi(this);for(const t of this.nodes)t.build(e,"void");return fi(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}}const ec=hi(Jd);yr("StackNode",Jd);class tc extends F{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,r=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 B(5,5,5),n=Jl(ll),o=Ud("MeshBasicNodeMaterial");o.colorNode=Ha(t,n,0),o.side=O,o.blending=L;const a=new U(i,o),u=new I;u.add(a),t.minFilter===S&&(t.minFilter=D);return new P(1,10,this).update(e,u),t.minFilter=s,t.currentGenerateMipmaps=r,a.geometry.dispose(),a.material.dispose(),this}}const sc=new Us,rc=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),ic=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),nc=e=>(e=Number(e))+(e%1?"":".0");class oc{constructor(e,t,s,r=null,i=null){this.object=e,this.material=i||e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=r,this.nodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.hashNodes={},this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.toneMappingNode=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.bindingsOffset={vertex:0,fragment:0,compute:0},this.bindingsArray=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=ec(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={keywords:new Rn,material:this.material},this.cache=new ln,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getRenderTarget(e,t,s){return new V(e,t,s)}getCubeRenderTarget(e,t){return new tc(e,t)}includes(e){return this.nodes.includes(e)}_getSharedBindings(e){const t=[];for(const s of e)if(!0===s.shared){const e=s.getNodes();let r=sc.get(e);void 0===r&&(sc.set(e,s),r=s),t.push(r)}else t.push(s);return t}getBindings(){let e=this.bindingsArray;if(null===e){const t=this.bindings;this.bindingsArray=e=this._getSharedBindings(null!==this.material?[...t.vertex,...t.fragment]:t.compute)}return e}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}buildUpdateNodes(){for(const e of this.nodes){const t=e.getUpdateType(),s=e.getUpdateBeforeType();t!==rr.NONE&&this.updateNodes.push(e.getSelf()),s!==rr.NONE&&this.updateBeforeNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}setCache(e){this.cache=e}getCache(){return this.cache}isAvailable(){return!1}getVertexIndex(){}getInstanceIndex(){}getFrontFacing(){}getFragCoord(){}isFlipY(){return!1}generateTexture(){}generateTextureLod(){}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new r:"vec2"===e?t=new i:"vec3"===e?t=new n:"vec4"===e&&(t=new o)),"float"===e)return nc(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${nc(t.r)}, ${nc(t.g)}, ${nc(t.b)} )`;const s=this.getTypeLength(e),a=this.getComponentType(e),u=e=>this.generateConst(a,e);if(2===s)return`${this.getType(e)}( ${u(t.x)}, ${u(t.y)} )`;if(3===s)return`${this.getType(e)}( ${u(t.x)}, ${u(t.y)}, ${u(t.z)} )`;if(4===s)return`${this.getType(e)}( ${u(t.x)}, ${u(t.y)}, ${u(t.z)}, ${u(t.w)} )`;if(s>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(u).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}generateMethod(e){return e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const s=this.attributes;for(const t of s)if(t.name===e)return t;const r=new Nn(e,t);return s.push(r),r}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"texture"===e||"cubeTexture"===e}needsColorSpaceToLinear(){return!1}getTextureEncodingFromMap(e){return this.getTextureColorSpaceFromMap(e)===h?G:k}getTextureColorSpaceFromMap(e){let t;return t=e&&e.isTexture?e.colorSpace:e&&e.isWebGLRenderTarget?e.texture.colorSpace:w,t}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?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;const s=rc.get(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return ic.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,r=e.itemSize,i=e.normalized;let n;return e instanceof z||!0===i||(n=this.getTypeFromArray(s)),this.getTypeFromLength(r,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/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=ec(this.stack),this.stacks.push(Ti()||this.stack),fi(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,fi(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let r=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getNodeData(e);return void 0===r&&(r={},s.setNodeData(e,r)),void 0===r[t]&&(r[t]={}),r[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let r=s.bufferAttribute;if(void 0===r){const i=this.uniforms.index++;r=new Nn("nodeAttribute"+i,t,e),this.bufferAttributes.push(r),s.bufferAttribute=r}return r}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const r=this.structs.index++;e.name=`StructType${r}`,this.structs[t].push(e),s.structType=e}return e}getUniformFromNode(e,t,s=this.shaderStage,r=null){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.uniform;if(void 0===n){const o=this.uniforms.index++;n=new _n(r||"nodeUniform"+o,t,e),this.uniforms[s].push(n),i.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),r=this.shaderStage){const i=this.getDataFromNode(e,r);let n=i.variable;if(void 0===n){const e=this.vars[r]||(this.vars[r]=[]);null===t&&(t="nodeVar"+e.length),n=new vn(t,s),e.push(n),i.variable=n}return n}getVaryingFromNode(e,t=null,s=e.getNodeType(this)){const r=this.getDataFromNode(e,"any");let i=r.varying;if(void 0===i){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),i=new Sn(t,s),e.push(i),r.varying=i}return i}getCodeFromNode(e,t,s=this.shaderStage){const r=this.getDataFromNode(e);let i=r.code;if(void 0===i){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;i=new An("nodeCode"+n,t),e.push(i),r.code=i}return i}addLineFlowCode(e){return""===e||(e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}buildFunctionNode(e){const t=new Jn,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout;let s;if(e.isArrayInput){s=[];for(const e of t.inputs)s.push(new jn(e.type,e.name))}else{s={};for(const e of t.inputs)s[e.name]=new jn(e.type,e.name)}e.layout=null;const r=e.call(s),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowStagesNode(e,t=null){const s=this.flow,r=this.vars,i=this.buildStage,n={code:""};this.flow=n,this.vars={};for(const s of or)this.setBuildStage(s),n.result=e.build(this,t);return n.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=r,this.setBuildStage(i),n}getFunctionOperator(){return null}flowChildNode(e,t=null){const s=this.flow,r={code:""};return this.flow=r,r.result=e.build(this,t),this.flow=s,r}flowNodeFromShaderStage(e,t,s=null,r=null){const i=this.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==r&&(n.code+=`${this.tab+r} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(i),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){}getVaryings(){}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){}build(e=!0){const{object:t,material:s}=this;e&&(null!==s?Od.fromMaterial(s).build(this):this.addFlow("compute",t));for(const e of or){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of ar){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t)return new Hd(e);if("vec2"===t)return new Wd(e);if("vec3"===t)return new jd(e);if("vec4"===t)return new Xd(e);if("color"===t)return new qd(e);if("mat3"===t)return new Yd(e);if("mat4"===t)return new Kd(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e){return Ud(e)}getPrimitiveType(e){let t;return t="i"===e[0]?"int":"u"===e[0]?"uint":"float",t}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const r=this.getTypeLength(t),i=this.getTypeLength(s);return r>4||i>4||0===i?e:r===i?`${this.getType(s)}( ${e} )`:r>i?this.format(`${e}.${"xyz".slice(0,i)}`,this.getTypeFromLength(i,this.getComponentType(t)),s):4===i&&r>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===r?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===r&&i>1&&t[0]!==s[0]&&(e=`${this.getType(this.getPrimitiveType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${$} - NodeMaterial System\n`}}class ac{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return void 0===s&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===rr.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(e)!==this.frameId&&(t.set(e,this.frameId),e.updateBefore(this))}else if(t===rr.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(e)!==this.renderId&&(t.set(e,this.renderId),e.updateBefore(this))}else t===rr.OBJECT&&e.updateBefore(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===rr.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(e)!==this.frameId&&(t.set(e,this.frameId),e.update(this))}else if(t===rr.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(e)!==this.renderId&&(t.set(e,this.renderId),e.update(this))}else t===rr.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 uc{constructor(e,t,s=null,r="",i=!1){this.type=e,this.name=t,this.count=s,this.qualifier=r,this.isConst=i}}uc.isNodeFunctionInput=!0;class lc extends xr{constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}yr("StructTypeNode",lc);class dc extends xr{constructor(...e){super(),this.isOutputStructNode=!0,this.members=e}setup(e){super.setup(e);const t=this.members,s=[];for(let r=0;rfc(e).append();Pr("discard",Tc),yr("DiscardNode",mc);class xc extends xr{constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let s=this._candidateFnCall;if(null===s){let r=null,i=-1;for(const s of this.functionNodes){const n=s.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const o=n.inputs;if(t.length===o.length){let n=0;for(let s=0;si&&(r=s,i=n)}}this._candidateFnCall=s=r(...t)}return s}}const yc=hi(xc),bc=e=>(...t)=>yc(e,...t);yr("FunctionOverloadingNode",xc);class Nc extends xr{constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;eNumber(n)?">=":"<"));const d={start:i,end:n,condition:u},c=d.start,h=d.end;let p="",g="",m="";l||(l="int"===a?u.includes("<")?"++":"--":u.includes("<")?"+= 1":"-= 1"),p+=e.getVar(a,o)+" = "+c,g+=o+" "+u+" "+h,m+=o+" "+l;const f=`for ( ${p}; ${g}; ${m} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\n\n").addFlowTab()}const i=pn(r,{tempWrite:!1}).build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,s=this.params.length-1;tli(new Nc(ci(e,"int"))).append();Pr("loop",((e,...t)=>an(e,_c(...t)))),yr("LoopNode",Nc);class vc extends Mr{constructor(){super("vec2")}setup(){const e=wi(cl.z,0,cl.x.negate()).normalize(),t=cl.cross(e);return Ai(e.dot(Cu),t.dot(Cu)).mul(.495).add(.5)}}const Sc=pi(vc);yr("MatcapUVNode",vc);class Ac extends Ki{constructor(e=Ac.LOCAL,t=1,s=0){super(s),this.scope=e,this.scale=t,this.updateType=rr.FRAME}update(e){const t=this.scope,s=this.scale;t===Ac.LOCAL?this.value+=e.deltaTime*s:t===Ac.DELTA?this.value=e.deltaTime*s:t===Ac.FRAME?this.value=e.frameId:this.value=e.time*s}serialize(e){super.serialize(e),e.scope=this.scope,e.scale=this.scale}deserialize(e){super.deserialize(e),this.scope=e.scope,this.scale=e.scale}}Ac.LOCAL="local",Ac.GLOBAL="global",Ac.DELTA="delta",Ac.FRAME="frame";const Rc=(e,t=0)=>li(new Ac(Ac.LOCAL,e,t)),Ec=(e,t=0)=>li(new Ac(Ac.GLOBAL,e,t)),Cc=(e,t=0)=>li(new Ac(Ac.DELTA,e,t)),wc=pi(Ac,Ac.FRAME).uint();yr("TimerNode",Ac);class Mc extends xr{constructor(e=Mc.SINE,t=Rc()){super(),this.method=e,this.timeNode=t}getNodeType(e){return this.timeNode.getNodeType(e)}setup(){const e=this.method,t=li(this.timeNode);let s=null;return e===Mc.SINE?s=t.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5):e===Mc.SQUARE?s=t.fract().round():e===Mc.TRIANGLE?s=t.add(.5).fract().mul(2).sub(1).abs():e===Mc.SAWTOOTH&&(s=t.fract()),s}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Mc.SINE="sine",Mc.SQUARE="square",Mc.TRIANGLE="triangle",Mc.SAWTOOTH="sawtooth";const Fc=hi(Mc,Mc.SINE),Bc=hi(Mc,Mc.SQUARE),Oc=hi(Mc,Mc.TRIANGLE),Lc=hi(Mc,Mc.SAWTOOTH);yr("OscNode",Mc);class Uc extends Mr{constructor(e,t){super(),this.scope=e,this.node=t}getNodeType(e){return this.node.getNodeType(e)}setup(){const{scope:e,node:t}=this;let s=null;return e===Uc.DIRECTION_TO_COLOR?s=t.mul(.5).add(.5):e===Uc.COLOR_TO_DIRECTION&&(s=t.mul(2).sub(1)),s}}Uc.DIRECTION_TO_COLOR="directionToColor",Uc.COLOR_TO_DIRECTION="colorToDirection";const Ic=hi(Uc,Uc.DIRECTION_TO_COLOR),Dc=hi(Uc,Uc.COLOR_TO_DIRECTION);Pr("directionToColor",Ic),Pr("colorToDirection",Dc),yr("PackingNode",Uc);class Pc extends xr{constructor(e,t,s,r=Ni(0),i=Ni(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=r,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:r,outHighNode:i,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(i.sub(r)).add(r)}}const Vc=hi(Pc,null,null,{doClamp:!1}),Gc=hi(Pc);Pr("remap",Vc),Pr("remapClamp",Gc),yr("RemapNode",Pc);class kc extends Mr{constructor(e,t,s=Ai(.5)){super("vec2"),this.uvNode=e,this.rotationNode=t,this.centerNode=s}setup(){const{uvNode:e,rotationNode:t,centerNode:s}=this,r=t.cos(),i=t.sin(),n=e.sub(s);return Ai(Ai(r,i).dot(n),Ai(i.negate(),r).dot(n)).add(s)}}const zc=hi(kc);Pr("rotateUV",zc),yr("RotateUVNode",kc);class $c extends xr{constructor(e,t=io(),s=Ni(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:r,height:i}=s,n=e.mod(r.mul(i)).floor(),o=n.mod(r),a=i.sub(n.add(1).div(r).ceil()),u=s.reciprocal(),l=Ai(o,a);return t.add(l).mul(u)}}const Hc=hi($c);yr("SpriteSheetUVNode",$c);class Wc extends xr{constructor(e,t=null,s=null,r=Ni(1),i=al,n=Au){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=s,this.scaleNode=r,this.positionNode=i,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:s,scaleNode:r,positionNode:i,normalNode:n}=this;let o=n.abs().normalize();o=o.div(o.dot(wi(1)));const a=i.yz.mul(r),u=i.zx.mul(r),l=i.xy.mul(r),d=e.value,c=null!==t?t.value:d,h=null!==s?s.value:d,p=Ha(d,a).mul(o.x),g=Ha(c,u).mul(o.y),m=Ha(h,l).mul(o.z);return uo(p,g,m)}}const jc=hi(Wc),Xc=(...e)=>jc(...e);Pr("triplanarTexture",Xc),yr("TriplanarTexturesNode",Wc);class qc extends xr{constructor(e=qc.LOCAL){super("vec3"),this.scope=e}getHash(){return`bitangent-${this.scope}`}generate(e){const t=this.scope;let s;t===qc.GEOMETRY?s=Su.cross(Sl):t===qc.LOCAL?s=Au.cross(Al):t===qc.VIEW?s=Ru.cross(Rl):t===qc.WORLD&&(s=Eu.cross(El));const r=s.mul(Sl.w).xyz;return ko(sn(r)).build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}qc.GEOMETRY="geometry",qc.LOCAL="local",qc.VIEW="view",qc.WORLD="world";const Yc=pi(qc,qc.GEOMETRY),Kc=pi(qc,qc.LOCAL),Qc=pi(qc,qc.VIEW),Zc=pi(qc,qc.WORLD),Jc=ko(Cu.cross(Cl).mul(Sl.w)),eh=ko(Jc.transformDirection(cu));yr("BitangentNode",qc);class th extends rn{constructor(e=0){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 s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new o(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const sh=(...e)=>li(new th(...e));yr("VertexColorNode",th);const rh=1/6,ih=e=>co(rh,co(e,co(e,e.negate().add(3)).sub(3)).add(1)),nh=e=>co(rh,co(e,co(e,co(3,e).sub(6))).add(4)),oh=e=>co(rh,co(e,co(e,co(-3,e).add(3)).add(3)).add(1)),ah=e=>co(rh,Ta(e,3)),uh=e=>ih(e).add(nh(e)),lh=e=>oh(e).add(ah(e)),dh=e=>uo(-1,nh(e).div(ih(e).add(nh(e)))),ch=e=>uo(1,ah(e).div(oh(e).add(ah(e)))),hh=(e,t,s)=>{const r=e.uvNode,i=co(r,t.zw).add(.5),n=Vo(i),o=zo(i),a=uh(o.x),u=lh(o.x),l=dh(o.x),d=ch(o.x),c=dh(o.y),h=ch(o.y),p=Ai(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Ai(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=Ai(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Ai(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),T=uh(o.y).mul(uo(a.mul(e.uv(p).level(s)),u.mul(e.uv(g).level(s)))),x=lh(o.y).mul(uo(a.mul(e.uv(m).level(s)),u.mul(e.uv(f).level(s))));return T.add(x)};class ph extends Mr{constructor(e,t=Ni(3)){super("vec4"),this.textureNode=e,this.blurNode=t}setup(){return((e,t)=>{const s=Ai(e.size(_i(t))),r=Ai(e.size(_i(t.add(1)))),i=ho(1,s),n=ho(1,r),o=hh(e,Oi(i,s),Vo(t)),a=hh(e,Oi(n,r),Go(t));return zo(t).mix(o,a)})(this.textureNode,this.blurNode)}}const gh=hi(ph);Pr("bicubic",gh),yr("TextureBicubicNode",ph);class mh extends xr{constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const fh=pi(mh);yr("PointUVNode",mh);class Th extends xr{constructor(e=Th.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let r;return t===Th.BACKGROUND_BLURRINESS?r=qa("backgroundBlurriness","float",s):t===Th.BACKGROUND_INTENSITY&&(r=qa("backgroundIntensity","float",s)),r}}Th.BACKGROUND_BLURRINESS="backgroundBlurriness",Th.BACKGROUND_INTENSITY="backgroundIntensity";const xh=pi(Th,Th.BACKGROUND_BLURRINESS),yh=pi(Th,Th.BACKGROUND_INTENSITY);yr("SceneNode",Th);class bh extends Nl{constructor(e,t,s=0){super(e,t,s),this.isStorageBufferNode=!0}getInputType(){return"storageBuffer"}}const Nh=(e,t,s)=>li(new bh(e,t,s));yr("StorageBufferNode",bh);class _h extends $a{constructor(e,t,s=null){super(e,t),this.storeNode=s,this.isStoreTextureNode=!0}getNodeType(){return"void"}}const vh=hi(_h);yr("TextureStoreNode",_h);class Sh extends Xa{constructor(e,t,s=null){super(e,t,s),this.userData=s}update(e){this.reference=null!==this.userData?this.userData:e.object.userData,super.update(e)}}const Ah=(e,t,s)=>li(new Sh(e,t,s));yr("UserDataNode",Sh);const Rh=mi((({base:e,blend:t})=>{const s=s=>t[s].lessThan(wo).cond(t[s],e[s].oneMinus().div(t[s]).oneMinus().max(0));return wi(s("x"),s("y"),s("z"))})),Eh=mi((({base:e,blend:t})=>{const s=s=>t[s].equal(1).cond(t[s],e[s].div(t[s].oneMinus()).max(0));return wi(s("x"),s("y"),s("z"))})),Ch=mi((({base:e,blend:t})=>{const s=s=>e[s].oneMinus().mul(t[s].oneMinus()).oneMinus();return wi(s("x"),s("y"),s("z"))})),wh=mi((({base:e,blend:t})=>{const s=s=>e[s].lessThan(.5).cond(e[s].mul(t[s],2),e[s].oneMinus().mul(t[s].oneMinus()).oneMinus());return wi(s("x"),s("y"),s("z"))}));class Mh extends Mr{constructor(e,t,s){super(),this.blendMode=e,this.baseNode=t,this.blendNode=s}setup(){const{blendMode:e,baseNode:t,blendNode:s}=this,r={base:t,blend:s};let i=null;return e===Mh.BURN?i=Rh(r):e===Mh.DODGE?i=Eh(r):e===Mh.SCREEN?i=Ch(r):e===Mh.OVERLAY&&(i=wh(r)),i}}Mh.BURN="burn",Mh.DODGE="dodge",Mh.SCREEN="screen",Mh.OVERLAY="overlay";const Fh=hi(Mh,Mh.BURN),Bh=hi(Mh,Mh.DODGE),Oh=hi(Mh,Mh.OVERLAY),Lh=hi(Mh,Mh.SCREEN);Pr("burn",Fh),Pr("dodge",Bh),Pr("overlay",Oh),Pr("screen",Lh),yr("BlendModeNode",Mh);class Uh extends xr{constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){return e.getFrontFacing()}}const Ih=pi(Uh),Dh=Ni(Ih).mul(2).sub(1);yr("FrontFacingNode",Uh);const Ph=mi((({textureNode:e,bumpScale:t})=>{let s=e;if(!0!==s.isTextureNode&&s.traverse((e=>{!0===e.isTextureNode&&(s=e)})),!0!==s.isTextureNode)throw new Error("THREE.TSL: dHdxy_fwd() requires a TextureNode.");const r=Ni(e),i=s.uvNode||io(),n=t=>e.cache().context({getUV:()=>t,forceUVContext:!0});return Ai(Ni(n(i.add(i.dFdx()))).sub(r),Ni(n(i.add(i.dFdy()))).sub(r)).mul(t)})),Vh=mi((e=>{const{surf_pos:t,surf_norm:s,dHdxy:r}=e,i=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(i),u=i.dot(o).mul(Dh),l=u.sign().mul(r.x.mul(o).add(r.y.mul(a)));return u.abs().mul(s).sub(l).normalize()}));class Gh extends Mr{constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Ph({textureNode:this.textureNode,bumpScale:e});return Vh({surf_pos:dl,surf_norm:Ru,dHdxy:t})}}const kh=hi(Gh);Pr("bumpMap",kh),yr("BumpMapNode",Gh);const zh=mi((({color:e,adjustment:t})=>t.mix(Kh(e.rgb),e.rgb))),$h=mi((({color:e,adjustment:t})=>{const s=uo(e.r,e.g,e.b).div(3),r=e.r.max(e.g.max(e.b)),i=r.sub(s).mul(t).mul(-3);return va(e.rgb,r,i)})),Hh=mi((({color:e,adjustment:t})=>{const s=wi(.57735,.57735,.57735),r=t.cos();return wi(e.rgb.mul(r).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(ma(s,e.rgb).mul(r.oneMinus())))))}));class Wh extends Mr{constructor(e,t,s=Ni(1)){super("vec3"),this.method=e,this.colorNode=t,this.adjustmentNode=s}setup(){const{method:e,colorNode:t,adjustmentNode:s}=this,r={color:t,adjustment:s};let i=null;return e===Wh.SATURATION?i=zh(r):e===Wh.VIBRANCE?i=$h(r):e===Wh.HUE&&(i=Hh(r)),i}}Wh.SATURATION="saturation",Wh.VIBRANCE="vibrance",Wh.HUE="hue";const jh=hi(Wh,Wh.SATURATION),Xh=hi(Wh,Wh.VIBRANCE),qh=hi(Wh,Wh.HUE),Yh=wi(.2125,.7154,.0721),Kh=(e,t=Yh)=>ma(e,t);Pr("saturation",jh),Pr("vibrance",Xh),Pr("hue",qh),yr("ColorAdjustmentNode",Wh);const Qh=mi((e=>{const{eye_pos:t,surf_norm:s,mapN:r,uv:i}=e,n=t.dFdx(),o=t.dFdy(),a=i.dFdx(),u=i.dFdy(),l=s,d=o.cross(l),c=l.cross(n),h=d.mul(a.x).add(c.mul(u.x)),p=d.mul(a.y).add(c.mul(u.y)),g=h.dot(h).max(p.dot(p)),m=Dh.mul(g.inverseSqrt());return uo(h.mul(r.x,m),p.mul(r.y,m),l.mul(r.z)).normalize()}));class Zh extends Mr{constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=H}setup(e){const{normalMapType:t,scaleNode:s}=this;let r=this.node.mul(2).sub(1);null!==s&&(r=wi(r.xy.mul(s),r.z));let i=null;if(t===W)i=xu.mul(r).normalize();else if(t===H){i=!0===e.hasGeometryAttribute("tangent")?ep.mul(r).normalize():Qh({eye_pos:dl,surf_norm:Ru,mapN:r,uv:io()})}return i}}const Jh=hi(Zh),ep=Di(Rl,Qc,Ru);Pr("normalMap",Jh),yr("NormalMapNode",Zh);class tp extends Mr{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 sp=hi(tp);Pr("posterize",sp),yr("PosterizeNode",tp);const rp=mi((({color:e,exposure:t})=>e.mul(t).clamp())),ip=mi((({color:e,exposure:t})=>(e=e.mul(t)).div(e.add(1)).clamp())),np=mi((({color:e,exposure:t})=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(r).pow(2.2)})),op=mi((({color:e})=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)})),ap=mi((({color:e,exposure:t})=>{const s=Di(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=Di(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=op({color:e}),(e=r.mul(e)).clamp()})),up={[X]:rp,[q]:ip,[Y]:np,[K]:ap};class lp extends Mr{constructor(e=j,t=Ni(1),s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){let e=super.getCacheKey();return e="{toneMapping:"+this.toneMapping+",nodes:"+e+"}",e}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(s===j)return t;const r={exposure:this.exposureNode,color:t},i=up[s];let n=null;return n=i?i(r):t,n}}const dp=(e,t,s)=>li(new lp(e,li(t),li(s)));yr("ToneMappingNode",lp);let cp=null;class hp extends Td{constructor(e=hd,t=null){null===cp&&(cp=new v),super(e,t,cp)}}const pp=hi(hp);Pr("viewportSharedTexture",pp),yr("ViewportSharedTextureNode",hp);const gp=new Q(-1,1,1,-1,0,1);const mp=new class extends Z{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new J([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new J(t,2))}};class fp{constructor(e=null){this._mesh=new U(mp,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,gp)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}const Tp=new fp,xp=new fp;class yp extends Mr{constructor(e,t=2){super(e),this.textureNode=e,this.sigma=t,this.directionNode=Ai(1),this._invSize=Qi(new i),this._passDirection=Qi(new i),this._horizontalRT=new V,this._horizontalRT.texture.name="GaussianBlurNode.horizontal",this._verticalRT=new V,this._verticalRT.texture.name="GaussianBlurNode.vertical",this.updateBeforeType=rr.RENDER,this.resolution=new i(1,1)}setSize(e,t){e=Math.max(Math.round(e*this.resolution.x),1),t=Math.max(Math.round(t*this.resolution.y),1),this._invSize.value.set(1/e,1/t),this._horizontalRT.setSize(e,t),this._verticalRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,s=this.textureNode,r=s.value,i=t.getRenderTarget(),n=s.value;Tp.material=this._material,xp.material=this._material,this.setSize(r.image.width,r.image.height),t.setRenderTarget(this._horizontalRT),this._passDirection.value.set(1,0),Tp.render(t),s.value=this._horizontalRT.texture,t.setRenderTarget(this._verticalRT),this._passDirection.value.set(0,1),xp.render(t),t.setRenderTarget(i),s.value=n}setup(e){const t=this.textureNode;if(!0!==t.isTextureNode)return Oi();const s=t.uvNode||io(),r=e=>t.cache().context({getUV:()=>e,forceUVContext:!0}),i=mi((()=>{const e=3+2*this.sigma,t=this._getCoefficients(e),i=this._invSize,n=Ai(this.directionNode).mul(this._passDirection),o=Ni(t[0]).toVar(),a=Oi(r(s).mul(o)).toVar();for(let u=1;uli(new yp(li(e),t));Pr("gaussianBlur",bp);const Np=new fp;class _p extends Mr{constructor(e,t=.96){super(e),this.textureNode=e,this.textureNodeOld=Ha(),this.damp=Qi(t),this._compRT=new V,this._compRT.texture.name="AfterImageNode.comp",this._oldRT=new V,this._oldRT.texture.name="AfterImageNode.old",this.updateBeforeType=rr.RENDER}setSize(e,t){this._compRT.setSize(e,t),this._oldRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,s=this.textureNode,r=t.getRenderTarget(),i=s.value;this.textureNodeOld.value=this._oldRT.texture,t.setRenderTarget(this._compRT),Np.render(t);const n=this._oldRT;this._oldRT=this._compRT,this._compRT=n;const o=i;this.setSize(o.image.width,o.image.height),t.setRenderTarget(r),s.value=i}setup(e){const t=this.textureNode,s=this.textureNodeOld;if(!0!==t.isTextureNode)return Oi();const r=t.uvNode||io();s.uvNode=r;const i=mi((([e,t])=>{const s=Ni(t).toVar(),r=Oi(e).toVar();return la(Ko(r.sub(s)),0)})),n=mi((()=>{const e=Oi(s),n=Oi((e=>t.cache().context({getUV:()=>e,forceUVContext:!0}))(r));return e.mulAssign(this.damp.mul(i(e,.1))),la(n,e)})),o=this._materialComposed||(this._materialComposed=e.createNodeMaterial("MeshBasicNodeMaterial"));o.fragmentNode=n(),Np.material=o;return e.getNodeProperties(this).textureNode=t,Ha(this._compRT.texture)}}const vp=(e,t)=>li(new _p(li(e),t));Pr("afterImage",vp);class Sp extends $a{constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Ap extends Mr{constructor(e,t,s){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this._pixelRatio=1,this._width=1,this._height=1;const r=new b;r.isRenderTargetTexture=!0,r.type=x,r.name="PostProcessingDepth";const i=new V(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ee});i.texture.name="PostProcessing",i.depthTexture=r,this.renderTarget=i,this.updateBeforeType=rr.FRAME,this._textureNode=li(new Sp(this,i.texture)),this._depthTextureNode=li(new Sp(this,r)),this._depthNode=null,this._cameraNear=Qi(0),this._cameraFar=Qi(0),this.isPassNode=!0}isGlobal(){return!0}getTextureNode(){return this._textureNode}getTextureDepthNode(){return this._depthTextureNode}getDepthNode(){if(null===this._depthNode){const e=this._cameraNear,t=this._cameraFar;this._depthNode=Sd(Ed(this._depthTextureNode,e,t),e,t)}return this._depthNode}setup(){return this.scope===Ap.COLOR?this.getTextureNode():this.getDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:r}=this;this._pixelRatio=t.getPixelRatio();const n=t.getSize(new i);this.setSize(n.width,n.height);const o=t.toneMapping,a=t.toneMappingNode,u=t.getRenderTarget();this._cameraNear.value=r.near,this._cameraFar.value=r.far,t.toneMapping=j,t.toneMappingNode=null,t.setRenderTarget(this.renderTarget),t.render(s,r),t.toneMapping=o,t.toneMappingNode=a,t.setRenderTarget(u)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,r=this._height*this._pixelRatio;this.renderTarget.setSize(s,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Ap.COLOR="color",Ap.DEPTH="depth";const Rp=(e,t)=>li(new Ap(Ap.COLOR,e,t)),Ep=(e,t)=>li(new Ap(Ap.DEPTH,e,t));yr("PassNode",Ap);class Cp extends Mr{constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],s=this.functionNode,r=s.getInputs(e),i=this.parameters;if(Array.isArray(i))for(let s=0;s(t=t.length>1||t[0]&&!0===t[0].isNode?ci(t):di(t[0]),li(new Cp(li(e),t)));Pr("call",wp),yr("FunctionCallNode",Cp);class Mp extends xr{constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new l,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:Ni()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=pr(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?gr(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 Fp=hi(Mp);Pr("scriptableValue",Fp),yr("ScriptableValueNode",Mp);class Bp extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const r=t(...s);return this.set(e,r),r}}}class Op{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 Lp=new Bp;class Up extends xr{constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new Bp,this._output=Fp(),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 s=this._outputs;return void 0===s[e]?s[e]=Fp(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=Fp(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[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 s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...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 Op(this),t=Lp.get("THREE"),s=Lp.get("TSL"),r=this.getMethod(this.codeNode),i=[e,this._local,Lp,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=r(...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:Ni()}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+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),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()}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 Ip=hi(Up);Pr("scriptable",Ip),yr("ScriptableNode",Up);class Dp extends xr{constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}mixAssign(e){return this.mix(e,this.colorNode)}setup(){return this.factorNode}}const Pp=hi(Dp);Pr("fog",Pp),yr("FogNode",Dp);class Vp extends Dp{constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(){return Ea(this.nearNode,this.farNode,dl.z.negate())}}const Gp=hi(Vp);Pr("rangeFog",Gp),yr("FogRangeNode",Vp);class kp extends Dp{constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(){const e=dl.z.negate(),t=this.densityNode;return t.mul(t,e,e).negate().exp().oneMinus()}}const zp=hi(kp);Pr("densityFog",zp),yr("FogExp2Node",kp);let $p=null,Hp=null;class Wp extends xr{constructor(e=Ni(),t=Ni()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(cr(this.minNode.value)),s=e.getTypeLength(cr(this.maxNode.value));return t>s?t:s}getNodeType(e){return!0===e.object.isInstancedMesh?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let s=null;if(!0===t.isInstancedMesh){const r=this.minNode.value,i=this.maxNode.value,n=e.getTypeLength(cr(r)),a=e.getTypeLength(cr(i));$p=$p||new o,Hp=Hp||new o,$p.setScalar(0),Hp.setScalar(0),1===n?$p.setScalar(r):r.isColor?$p.set(r.r,r.g,r.b):$p.set(r.x,r.y,r.z||0,r.w||0),1===a?Hp.setScalar(i):i.isColor?Hp.set(i.r,i.g,i.b):Hp.set(i.x,i.y,i.z||0,i.w||0);const u=4,l=u*t.count,c=new Float32Array(l);for(let e=0;eli(new Xp(li(e),t,s));Pr("compute",qp),yr("ComputeNode",Xp);class Yp extends xr{constructor(e=Yp.TARGET_DIRECTION,t=null){super(),this.scope=e,this.light=t}setup(){const{scope:e,light:t}=this;let s=null;return e===Yp.TARGET_DIRECTION&&(s=cu.transformDirection(ru(t).sub(ru(t.target)))),s}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Yp.TARGET_DIRECTION="targetDirection";const Kp=hi(Yp,Yp.TARGET_DIRECTION);yr("LightNode",Yp);const Qp=mi((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:r}=e,i=t.pow(r).max(.01).reciprocal();return s.greaterThan(0).cond(i.mul(t.div(s).pow4().oneMinus().clamp().pow2()),i)}));class Zp extends $l{constructor(e=null){super(e),this.cutoffDistanceNode=Qi(0),this.decayExponentNode=Qi(0)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:r,light:i}=this,n=e.context.lightingModel,o=nu(i).sub(dl),a=o.normalize(),u=o.length(),l=Qp({lightDistance:u,cutoffDistance:s,decayExponent:r}),d=t.mul(l),c=e.context.reflectedLight;n.direct({lightDirection:a,lightColor:d,reflectedLight:c},e.stack,e)}}yr("PointLightNode",Zp),ql(te,Zp);class Jp extends $l{constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,r=Kp(this.light),i=e.context.reflectedLight;t.direct({lightDirection:r,lightColor:s,reflectedLight:i},e.stack,e)}}yr("DirectionalLightNode",Jp),ql(se,Jp);class eg extends $l{constructor(e=null){super(e),this.coneCosNode=Qi(0),this.penumbraCosNode=Qi(0),this.cutoffDistanceNode=Qi(0),this.decayExponentNode=Qi(0)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e){const{coneCosNode:t,penumbraCosNode:s}=this;return Ea(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:r,decayExponentNode:i,light:n}=this,o=nu(n).sub(dl),a=o.normalize(),u=a.dot(Kp(n)),l=this.getSpotAttenuation(u),d=o.length(),c=Qp({lightDistance:d,cutoffDistance:r,decayExponent:i}),h=s.mul(l).mul(c),p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:h,reflectedLight:p},e.stack,e)}}yr("SpotLightNode",eg),ql(re,eg);class tg extends eg{getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const r=e.acos().mul(1/Math.PI);s=Ha(t,Ai(r,0),0).r}else s=super.getSpotAttenuation(e);return s}}yr("IESSpotLightNode",tg),ql(class extends re{constructor(e,t,s,r,i,n){super(e,t,s,r,i,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}},tg);class sg extends $l{constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}yr("AmbientLightNode",sg),ql(ie,sg);class rg extends $l{constructor(e=null){super(e),this.lightPositionNode=ru(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Qi(new r)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:r}=this,i=Ru.dot(r).mul(.5).add(.5),n=va(s,t,i);e.context.irradiance.addAssign(n)}}yr("HemisphereLightNode",rg),ql(ne,rg);const ig=mi((e=>{const t=e.uv.mul(2),s=t.x.floor(),r=t.y.floor();return s.add(r).mod(2).sign()}));class ng extends Mr{constructor(e=io()){super("float"),this.uvNode=e}setup(){return ig({uv:this.uvNode})}}const og=hi(ng);Pr("checker",og),yr("CheckerNode",ng);class ag extends oe{constructor(e){super(e),this.textures={}}load(e,t,s,r){const i=new ae(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,(s=>{try{t(this.parse(JSON.parse(s)))}catch(t){r&&r(t),this.manager.itemError(e)}}),s,r)}parseNodes(e){const t={};if(void 0!==e){for(const s of e){const{uuid:e,type:r}=s;t[e]=li(br(r)),t[e].uuid=e}const s={nodes:t,textures:this.textures};for(const r of e){r.meta=s;t[r.uuid].deserialize(r),delete r.meta}}return t}parse(e){const t=li(br(e.type));t.uuid=e.uuid;const s={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=s,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}}const ug=new ue;class lg extends Od{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.setDefaultValues(ug),this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor;this.vertexNode=mi((()=>{sn(Ai(),"vUv").assign(io());const e=nn("instancePosition"),t=Cn("vec4","mvPos");t.assign(Tu.mul(Oi(e,1)));const s=cd.z.div(cd.w),r=au.mul(t),i=Cn("vec2","offset");return i.assign(ol.xy),i.assign(i.mul(il)),i.assign(i.div(cd.z)),i.y.assign(i.y.mul(s)),i.assign(i.mul(r.w)),r.assign(r.add(Oi(i,0,0))),r}))(),this.fragmentNode=mi((()=>{const s=sn(Ai(),"vUv"),r=Cn("float","alpha");r.assign(1);const i=s.x,n=s.y,o=i.mul(i).add(n.mul(n));if(e){const e=Cn("float","dlen");e.assign(o.fwidth()),r.assign(Ea(e.oneMinus(),e.add(1),o).oneMinus())}else o.greaterThan(1).discard();let a;if(this.pointColorNode)a=this.pointColorNode;else if(t){a=nn("instanceColor").mul(Lu)}else a=Lu;return Oi(a,r)}))(),this.needsUpdate=!0}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}Ld("InstancedPointsNodeMaterial",lg);const dg=new le;class cg extends Od{constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(dg),this.setValues(e)}}Ld("LineBasicNodeMaterial",cg);const hg=new de;class pg extends Od{constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(hg),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?Ni(this.dashScaleNode):Ju,s=this.dashSizeNode?Ni(this.dashSizeNode):el,r=this.dashSizeNode?Ni(this.dashGapNode):tl;$n.assign(s),Hn.assign(r);const i=sn(nn("lineDistance").mul(t));(e?i.add(e):i).mod($n.add(Hn)).greaterThan($n).discard()}}Ld("LineDashedNodeMaterial",pg);const gg=new de;class mg extends Od{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.setDefaultValues(gg),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor,s=this.dashed,r=this.worldUnits,i=mi((({start:e,end:t})=>{const s=au.element(2).element(2),r=au.element(3).element(2).mul(-.5).div(s).sub(e.z).div(t.z.sub(e.z));return Oi(va(e.xyz,t.xyz,r),t.w)}));this.vertexNode=mi((()=>{wn("vec2","vUv").assign(io());const e=nn("instanceStart"),t=nn("instanceEnd"),n=Cn("vec4","start"),o=Cn("vec4","end");n.assign(Tu.mul(Oi(e,1))),o.assign(Tu.mul(Oi(t,1))),r&&(wn("vec3","worldStart").assign(n.xyz),wn("vec3","worldEnd").assign(o.xyz));const a=cd.z.div(cd.w),u=au.element(2).element(3).equal(-1);xi(u,(()=>{xi(n.z.lessThan(0).and(o.z.greaterThan(0)),(()=>{o.assign(i({start:n,end:o}))})).elseif(o.z.lessThan(0).and(n.z.greaterThanEqual(0)),(()=>{n.assign(i({start:o,end:n}))}))}));const l=au.mul(n),d=au.mul(o),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).temp();p.x.assign(p.x.mul(a)),p.assign(p.normalize());const g=bn(Oi());if(r){const e=o.xyz.sub(n.xyz).normalize(),t=va(n.xyz,o.xyz,.5).normalize(),r=e.cross(t).normalize(),i=e.cross(r),a=wn("vec4","worldPos");a.assign(ol.y.lessThan(.5).cond(n,o));const u=sl.mul(.5);a.addAssign(Oi(ol.x.lessThan(0).cond(r.mul(u),r.mul(u).negate()),0)),s||(a.addAssign(Oi(ol.y.lessThan(.5).cond(e.mul(u).negate(),e.mul(u)),0)),a.addAssign(Oi(i.mul(u),0)),xi(ol.y.greaterThan(1).or(ol.y.lessThan(0)),(()=>{a.subAssign(Oi(i.mul(2).mul(u),0))}))),g.assign(au.mul(a));const l=bn(wi());l.assign(ol.y.lessThan(.5).cond(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=Cn("vec2","offset");e.assign(Ai(p.y,p.x.negate())),p.x.assign(p.x.div(a)),e.x.assign(e.x.div(a)),e.assign(ol.x.lessThan(0).cond(e.negate(),e)),xi(ol.y.lessThan(0),(()=>{e.assign(e.sub(p))})).elseif(ol.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(sl)),e.assign(e.div(cd.w)),g.assign(ol.y.lessThan(.5).cond(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(Oi(e,0,0)))}return g}))();const n=mi((({p1:e,p2:t,p3:s,p4:r})=>{const i=e.sub(s),n=r.sub(s),o=t.sub(e),a=i.dot(n),u=n.dot(o),l=i.dot(o),d=n.dot(n),c=o.dot(o).mul(d).sub(u.mul(u)),h=a.mul(u).sub(l.mul(d)).div(c).clamp(),p=a.add(u.mul(h)).div(d).clamp();return Ai(h,p)}));this.fragmentNode=mi((()=>{const i=wn("vec2","vUv");if(s){const e=this.offsetNode?Ni(this.offsetNodeNode):rl,t=this.dashScaleNode?Ni(this.dashScaleNode):Ju,s=this.dashSizeNode?Ni(this.dashSizeNode):el,r=this.dashSizeNode?Ni(this.dashGapNode):tl;$n.assign(s),Hn.assign(r);const n=nn("instanceDistanceStart"),o=nn("instanceDistanceEnd"),a=ol.y.lessThan(.5).cond(t.mul(n),Ju.mul(o)),u=sn(a.add(rl)),l=e?u.add(e):u;i.y.lessThan(-1).or(i.y.greaterThan(1)).discard(),l.mod($n.add(Hn)).greaterThan($n).discard()}const o=Cn("float","alpha");if(o.assign(1),r){const t=wn("vec3","worldStart"),r=wn("vec3","worldEnd"),i=wn("vec4","worldPos").xyz.normalize().mul(1e5),a=r.sub(t),u=n({p1:t,p2:r,p3:wi(0,0,0),p4:i}),l=t.add(a.mul(u.x)),d=i.mul(u.y),c=l.sub(d).length().div(sl);if(!s)if(e){const e=c.fwidth();o.assign(Ea(e.negate().add(.5),e.add(.5),c).oneMinus())}else c.greaterThan(.5).discard()}else if(e){const e=i.x,t=i.y.greaterThan(0).cond(i.y.sub(1),i.y.add(1)),s=e.mul(e).add(t.mul(t)),r=Cn("float","dlen");r.assign(s.fwidth()),xi(i.y.abs().greaterThan(1),(()=>{o.assign(Ea(r.oneMinus(),r.add(1),s).oneMinus())}))}else xi(i.y.abs().greaterThan(1),(()=>{const e=i.x,t=i.y.greaterThan(0).cond(i.y.sub(1),i.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let a;if(this.lineColorNode)a=this.lineColorNode;else if(t){const e=nn("instanceColorStart"),t=nn("instanceColorEnd");a=ol.y.lessThan(.5).cond(e,t).mul(Lu)}else a=Lu;return Oi(a,o)}))(),this.needsUpdate=!0}get worldUnits(){return this.useWorldUnits}set worldUnits(e){this.useWorldUnits!==e&&(this.useWorldUnits=e,this.setupShaders())}get dashed(){return this.useDash}set dashed(e){this.useDash!==e&&(this.useDash=e,this.setupShaders())}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}Ld("Line2NodeMaterial",mg);const fg=new ce;class Tg extends Od{constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.colorSpaced=!1,this.setDefaultValues(fg),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Ni(this.opacityNode):Du;Mn.assign(Oi(Ic(Cu),e))}}Ld("MeshNormalNodeMaterial",Tg);const xg=new he;class yg extends Od{constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(xg),this.setValues(e)}}Ld("MeshBasicNodeMaterial",yg);const bg=mi((({f0:e,f90:t,dotVH:s})=>{const r=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(r.oneMinus()).add(t.mul(r))})),Ng=mi((e=>e.diffuseColor.mul(1/Math.PI))),_g=mi((({dotNH:e})=>kn.mul(.5/Math.PI).add(1).mul(e.pow(kn)))),vg=mi((({lightDirection:e})=>{const t=e.add(cl).normalize(),s=Cu.dot(t).clamp(),r=cl.dot(t).clamp(),i=bg({f0:Gn,f90:1,dotVH:r}),n=Ni(.25),o=_g({dotNH:s});return i.mul(n).mul(o)}));class Sg extends xn{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const r=Cu.dot(e).clamp().mul(t);s.directDiffuse.addAssign(r.mul(Ng({diffuseColor:Mn.rgb}))),!0===this.specular&&s.directSpecular.addAssign(r.mul(vg({lightDirection:e})).mul(Vu))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Ng({diffuseColor:Mn})))}}const Ag=new pe;class Rg extends Od{constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ag),this.setValues(e)}setupLightingModel(){return new Sg(!1)}}Ld("MeshLambertNodeMaterial",Rg);const Eg=new ge;class Cg extends Od{constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Eg),this.setValues(e)}setupLightingModel(){return new Sg}setupVariants(){const e=(this.shininessNode?Ni(this.shininessNode):Uu).max(1e-4);kn.assign(e);const t=this.specularNode||Pu;Gn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}Ld("MeshPhongNodeMaterial",Cg);const wg=mi((()=>{const e=Su.dFdx().abs().max(Su.dFdy().abs());return e.x.max(e.y).max(e.z)})),Mg=mi((e=>{const{roughness:t}=e,s=wg();let r=t.max(.0525);return r=r.add(s),r=r.min(1),r})),Fg=mi((e=>{const{alpha:t,dotNL:s,dotNV:r}=e,i=t.pow2(),n=s.mul(i.add(i.oneMinus().mul(r.pow2())).sqrt()),o=r.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt());return ho(.5,n.add(o).max(wo))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Bg=mi((({alpha:e,dotNH:t})=>{const s=e.pow2(),r=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(r.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),Og=mi((e=>{const{lightDirection:t,f0:s,f90:r,roughness:i,iridescenceFresnel:n}=e,o=e.normalView||Cu,a=i.pow2(),u=t.add(cl).normalize(),l=o.dot(t).clamp(),d=o.dot(cl).clamp(),c=o.dot(u).clamp(),h=cl.dot(u).clamp();let p=bg({f0:s,f90:r,dotVH:h});n&&(p=Dn.mix(p,n));const g=Fg({alpha:a,dotNL:l,dotNV:d}),m=Bg({alpha:a,dotNH:c});return p.mul(g).mul(m)})),Lg=mi((({roughness:e,dotNV:t})=>{const s=Oi(-1,-.0275,-.572,.022),r=Oi(1,.0425,1.04,-.04),i=e.mul(s).add(r),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return Ai(-1.04,1.04).mul(n).add(i.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),Ug=mi((e=>{const{dotNV:t,specularColor:s,specularF90:r,roughness:i}=e,n=Lg({dotNV:t,roughness:i});return s.mul(n.x).add(r.mul(n.y))})),Ig=mi((({f:e,f90:t,dotVH:s})=>{const r=s.oneMinus().saturate(),i=r.mul(r),n=r.mul(i,i).clamp(0,.9999);return e.sub(wi(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"}]}),Dg=mi((({roughness:e,dotNH:t})=>{const s=e.pow2(),r=Ni(1).div(s),i=t.pow2().oneMinus().max(.0078125);return Ni(2).add(r).mul(i.pow(r.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),Pg=mi((({dotNV:e,dotNL:t})=>Ni(1).div(Ni(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Vg=mi((({lightDirection:e})=>{const t=e.add(cl).normalize(),s=Cu.dot(e).clamp(),r=Cu.dot(cl).clamp(),i=Cu.dot(t).clamp(),n=Dg({roughness:In,dotNH:i}),o=Pg({dotNV:r,dotNL:s});return Un.mul(n).mul(o)})),Gg=Di(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),kg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),zg=(e,t)=>{const s=e.mul(2*Math.PI*1e-9),r=wi(54856e-17,44201e-17,52481e-17),i=wi(1681e3,1795300,2208400),n=wi(43278e5,93046e5,66121e5),o=Ni(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=r.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());a=wi(a.x.add(o),a.y,a.z).div(1.0685e-7);return Gg.mul(a)},$g=mi((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:r,baseF0:i})=>{const n=va(e,t,Ea(0,.03,r)),o=e.div(n).pow2().mul(Ni(1).sub(s.pow2())),a=Ni(1).sub(o).sqrt(),u=kg(n,e),l=bg({f0:u,f90:1,dotVH:s}),d=l.oneMinus(),c=n.lessThan(e).cond(Math.PI,0),h=Ni(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return wi(1).add(t).div(wi(1).sub(t))})(i.clamp(0,.9999)),g=kg(p,n.vec3()),m=bg({f0:g,f90:1,dotVH:a}),f=wi(p.x.lessThan(n).cond(Math.PI,0),p.y.lessThan(n).cond(Math.PI,0),p.z.lessThan(n).cond(Math.PI,0)),T=n.mul(r,a,2),x=wi(h).add(f),y=l.mul(m).clamp(1e-5,.9999),b=y.sqrt(),N=d.pow2().mul(m).div(wi(1).sub(y));let _=l.add(N),v=N.sub(d);for(let e=1;e<=2;++e){v=v.mul(b);const t=zg(Ni(e).mul(T),Ni(e).mul(x)).mul(2);_=_.add(v.mul(t))}return _.max(wi(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"}]}),Hg=mi((({normal:e,viewDir:t,roughness:s})=>{const r=e.dot(t).saturate(),i=s.pow2(),n=Zd(s.lessThan(.25),Ni(-339.2).mul(i).add(Ni(161.4).mul(s)).sub(25.9),Ni(-8.48).mul(i).add(Ni(14.3).mul(s)).sub(9.95)),o=Zd(s.lessThan(.25),Ni(44).mul(i).sub(Ni(23.7).mul(s)).add(3.26),Ni(1.97).mul(i).sub(Ni(3.27).mul(s)).add(.72));return Zd(s.lessThan(.25),0,Ni(.1).mul(s).sub(.025)).add(n.mul(r).add(o).exp()).mul(1/Math.PI).saturate()})),Wg=wi(.04),jg=wi(1);class Xg extends xn{constructor(e=!1,t=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(){if(!0===this.clearcoat&&(this.clearcoatRadiance=wi().temp("clearcoatRadiance"),this.clearcoatSpecularDirect=wi().temp("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=wi().temp("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=wi().temp("sheenSpecularDirect"),this.sheenSpecularIndirect=wi().temp("sheenSpecularIndirect")),!0===this.iridescence){const e=Cu.dot(cl).clamp();this.iridescenceFresnel=$g({outsideIOR:Ni(1),eta2:Pn,cosTheta1:e,thinFilmThickness:Vn,baseF0:Gn}),this.iridescenceF0=Ig({f:this.iridescenceFresnel,f90:1,dotVH:e})}}computeMultiscattering(e,t,s=Ni(1)){const r=Cu.dot(cl).clamp(),i=Lg({roughness:Fn,dotNV:r}),n=(this.iridescenceF0?Dn.mix(Gn,this.iridescenceF0):Gn).mul(i.x).add(s.mul(i.y)),o=i.x.add(i.y).oneMinus(),a=Gn.add(Gn.oneMinus().mul(.047619)),u=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(u.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const r=Cu.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(r.mul(Vg({lightDirection:e}))),!0===this.clearcoat){const s=Mu.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(Og({lightDirection:e,f0:Wg,f90:jg,roughness:Ln,normalView:Mu})))}s.directDiffuse.addAssign(r.mul(Ng({diffuseColor:Mn.rgb}))),s.directSpecular.addAssign(r.mul(Og({lightDirection:e,f0:Gn,f90:1,roughness:Fn,iridescence:this.iridescence,iridescenceFresnel:this.iridescenceFresnel})))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Ng({diffuseColor:Mn})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(Un,Hg({normal:Cu,viewDir:cl,roughness:In}))),!0===this.clearcoat){const e=Mu.dot(cl).clamp(),t=Ug({dotNV:e,specularColor:Wg,specularF90:jg,roughness:Ln});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=wi().temp("singleScattering"),i=wi().temp("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(r,i);const o=r.add(i),a=Mn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(r)),s.indirectSpecular.addAssign(i.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=Cu.dot(cl).clamp().add(e),r=Fn.mul(-16).oneMinus().negate().exp2(),i=e.sub(s.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(i)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Mu.dot(cl).clamp(),s=bg({dotVH:e,f0:Wg,f90:jg}),r=t.mul(On.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(On));t.assign(r)}if(!0===this.sheen){const e=Un.r.max(Un.g).max(Un.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const qg=new me;class Yg extends Od{constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(qg),this.setValues(e)}setupLightingModel(){return new Xg}setupVariants(){const e=this.metalnessNode?Ni(this.metalnessNode):zu;Bn.assign(e);let t=this.roughnessNode?Ni(this.roughnessNode):ku;t=Mg({roughness:t}),Fn.assign(t);const s=va(wi(.04),Mn.rgb,e);Gn.assign(s),Mn.assign(Oi(Mn.rgb.mul(e.oneMinus()),Mn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}Ld("MeshStandardNodeMaterial",Yg);const Kg=new fe;class Qg extends Yg{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.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.setDefaultValues(Kg),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}setupLightingModel(){return new Xg(this.useClearcoat,this.useSheen,this.useIridescence)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Ni(this.clearcoatNode):Hu,t=this.clearcoatRoughnessNode?Ni(this.clearcoatRoughnessNode):Wu;On.assign(e),Ln.assign(t)}if(this.useSheen){const e=this.sheenNode?wi(this.sheenNode):qu,t=this.sheenRoughnessNode?Ni(this.sheenRoughnessNode):Yu;Un.assign(e),In.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Ni(this.iridescenceNode):Ku,t=this.iridescenceIORNode?Ni(this.iridescenceIORNode):Qu,s=this.iridescenceThicknessNode?Ni(this.iridescenceThicknessNode):Zu;Dn.assign(e),Pn.assign(t),Vn.assign(s)}}setupNormal(e){super.setupNormal(e);const t=this.clearcoatNormalNode?wi(this.clearcoatNormalNode):ju;Mu.assign(t)}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,super.copy(e)}}Ld("MeshPhysicalNodeMaterial",Qg);class Zg extends Xg{constructor(e,t,s,r){super(e,t,s),this.useSSS=r}direct({lightDirection:e,lightColor:t,reflectedLight:s},r,i){if(!0===this.useSSS){const r=i.material,{thicknessColorNode:n,thicknessDistortionNode:o,thicknessAmbientNode:a,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=r,c=e.add(Cu.mul(o)).normalize(),h=Ni(cl.dot(c.negate()).saturate().pow(l).mul(d)),p=wi(h.add(a).mul(n));s.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:s},r,i)}}class Jg extends Qg{constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Ni(.1),this.thicknessAmbientNode=Ni(0),this.thicknessAttenuationNode=Ni(.1),this.thicknessPowerNode=Ni(2),this.thicknessScaleNode=Ni(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Zg(this.useClearcoat,this.useSheen,this.useIridescence,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)}}Ld("MeshSSSNodeMaterial",Jg);const em=new ue;class tm extends Od{constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.normals=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(em),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}Ld("PointsNodeMaterial",tm);const sm=new Te;class rm extends Od{constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this.normals=!1,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(sm),this.setValues(e)}setupPosition({object:e,context:t}){const{positionNode:s,rotationNode:r,scaleNode:i}=this,n=al;let o=Tu.mul(wi(s||0)),a=Ai(yu[0].xyz.length(),yu[1].xyz.length());null!==i&&(a=a.mul(i));let u=n.xy;e.center&&!0===e.center.isVector2&&(u=u.sub(Qi(e.center).sub(.5))),u=u.mul(a);const l=Ni(r||Xu),d=l.cos(),c=l.sin(),h=Ai(Ai(d,c.negate()).dot(u),Ai(c,d).dot(u));o=Oi(o.xy.add(h),o.zw);const p=au.mul(o);return t.vertex=n,p}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}}Ld("SpriteNodeMaterial",rm);const im=xe.createMaterialFromType;xe.createMaterialFromType=function(e){const t=Ud(e);return void 0!==t?t:im.call(this,e)};class nm extends xe{constructor(e){super(e),this.nodes={}}parse(e){const t=super.parse(e),s=this.nodes,r=e.inputNodes;for(const e in r){const i=r[e];t[e]=s[i]}return t}setNodes(e){return this.nodes=e,this}}class om extends ye{constructor(e){super(e),this._nodesJSON=null}parse(e,t){this._nodesJSON=e.nodes;const s=super.parse(e,t);return this._nodesJSON=null,s}parseNodes(e,t){if(void 0!==e){const s=new ag;return s.setTextures(t),s.parseNodes(e)}return{}}parseMaterials(e,t){const s={};if(void 0!==e){const r=this.parseNodes(this._nodesJSON,t),i=new nm;i.setTextures(t),i.setNodes(r);for(let t=0,r=e.length;t{const t=(e=e.trim()).indexOf(cm),s=-1!==t?e.slice(t+12):e,r=s.match(lm);if(null!==r&&5===r.length){const i=r[4],n=[];let o=null;for(;null!==(o=dm.exec(i));)n.push(o);const a=[];let u=0;for(;u{const r=Ni(s).toVar(),i=Ni(t).toVar(),n=Si(e).toVar();return Zd(n,i,r)})),mm=mi((([e,t])=>{const s=Si(t).toVar(),r=Ni(e).toVar();return Zd(s,r.negate(),r)})),fm=mi((([e])=>{const t=Ni(e).toVar();return _i(Vo(t))})),Tm=mi((([e,t])=>{const s=Ni(e).toVar();return t.assign(fm(s)),s.sub(Ni(t))})),xm=mi((([e,t,s,r,i,n])=>{const o=Ni(n).toVar(),a=Ni(i).toVar(),u=Ni(r).toVar(),l=Ni(s).toVar(),d=Ni(t).toVar(),c=Ni(e).toVar(),h=Ni(lo(1,a)).toVar();return lo(1,o).mul(c.mul(h).add(d.mul(a))).add(o.mul(l.mul(h).add(u.mul(a))))})),ym=mi((([e,t,s,r,i,n])=>{const o=Ni(n).toVar(),a=Ni(i).toVar(),u=wi(r).toVar(),l=wi(s).toVar(),d=wi(t).toVar(),c=wi(e).toVar(),h=Ni(lo(1,a)).toVar();return lo(1,o).mul(c.mul(h).add(d.mul(a))).add(o.mul(l.mul(h).add(u.mul(a))))})),bm=bc([xm,ym]),Nm=mi((([e,t,s,r,i,n,o,a,u,l,d])=>{const c=Ni(d).toVar(),h=Ni(l).toVar(),p=Ni(u).toVar(),g=Ni(a).toVar(),m=Ni(o).toVar(),f=Ni(n).toVar(),T=Ni(i).toVar(),x=Ni(r).toVar(),y=Ni(s).toVar(),b=Ni(t).toVar(),N=Ni(e).toVar(),_=Ni(lo(1,p)).toVar(),v=Ni(lo(1,h)).toVar();return Ni(lo(1,c)).toVar().mul(v.mul(N.mul(_).add(b.mul(p))).add(h.mul(y.mul(_).add(x.mul(p))))).add(c.mul(v.mul(T.mul(_).add(f.mul(p))).add(h.mul(m.mul(_).add(g.mul(p))))))})),_m=mi((([e,t,s,r,i,n,o,a,u,l,d])=>{const c=Ni(d).toVar(),h=Ni(l).toVar(),p=Ni(u).toVar(),g=wi(a).toVar(),m=wi(o).toVar(),f=wi(n).toVar(),T=wi(i).toVar(),x=wi(r).toVar(),y=wi(s).toVar(),b=wi(t).toVar(),N=wi(e).toVar(),_=Ni(lo(1,p)).toVar(),v=Ni(lo(1,h)).toVar();return Ni(lo(1,c)).toVar().mul(v.mul(N.mul(_).add(b.mul(p))).add(h.mul(y.mul(_).add(x.mul(p))))).add(c.mul(v.mul(T.mul(_).add(f.mul(p))).add(h.mul(m.mul(_).add(g.mul(p))))))})),vm=bc([Nm,_m]),Sm=mi((([e,t,s])=>{const r=Ni(s).toVar(),i=Ni(t).toVar(),n=vi(e).toVar(),o=vi(n.bitAnd(vi(7))).toVar(),a=Ni(gm(o.lessThan(vi(4)),i,r)).toVar(),u=Ni(co(2,gm(o.lessThan(vi(4)),r,i))).toVar();return mm(a,Si(o.bitAnd(vi(1)))).add(mm(u,Si(o.bitAnd(vi(2)))))})),Am=mi((([e,t,s,r])=>{const i=Ni(r).toVar(),n=Ni(s).toVar(),o=Ni(t).toVar(),a=vi(e).toVar(),u=vi(a.bitAnd(vi(15))).toVar(),l=Ni(gm(u.lessThan(vi(8)),o,n)).toVar(),d=Ni(gm(u.lessThan(vi(4)),n,gm(u.equal(vi(12)).or(u.equal(vi(14))),o,i))).toVar();return mm(l,Si(u.bitAnd(vi(1)))).add(mm(d,Si(u.bitAnd(vi(2)))))})),Rm=bc([Sm,Am]),Em=mi((([e,t,s])=>{const r=Ni(s).toVar(),i=Ni(t).toVar(),n=Fi(e).toVar();return wi(Rm(n.x,i,r),Rm(n.y,i,r),Rm(n.z,i,r))})),Cm=mi((([e,t,s,r])=>{const i=Ni(r).toVar(),n=Ni(s).toVar(),o=Ni(t).toVar(),a=Fi(e).toVar();return wi(Rm(a.x,o,n,i),Rm(a.y,o,n,i),Rm(a.z,o,n,i))})),wm=bc([Em,Cm]),Mm=mi((([e])=>{const t=Ni(e).toVar();return co(.6616,t)})),Fm=mi((([e])=>{const t=Ni(e).toVar();return co(.982,t)})),Bm=mi((([e])=>{const t=wi(e).toVar();return co(.6616,t)})),Om=bc([Mm,Bm]),Lm=mi((([e])=>{const t=wi(e).toVar();return co(.982,t)})),Um=bc([Fm,Lm]),Im=mi((([e,t])=>{const s=_i(t).toVar(),r=vi(e).toVar();return r.shiftLeft(s).bitOr(r.shiftRight(_i(32).sub(s)))})),Dm=mi((([e,t,s])=>{e.subAssign(s),e.bitXorAssign(Im(s,_i(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(Im(e,_i(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(Im(t,_i(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(Im(s,_i(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(Im(e,_i(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(Im(t,_i(4))),t.addAssign(e)})),Pm=mi((([e,t,s])=>{const r=vi(s).toVar(),i=vi(t).toVar(),n=vi(e).toVar();return r.bitXorAssign(i),r.subAssign(Im(i,_i(14))),n.bitXorAssign(r),n.subAssign(Im(r,_i(11))),i.bitXorAssign(n),i.subAssign(Im(n,_i(25))),r.bitXorAssign(i),r.subAssign(Im(i,_i(16))),n.bitXorAssign(r),n.subAssign(Im(r,_i(4))),i.bitXorAssign(n),i.subAssign(Im(n,_i(14))),r.bitXorAssign(i),r.subAssign(Im(i,_i(24))),r})),Vm=mi((([e])=>{const t=vi(e).toVar();return Ni(t).div(Ni(vi(_i(4294967295))))})),Gm=mi((([e])=>{const t=Ni(e).toVar();return t.mul(t.mul(t.mul(t.mul(t.mul(6).sub(15)).add(10))))})),km=mi((([e])=>{const t=_i(e).toVar(),s=vi(vi(1)).toVar(),r=vi(vi(_i(3735928559)).add(s.shiftLeft(vi(2)).add(vi(13)))).toVar();return Pm(r.add(vi(t)),r,r)})),zm=mi((([e,t])=>{const s=_i(t).toVar(),r=_i(e).toVar(),i=vi(vi(2)).toVar(),n=vi().toVar(),o=vi().toVar(),a=vi().toVar();return n.assign(o.assign(a.assign(vi(_i(3735928559)).add(i.shiftLeft(vi(2)).add(vi(13)))))),n.addAssign(vi(r)),o.addAssign(vi(s)),Pm(n,o,a)})),$m=mi((([e,t,s])=>{const r=_i(s).toVar(),i=_i(t).toVar(),n=_i(e).toVar(),o=vi(vi(3)).toVar(),a=vi().toVar(),u=vi().toVar(),l=vi().toVar();return a.assign(u.assign(l.assign(vi(_i(3735928559)).add(o.shiftLeft(vi(2)).add(vi(13)))))),a.addAssign(vi(n)),u.addAssign(vi(i)),l.addAssign(vi(r)),Pm(a,u,l)})),Hm=mi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=_i(t).toVar(),a=_i(e).toVar(),u=vi(vi(4)).toVar(),l=vi().toVar(),d=vi().toVar(),c=vi().toVar();return l.assign(d.assign(c.assign(vi(_i(3735928559)).add(u.shiftLeft(vi(2)).add(vi(13)))))),l.addAssign(vi(a)),d.addAssign(vi(o)),c.addAssign(vi(n)),Dm(l,d,c),l.addAssign(vi(i)),Pm(l,d,c)})),Wm=mi((([e,t,s,r,i])=>{const n=_i(i).toVar(),o=_i(r).toVar(),a=_i(s).toVar(),u=_i(t).toVar(),l=_i(e).toVar(),d=vi(vi(5)).toVar(),c=vi().toVar(),h=vi().toVar(),p=vi().toVar();return c.assign(h.assign(p.assign(vi(_i(3735928559)).add(d.shiftLeft(vi(2)).add(vi(13)))))),c.addAssign(vi(l)),h.addAssign(vi(u)),p.addAssign(vi(a)),Dm(c,h,p),c.addAssign(vi(o)),h.addAssign(vi(n)),Pm(c,h,p)})),jm=bc([km,zm,$m,Hm,Wm]),Xm=mi((([e,t])=>{const s=_i(t).toVar(),r=_i(e).toVar(),i=vi(jm(r,s)).toVar(),n=Fi().toVar();return n.x.assign(i.bitAnd(_i(255))),n.y.assign(i.shiftRight(_i(8)).bitAnd(_i(255))),n.z.assign(i.shiftRight(_i(16)).bitAnd(_i(255))),n})),qm=mi((([e,t,s])=>{const r=_i(s).toVar(),i=_i(t).toVar(),n=_i(e).toVar(),o=vi(jm(n,i,r)).toVar(),a=Fi().toVar();return a.x.assign(o.bitAnd(_i(255))),a.y.assign(o.shiftRight(_i(8)).bitAnd(_i(255))),a.z.assign(o.shiftRight(_i(16)).bitAnd(_i(255))),a})),Ym=bc([Xm,qm]),Km=mi((([e])=>{const t=Ai(e).toVar(),s=_i().toVar(),r=_i().toVar(),i=Ni(Tm(t.x,s)).toVar(),n=Ni(Tm(t.y,r)).toVar(),o=Ni(Gm(i)).toVar(),a=Ni(Gm(n)).toVar(),u=Ni(bm(Rm(jm(s,r),i,n),Rm(jm(s.add(_i(1)),r),i.sub(1),n),Rm(jm(s,r.add(_i(1))),i,n.sub(1)),Rm(jm(s.add(_i(1)),r.add(_i(1))),i.sub(1),n.sub(1)),o,a)).toVar();return Om(u)})),Qm=mi((([e])=>{const t=wi(e).toVar(),s=_i().toVar(),r=_i().toVar(),i=_i().toVar(),n=Ni(Tm(t.x,s)).toVar(),o=Ni(Tm(t.y,r)).toVar(),a=Ni(Tm(t.z,i)).toVar(),u=Ni(Gm(n)).toVar(),l=Ni(Gm(o)).toVar(),d=Ni(Gm(a)).toVar(),c=Ni(vm(Rm(jm(s,r,i),n,o,a),Rm(jm(s.add(_i(1)),r,i),n.sub(1),o,a),Rm(jm(s,r.add(_i(1)),i),n,o.sub(1),a),Rm(jm(s.add(_i(1)),r.add(_i(1)),i),n.sub(1),o.sub(1),a),Rm(jm(s,r,i.add(_i(1))),n,o,a.sub(1)),Rm(jm(s.add(_i(1)),r,i.add(_i(1))),n.sub(1),o,a.sub(1)),Rm(jm(s,r.add(_i(1)),i.add(_i(1))),n,o.sub(1),a.sub(1)),Rm(jm(s.add(_i(1)),r.add(_i(1)),i.add(_i(1))),n.sub(1),o.sub(1),a.sub(1)),u,l,d)).toVar();return Um(c)})),Zm=bc([Km,Qm]),Jm=mi((([e])=>{const t=Ai(e).toVar(),s=_i().toVar(),r=_i().toVar(),i=Ni(Tm(t.x,s)).toVar(),n=Ni(Tm(t.y,r)).toVar(),o=Ni(Gm(i)).toVar(),a=Ni(Gm(n)).toVar(),u=wi(bm(wm(Ym(s,r),i,n),wm(Ym(s.add(_i(1)),r),i.sub(1),n),wm(Ym(s,r.add(_i(1))),i,n.sub(1)),wm(Ym(s.add(_i(1)),r.add(_i(1))),i.sub(1),n.sub(1)),o,a)).toVar();return Om(u)})),ef=mi((([e])=>{const t=wi(e).toVar(),s=_i().toVar(),r=_i().toVar(),i=_i().toVar(),n=Ni(Tm(t.x,s)).toVar(),o=Ni(Tm(t.y,r)).toVar(),a=Ni(Tm(t.z,i)).toVar(),u=Ni(Gm(n)).toVar(),l=Ni(Gm(o)).toVar(),d=Ni(Gm(a)).toVar(),c=wi(vm(wm(Ym(s,r,i),n,o,a),wm(Ym(s.add(_i(1)),r,i),n.sub(1),o,a),wm(Ym(s,r.add(_i(1)),i),n,o.sub(1),a),wm(Ym(s.add(_i(1)),r.add(_i(1)),i),n.sub(1),o.sub(1),a),wm(Ym(s,r,i.add(_i(1))),n,o,a.sub(1)),wm(Ym(s.add(_i(1)),r,i.add(_i(1))),n.sub(1),o,a.sub(1)),wm(Ym(s,r.add(_i(1)),i.add(_i(1))),n,o.sub(1),a.sub(1)),wm(Ym(s.add(_i(1)),r.add(_i(1)),i.add(_i(1))),n.sub(1),o.sub(1),a.sub(1)),u,l,d)).toVar();return Um(c)})),tf=bc([Jm,ef]),sf=mi((([e])=>{const t=Ni(e).toVar(),s=_i(fm(t)).toVar();return Vm(jm(s))})),rf=mi((([e])=>{const t=Ai(e).toVar(),s=_i(fm(t.x)).toVar(),r=_i(fm(t.y)).toVar();return Vm(jm(s,r))})),nf=mi((([e])=>{const t=wi(e).toVar(),s=_i(fm(t.x)).toVar(),r=_i(fm(t.y)).toVar(),i=_i(fm(t.z)).toVar();return Vm(jm(s,r,i))})),of=mi((([e])=>{const t=Oi(e).toVar(),s=_i(fm(t.x)).toVar(),r=_i(fm(t.y)).toVar(),i=_i(fm(t.z)).toVar(),n=_i(fm(t.w)).toVar();return Vm(jm(s,r,i,n))})),af=bc([sf,rf,nf,of]),uf=mi((([e])=>{const t=Ni(e).toVar(),s=_i(fm(t)).toVar();return wi(Vm(jm(s,_i(0))),Vm(jm(s,_i(1))),Vm(jm(s,_i(2))))})),lf=mi((([e])=>{const t=Ai(e).toVar(),s=_i(fm(t.x)).toVar(),r=_i(fm(t.y)).toVar();return wi(Vm(jm(s,r,_i(0))),Vm(jm(s,r,_i(1))),Vm(jm(s,r,_i(2))))})),df=mi((([e])=>{const t=wi(e).toVar(),s=_i(fm(t.x)).toVar(),r=_i(fm(t.y)).toVar(),i=_i(fm(t.z)).toVar();return wi(Vm(jm(s,r,i,_i(0))),Vm(jm(s,r,i,_i(1))),Vm(jm(s,r,i,_i(2))))})),cf=mi((([e])=>{const t=Oi(e).toVar(),s=_i(fm(t.x)).toVar(),r=_i(fm(t.y)).toVar(),i=_i(fm(t.z)).toVar(),n=_i(fm(t.w)).toVar();return wi(Vm(jm(s,r,i,n,_i(0))),Vm(jm(s,r,i,n,_i(1))),Vm(jm(s,r,i,n,_i(2))))})),hf=bc([uf,lf,df,cf]),pf=mi((([e,t,s,r])=>{const i=Ni(r).toVar(),n=Ni(s).toVar(),o=_i(t).toVar(),a=wi(e).toVar(),u=Ni(0).toVar(),l=Ni(1).toVar();return _c({start:_i(0),end:o},(({i:e})=>{u.addAssign(l.mul(Zm(a))),l.mulAssign(i),a.mulAssign(n)})),u})),gf=mi((([e,t,s,r])=>{const i=Ni(r).toVar(),n=Ni(s).toVar(),o=_i(t).toVar(),a=wi(e).toVar(),u=wi(0).toVar(),l=Ni(1).toVar();return _c({start:_i(0),end:o},(({i:e})=>{u.addAssign(l.mul(tf(a))),l.mulAssign(i),a.mulAssign(n)})),u})),mf=mi((([e,t,s,r])=>{const i=Ni(r).toVar(),n=Ni(s).toVar(),o=_i(t).toVar(),a=wi(e).toVar();return Ai(pf(a,o,n,i),pf(a.add(wi(_i(19),_i(193),_i(17))),o,n,i))})),ff=mi((([e,t,s,r])=>{const i=Ni(r).toVar(),n=Ni(s).toVar(),o=_i(t).toVar(),a=wi(e).toVar(),u=wi(gf(a,o,n,i)).toVar(),l=Ni(pf(a.add(wi(_i(19),_i(193),_i(17))),o,n,i)).toVar();return Oi(u,l)})),Tf=mi((([e,t,s,r,i,n,o])=>{const a=_i(o).toVar(),u=Ni(n).toVar(),l=_i(i).toVar(),d=_i(r).toVar(),c=_i(s).toVar(),h=_i(t).toVar(),p=Ai(e).toVar(),g=wi(hf(Ai(h.add(d),c.add(l)))).toVar(),m=Ai(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Ai(Ai(Ni(h),Ni(c)).add(m)).toVar(),T=Ai(f.sub(p)).toVar();return xi(a.equal(_i(2)),(()=>Yo(T.x).add(Yo(T.y)))),xi(a.equal(_i(3)),(()=>la(Yo(T.x),Yo(T.y)))),ma(T,T)})),xf=mi((([e,t,s,r,i,n,o,a,u])=>{const l=_i(u).toVar(),d=Ni(a).toVar(),c=_i(o).toVar(),h=_i(n).toVar(),p=_i(i).toVar(),g=_i(r).toVar(),m=_i(s).toVar(),f=_i(t).toVar(),T=wi(e).toVar(),x=wi(hf(wi(f.add(p),m.add(h),g.add(c)))).toVar();x.subAssign(.5),x.mulAssign(d),x.addAssign(.5);const y=wi(wi(Ni(f),Ni(m),Ni(g)).add(x)).toVar(),b=wi(y.sub(T)).toVar();return xi(l.equal(_i(2)),(()=>Yo(b.x).add(Yo(b.y).add(Yo(b.z))))),xi(l.equal(_i(3)),(()=>la(la(Yo(b.x),Yo(b.y)),Yo(b.z)))),ma(b,b)})),yf=bc([Tf,xf]),bf=mi((([e,t,s])=>{const r=_i(s).toVar(),i=Ni(t).toVar(),n=Ai(e).toVar(),o=_i().toVar(),a=_i().toVar(),u=Ai(Tm(n.x,o),Tm(n.y,a)).toVar(),l=Ni(1e6).toVar();return _c({start:-1,end:_i(1),name:"x",condition:"<="},(({x:e})=>{_c({start:-1,end:_i(1),name:"y",condition:"<="},(({y:t})=>{const s=Ni(yf(u,e,t,o,a,i,r)).toVar();l.assign(ua(l,s))}))})),xi(r.equal(_i(0)),(()=>{l.assign(Do(l))})),l})),Nf=mi((([e,t,s])=>{const r=_i(s).toVar(),i=Ni(t).toVar(),n=Ai(e).toVar(),o=_i().toVar(),a=_i().toVar(),u=Ai(Tm(n.x,o),Tm(n.y,a)).toVar(),l=Ai(1e6,1e6).toVar();return _c({start:-1,end:_i(1),name:"x",condition:"<="},(({x:e})=>{_c({start:-1,end:_i(1),name:"y",condition:"<="},(({y:t})=>{const s=Ni(yf(u,e,t,o,a,i,r)).toVar();xi(s.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(s)})).elseif(s.lessThan(l.y),(()=>{l.y.assign(s)}))}))})),xi(r.equal(_i(0)),(()=>{l.assign(Do(l))})),l})),_f=mi((([e,t,s])=>{const r=_i(s).toVar(),i=Ni(t).toVar(),n=Ai(e).toVar(),o=_i().toVar(),a=_i().toVar(),u=Ai(Tm(n.x,o),Tm(n.y,a)).toVar(),l=wi(1e6,1e6,1e6).toVar();return _c({start:-1,end:_i(1),name:"x",condition:"<="},(({x:e})=>{_c({start:-1,end:_i(1),name:"y",condition:"<="},(({y:t})=>{const s=Ni(yf(u,e,t,o,a,i,r)).toVar();xi(s.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(s)})).elseif(s.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(s)})).elseif(s.lessThan(l.z),(()=>{l.z.assign(s)}))}))})),xi(r.equal(_i(0)),(()=>{l.assign(Do(l))})),l})),vf=mi((([e,t,s])=>{const r=_i(s).toVar(),i=Ni(t).toVar(),n=wi(e).toVar(),o=_i().toVar(),a=_i().toVar(),u=_i().toVar(),l=wi(Tm(n.x,o),Tm(n.y,a),Tm(n.z,u)).toVar(),d=Ni(1e6).toVar();return _c({start:-1,end:_i(1),name:"x",condition:"<="},(({x:e})=>{_c({start:-1,end:_i(1),name:"y",condition:"<="},(({y:t})=>{_c({start:-1,end:_i(1),name:"z",condition:"<="},(({z:s})=>{const n=Ni(yf(l,e,t,s,o,a,u,i,r)).toVar();d.assign(ua(d,n))}))}))})),xi(r.equal(_i(0)),(()=>{d.assign(Do(d))})),d})),Sf=bc([bf,vf]),Af=mi((([e,t,s])=>{const r=_i(s).toVar(),i=Ni(t).toVar(),n=wi(e).toVar(),o=_i().toVar(),a=_i().toVar(),u=_i().toVar(),l=wi(Tm(n.x,o),Tm(n.y,a),Tm(n.z,u)).toVar(),d=Ai(1e6,1e6).toVar();return _c({start:-1,end:_i(1),name:"x",condition:"<="},(({x:e})=>{_c({start:-1,end:_i(1),name:"y",condition:"<="},(({y:t})=>{_c({start:-1,end:_i(1),name:"z",condition:"<="},(({z:s})=>{const n=Ni(yf(l,e,t,s,o,a,u,i,r)).toVar();xi(n.lessThan(d.x),(()=>{d.y.assign(d.x),d.x.assign(n)})).elseif(n.lessThan(d.y),(()=>{d.y.assign(n)}))}))}))})),xi(r.equal(_i(0)),(()=>{d.assign(Do(d))})),d})),Rf=bc([Nf,Af]),Ef=mi((([e,t,s])=>{const r=_i(s).toVar(),i=Ni(t).toVar(),n=wi(e).toVar(),o=_i().toVar(),a=_i().toVar(),u=_i().toVar(),l=wi(Tm(n.x,o),Tm(n.y,a),Tm(n.z,u)).toVar(),d=wi(1e6,1e6,1e6).toVar();return _c({start:-1,end:_i(1),name:"x",condition:"<="},(({x:e})=>{_c({start:-1,end:_i(1),name:"y",condition:"<="},(({y:t})=>{_c({start:-1,end:_i(1),name:"z",condition:"<="},(({z:s})=>{const n=Ni(yf(l,e,t,s,o,a,u,i,r)).toVar();xi(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)}))}))}))})),xi(r.equal(_i(0)),(()=>{d.assign(Do(d))})),d})),Cf=bc([_f,Ef]);gm.setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),mm.setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),fm.setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),xm.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"}]}),ym.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"}]}),Nm.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"}]}),_m.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"}]}),Sm.setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Am.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"}]}),Em.setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Cm.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"}]}),Mm.setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Fm.setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Bm.setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),Lm.setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),Im.setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),Pm.setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Vm.setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),Gm.setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),km.setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),zm.setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),$m.setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Hm.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"}]}),Wm.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"}]}),Xm.setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),qm.setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Km.setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Qm.setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]}),Jm.setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),ef.setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),sf.setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),rf.setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),nf.setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),of.setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]}),uf.setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),lf.setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),df.setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),cf.setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]}),pf.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"}]}),gf.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"}]}),mf.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"}]}),ff.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"}]}),Tf.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"}]}),xf.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"}]}),bf.setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Nf.setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),_f.setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),vf.setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Af.setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Ef.setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]});const wf=mi((([e])=>{const t=wi(e).toVar(),s=Ni(t.x).toVar(),r=Ni(t.y).toVar(),i=Ni(t.z).toVar();xi(r.lessThan(1e-4),(()=>wi(i,i,i))).else((()=>{s.assign(co(6,s.sub(Vo(s))));const e=_i(ia(s)).toVar(),t=Ni(s.sub(Ni(e))).toVar(),n=Ni(i.mul(lo(1,r))).toVar(),o=Ni(i.mul(lo(1,r.mul(t)))).toVar(),a=Ni(i.mul(lo(1,r.mul(lo(1,t))))).toVar();return xi(e.equal(_i(0)),(()=>wi(i,a,n))).elseif(e.equal(_i(1)),(()=>wi(o,i,n))).elseif(e.equal(_i(2)),(()=>wi(n,i,a))).elseif(e.equal(_i(3)),(()=>wi(n,o,i))).elseif(e.equal(_i(4)),(()=>wi(a,n,i))),wi(i,n,o)}))})),Mf=mi((([e])=>{const t=wi(e).toVar(),s=Ni(t.x).toVar(),r=Ni(t.y).toVar(),i=Ni(t.z).toVar(),n=Ni(ua(s,ua(r,i))).toVar(),o=Ni(la(s,la(r,i))).toVar(),a=Ni(o.sub(n)).toVar(),u=Ni().toVar(),l=Ni().toVar(),d=Ni().toVar();return d.assign(o),xi(o.greaterThan(0),(()=>{l.assign(a.div(o))})).else((()=>{l.assign(0)})),xi(l.lessThanEqual(0),(()=>{u.assign(0)})).else((()=>{xi(s.greaterThanEqual(o),(()=>{u.assign(r.sub(i).div(a))})).elseif(r.greaterThanEqual(o),(()=>{u.assign(uo(2,i.sub(s).div(a)))})).else((()=>{u.assign(uo(4,s.sub(r).div(a)))})),u.mulAssign(1/6),xi(u.lessThan(0),(()=>{u.addAssign(1)}))})),wi(u,l,d)}));wf.setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),Mf.setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]});const Ff=mi((([e])=>{const t=wi(e).toVar(),s=Bi(To(t,wi(.04045))).toVar(),r=wi(t.div(12.92)).toVar(),i=wi(Ta(la(t.add(wi(.055)),wi(0)).div(1.055),wi(2.4))).toVar();return va(r,i,s)}));Ff.setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]});const Bf=(e,t)=>{e=Ni(e),t=Ni(t);const s=Ai(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Ea(e.sub(s),e.add(s),t)},Of=(e,t,s,r)=>va(e,t,s[r].clamp()),Lf=(e,t,s=io())=>Of(e,t,s,"x"),Uf=(e,t,s=io())=>Of(e,t,s,"y"),If=(e,t,s,r,i)=>va(e,t,Bf(s,r[i])),Df=(e,t,s,r=io())=>If(e,t,s,r,"x"),Pf=(e,t,s,r=io())=>If(e,t,s,r,"y"),Vf=(e=1,t=0,s=io())=>s.mul(e).add(t),Gf=(e,t=1)=>(e=Ni(e)).abs().pow(t).mul(e.sign()),kf=(e,t=1,s=.5)=>Ni(e).sub(s).mul(t).add(s),zf=(e=io(),t=1,s=0)=>Zm(e.convert("vec2|vec3")).mul(t).add(s),$f=(e=io(),t=1,s=0)=>tf(e.convert("vec2|vec3")).mul(t).add(s),Hf=(e=io(),t=1,s=0)=>{e=e.convert("vec2|vec3");return Oi(tf(e),Zm(e.add(Ai(19,73)))).mul(t).add(s)},Wf=(e=io(),t=1)=>Sf(e.convert("vec2|vec3"),t,_i(1)),jf=(e=io(),t=1)=>Rf(e.convert("vec2|vec3"),t,_i(1)),Xf=(e=io(),t=1)=>Cf(e.convert("vec2|vec3"),t,_i(1)),qf=(e=io())=>af(e.convert("vec2|vec3")),Yf=(e=io(),t=3,s=2,r=.5,i=1)=>pf(e,_i(t),s,r).mul(i),Kf=(e=io(),t=3,s=2,r=.5,i=1)=>mf(e,_i(t),s,r).mul(i),Qf=(e=io(),t=3,s=2,r=.5,i=1)=>gf(e,_i(t),s,r).mul(i),Zf=(e=io(),t=3,s=2,r=.5,i=1)=>ff(e,_i(t),s,r).mul(i);function Jf(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function eT(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}class tT{constructor(){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparent=[],this.lightsNode=new Wl([]),this.lightsArray=[],this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparent.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,r,i,n){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:r,renderOrder:e.renderOrder,z:i,group:n},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=r,o.renderOrder=e.renderOrder,o.z=i,o.group=n),this.renderItemsIndex++,o}push(e,t,s,r,i,n){const o=this.getNextRenderItem(e,t,s,r,i,n);!0===e.occlusionTest&&this.occlusionQueryCount++,(!0===s.transparent?this.transparent:this.opaque).push(o)}unshift(e,t,s,r,i,n){const o=this.getNextRenderItem(e,t,s,r,i,n);(!0===s.transparent?this.transparent:this.opaque).unshift(o)}pushLight(e){this.lightsArray.push(e)}getLightsNode(){return this.lightsNode.fromLights(this.lightsArray)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Jf),this.transparent.length>1&&this.transparent.sort(t||eT)}finish(){this.lightsNode.fromLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,l=a.height>>t;let d=e.depthTexture||i[t],c=!1;void 0===d&&(d=new b,d.format=be,d.type=Ne,d.image.width=u,d.image.height=l,i[t]=d),s.width===a.width&&a.height===s.height||(c=!0,d.needsUpdate=!0,d.image.width=u,d.image.height=l),s.width=a.width,s.height=a.height,s.textures=o,s.depthTexture=d,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.sampleCount!==r&&(c=!0,d.needsUpdate=!0,s.sampleCount=r);const h={sampleCount:r};for(let e=0;e{if(e.removeEventListener("dispose",t),void 0!==o)for(let e=0;e0){const r=e.image;if(void 0===r);else if(!1===r.complete);else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=r;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(i.createTexture(e,t),s.isDefaultTexture=!1),i.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),s.isDefaultTexture=!0}if(!0!==s.initialized){s.initialized=!0,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=oT){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),t.width=s.width,t.height=s.height,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let r;return r=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,s)))+1,r}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==N&&e.minFilter!==D)}isEnvironmentTexture(e){const t=e.mapping;return t===_e||t===ve||t===Se||t===Ae}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class uT extends r{constructor(e,t,s,r=1){super(e,t,s),this.a=r}set(e,t,s,r=1){return this.a=r,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}const lT=new uT;class dT extends Vs{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const r=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)r._clearColor.getRGB(lT,this.renderer.currentColorSpace),lT.a=r._clearColor.a;else if(!0===i.isColor)i.getRGB(lT,this.renderer.currentColorSpace),lT.a=1,n=!0;else if(!0===i.isNode){const s=this.get(e),n=i;lT.copy(r._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=pn(Oi(n),{getUV:()=>Eu,getTextureLevel:()=>xh}).mul(yh);let t=pl();t=t.setZ(t.w);const r=new Od;r.side=O,r.depthTest=!1,r.depthWrite=!1,r.fog=!1,r.vertexNode=t,r.fragmentNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new U(new Re(1,32,32),r),o.frustumCulled=!1,o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=Oi(n),o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null)}if(!0===r.autoClear||!0===n){lT.multiplyScalar(lT.a);const e=s.clearColorValue;e.r=lT.r,e.g=lT.g,e.b=lT.b,e.a=lT.a,s.depthClearValue=r._clearDepth,s.stencilClearValue=r._clearStencil,s.clearColor=!0===r.autoClearColor,s.clearDepth=!0===r.autoClearDepth,s.clearStencil=!0===r.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}class cT{constructor(e,t,s,r,i,n,o){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.nodeAttributes=r,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=o,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){let s=t;!0!==t.shared&&(s=t.clone()),e.push(s)}return e}}class hT extends Vs{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new ac,this.nodeBuilderCache=new Map,this.callHashCache=new Us,this.groupsData=new Us}updateGroup(e){const t=e.groupNode,s=t.name;if(s===Er.name)return!0;if(s===Rr.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===Ar.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}const r=[t,e];let i=this.groupsData.get(r);return void 0===i&&this.groupsData.set(r,i={}),i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:r}=this,i=this.getForRenderCacheKey(e);if(s=r.get(i),void 0===s){const t=this.backend.createNodeBuilder(e.object,this.renderer,e.scene);t.material=e.material,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.toneMappingNode=this.getToneMappingNode(),t.build(),s=this._createNodeBuilderState(t),r.set(i,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const r=this.backend.createNodeBuilder(e,this.renderer);r.build(),s=this._createNodeBuilderState(r),t.nodeBuilderState=r}return s}_createNodeBuilderState(e){return new cT(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getToneMappingNode(){return!1===this.isToneMappingState?null:this.renderer.toneMappingNode||this.get(this.renderer).toneMappingNode||null}getCacheKey(e,t){const s=[e,t],r=this.renderer.info.calls;let i=this.callHashCache.get(s);if(void 0===i||i.callId!==r){const n=this.getEnvironmentNode(e),o=this.getFogNode(e),a=this.getToneMappingNode(),u=[];t&&u.push(t.getCacheKey()),n&&u.push(n.getCacheKey()),o&&u.push(o.getCacheKey()),a&&u.push(a.getCacheKey()),i={callId:r,cacheKey:u.join(",")},this.callHashCache.set(s,i)}return i.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e),this.updateToneMapping()}get isToneMappingState(){const e=this.renderer.getRenderTarget();return!e||!e.isCubeRenderTarget}updateToneMapping(){const e=this.renderer,t=this.get(e),s=e.toneMapping;if(this.isToneMappingState&&s!==j){if(t.toneMapping!==s){const r=t.rendererToneMappingNode||dp(s,qa("toneMappingExposure","float",e));r.toneMapping=s,t.rendererToneMappingNode=r,t.toneMappingNode=r,t.toneMapping=s}}else delete t.toneMappingNode,delete t.toneMapping}updateBackground(e){const t=this.get(e),s=e.background;if(s){if(t.background!==s){let e=null;if(!0===s.isCubeTexture)e=Gl(s,Eu);else if(!0===s.isTexture){let t=null;s.mapping===_e||s.mapping===ve?(t=Jl(),s.flipY=!1):t=pd,e=Ha(s,t).setUpdateMatrix(!0)}else s.isColor;t.backgroundNode=e,t.background=s}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;s.isFogExp2?e=zp(qa("color","color",s),qa("density","float",s)):s.isFog&&(e=Gp(qa("color","color",s),qa("near","float",s),qa("far","float",s))),t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){let e=null;!0===s.isCubeTexture?e=Gl(s):!0===s.isTexture&&(e=Ha(s)),t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,r=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=r,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}updateBefore(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateBeforeNodes)t.updateBeforeNode(e)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}dispose(){super.dispose(),this.nodeFrame=new ac,this.nodeBuilderCache=new Map}}const pT=new I,gT=new i,mT=new o,fT=new Ee,TT=new u,xT=new n;class yT{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:r=!0}=t;this.domElement=e.getDomElement(),this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=s,this.outputColorSpace=h,this.toneMapping=j,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=!0,this.stencil=!0,this.info=new qs,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new o(0,0,this._width,this._height),this._scissor=new o(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null;const i=!0===this.alpha?0:1;this._clearColor=new uT(0,0,0,i),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._initialized=!1,this._initPromise=null,this.shadowMap={enabled:!1,type:null},this.xr={enabled:!1}}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)=>{const s=this.backend;try{await s.init(this)}catch(e){return void t(e)}this._nodes=new hT(this,s),this._animation=new Ls(this._nodes,this.info),this._attributes=new Hs(s),this._background=new dT(this,this._nodes),this._geometries=new Xs(this._attributes,this.info),this._textures=new aT(s,this.info),this._pipelines=new er(s,this._nodes),this._bindings=new tr(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Ps(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new sT,this._renderContexts=new nT,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compile(){}async render(e,t){!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,r=s.renderId,i=this._currentRenderContext,n=this._currentRenderObjectFunction,o=!0===e.isScene?e:pT,a=this._renderTarget,u=this._renderContexts.get(e,t,a),l=this._activeCubeFace,d=this._activeMipmapLevel;this._currentRenderContext=u,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,s.renderId=this.info.calls;const c=this.coordinateSystem;t.coordinateSystem!==c&&(t.coordinateSystem=c,t.updateProjectionMatrix()),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===this.info.autoReset&&this.info.reset();let h=this._viewport,p=this._scissor,g=this._pixelRatio;null!==a&&(h=a.viewport,p=a.scissor,g=1),this.getDrawingBufferSize(gT),mT.set(0,0,gT.width,gT.height);const m=void 0===h.minDepth?0:h.minDepth,f=void 0===h.maxDepth?1:h.maxDepth;u.viewportValue.copy(h).multiplyScalar(g).floor(),u.viewportValue.width>>=d,u.viewportValue.height>>=d,u.viewportValue.minDepth=m,u.viewportValue.maxDepth=f,u.viewport=!1===u.viewportValue.equals(mT),u.scissorValue.copy(p).multiplyScalar(g).floor(),u.scissor=this._scissorTest&&!1===u.scissorValue.equals(mT),u.scissorValue.width>>=d,u.scissorValue.height>>=d,u.depth=this.depth,u.stencil=this.stencil,o.onBeforeRender(this,e,t,a),TT.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),fT.setFromProjectionMatrix(TT,c);const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==a){this._textures.updateRenderTarget(a,d);const e=this._textures.get(a);u.textures=e.textures,u.depthTexture=e.depthTexture,u.width=e.width,u.height=e.height,u.renderTarget=a}else u.textures=null,u.depthTexture=null,u.width=this.domElement.width,u.height=this.domElement.height;u.width>>=d,u.height>>=d,u.activeCubeFace=l,u.activeMipmapLevel=d,u.occlusionQueryCount=T.occlusionQueryCount,this._nodes.updateScene(o),this._background.update(o,T,u),this.backend.beginRender(u);const x=T.opaque,y=T.transparent,b=T.lightsNode;x.length>0&&this._renderObjects(x,t,o,b),y.length>0&&this._renderObjects(y,t,o,b),this.backend.finishRender(u),s.renderId=r,this._currentRenderContext=i,this._currentRenderObjectFunction=n,o.onAfterRender(this,e,t,a)}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)}getArrayBuffer(e){return this.getArrayBufferAsync(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.setSize(this._width,this._height,!1)}setDrawingBufferSize(e,t,s){this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,s=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,r){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,s,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,r,i=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,r),o.minDepth=i,o.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){let r=null;const i=this._renderTarget;null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i)),this.backend.clear(e,t,s,r)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}get currentColorSpace(){const e=this._renderTarget;if(null!==e){const t=e.texture;return(Array.isArray(t)?t[0]:t).colorSpace}return this.outputColorSpace}dispose(){this.info.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}async compute(e){!1===this._initialized&&await this.init();const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,t.renderId=this.info.calls;const r=this.backend,i=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const t of a){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e),t.onInit({renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=i.getForCompute(t,s);r.compute(e,t,s,a)}r.finishCompute(e),t.renderId=s}hasFeature(e){return this.backend.hasFeature(e)}copyFramebufferToTexture(e){const t=this._currentRenderContext;this._textures.updateTexture(e),this.backend.copyFramebufferToTexture(e,t)}readRenderTargetPixelsAsync(e,t,s,r,i){return this.backend.copyTextureToBuffer(e.texture,t,s,r,i)}_projectObject(e,t,s,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||fT.intersectsSprite(e)){!0===this.sortObjects&&xT.setFromMatrixPosition(e.matrixWorld).applyMatrix4(TT);const t=e.geometry,i=e.material;i.visible&&r.push(e,t,i,s,xT.z,null)}}else if(e.isLineLoop);else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||fT.intersectsObject(e))){const t=e.geometry,i=e.material;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),xT.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(TT)),Array.isArray(i)){const n=t.groups;for(let o=0,a=n.length;o0?i:"";t=`${s.name} {\n\t${r} ${e.name}[${n}];\n};\n`}else{t=`${this.getVectorType(e.type)} ${e.name};`,i=!0}const n=e.node.precision;if(null!==n&&(t=LT[n]+" "+t),i){t="\t"+t;const s=e.groupNode.name;(r[s]||(r[s]=[])).push(t)}else t="uniform "+t,s.push(t)}let i="";for(const t in r){const s=r[t];i+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return i+=s.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Me){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const r=s.array;!1==(r instanceof Uint32Array||r instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e){const e=this.getAttributesArray();let s=0;for(const r of e)t+=`layout( location = ${s++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){const t=[],s=e.getMemberTypes();for(let e=0;e0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${r.code}\n\t`,e===i&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${r.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${r.result};`)))}const n=e[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.flow=s}null!==this.material&&(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment))}getUniformFromNode(e,t,s,r=null){const i=super.getUniformFromNode(e,t,s,r),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){if("texture"===t)o=new FT(i.name,i.node),this.bindings[s].push(o);else if("cubeTexture"===t)o=new BT(i.name,i.node),this.bindings[s].push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`;const t=new AT(e.name,e.value);i.name=`buffer${e.id}`,this.bindings[s].push(t),o=t}else{const r=e.groupNode,n=r.name,a=this.uniformGroups[s]||(this.uniformGroups[s]={});let u=a[n];void 0===u&&(u=new CT(s+"_"+n,r),a[n]=u,this.bindings[s].push(u)),o=this.getNodeUniform(i,t),u.addUniform(o)}n.uniformGPU=o}return i}}let PT=null,VT=null,GT=null;class kT{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(e){}finish(e){}draw(e,t){}createProgram(e){}destroyProgram(e){}createBindings(e){}updateBindings(e){}createRenderPipeline(e){}createComputePipeline(e,t){}destroyPipeline(e){}needsRenderUpdate(e){}getRenderCacheKey(e){}createNodeBuilder(e){}createSampler(e){}createDefaultTexture(e){}createTexture(e){}copyTextureToBuffer(e,t,s,r,i){}createAttribute(e){}createIndexAttribute(e){}updateAttribute(e){}destroyAttribute(e){}getContext(){}updateSize(){}hasFeature(e){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.isInstancedMesh?t.count:1}getDrawingBufferSize(){return PT=PT||new i,this.renderer.getDrawingBufferSize(PT)}getScissor(){return VT=VT||new o,this.renderer.getScissor(VT)}getClearColor(){const e=this.renderer;return GT=GT||new uT,e.getClearColor(GT),GT.getRGB(GT,this.renderer.currentColorSpace),GT}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Fe(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${$} 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}delete(e){this.data.delete(e)}}class zT{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:r}=s,i=e.array,n=e.usage||r.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let u,l=a.bufferGPU;if(void 0===l&&(l=r.createBuffer(),r.bindBuffer(t,l),r.bufferData(t,i,n),r.bindBuffer(t,null),a.bufferGPU=l,a.bufferType=t,a.version=o.version),i instanceof Float32Array)u=r.FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=r.SHORT;else if(i instanceof Uint32Array)u=r.UNSIGNED_INT;else if(i instanceof Int32Array)u=r.INT;else if(i instanceof Int8Array)u=r.BYTE;else if(i instanceof Uint8Array)u=r.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=r.UNSIGNED_BYTE}s.set(e,{bufferGPU:l,type:u,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,isInteger:u===r.INT||u===r.UNSIGNED_INT||e.gpuType===Me})}updateAttribute(e){const t=this.backend,{gl:s}=t,r=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,r);else{for(let e=0,t=a.length;e{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void r();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(i)}()}))}}let qT,YT,KT,QT=!1;class ZT{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===QT&&(this._init(this.gl),QT=!0)}_init(e){qT={[Jt]:e.REPEAT,[es]:e.CLAMP_TO_EDGE,[ts]:e.MIRRORED_REPEAT},YT={[N]:e.NEAREST,[A]:e.NEAREST_MIPMAP_NEAREST,[ss]:e.NEAREST_MIPMAP_LINEAR,[D]:e.LINEAR,[rs]:e.LINEAR_MIPMAP_NEAREST,[S]:e.LINEAR_MIPMAP_LINEAR},KT={[is]:e.NEVER,[ns]:e.ALWAYS,[_]:e.LESS,[os]:e.LEQUAL,[as]:e.EQUAL,[us]:e.GEQUAL,[ls]:e.GREATER,[ds]:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===N||e===A||e===ss?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D,s}getInternalFormat(e,t,s,r,i=!1){const{gl:n,extensions:o}=this;if(null!==e&&void 0!==n[e])return n[e];let a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=r===h&&!1===i?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_INT&&(a=n.DEPTH24_STENCIL8),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:r}=this;s.texParameteri(e,s.TEXTURE_WRAP_S,qT[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,qT[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,qT[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,YT[t.magFilter]);const i=t.minFilter===D?S:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,YT[i]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,KT[t.compareFunction])),!0===r.has("EXT_texture_filter_anisotropic")){if(t.magFilter===N)return;if(t.minFilter!==ss&&t.minFilter!==S)return;if(t.type===x&&!1===r.has("OES_texture_float_linear"))return;t.anisotropy}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:r}=this,i=this.getGLTextureType(e);let n=r[i];void 0===n&&(n=t.createTexture(),s.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),r[i]=n),s.set(e,{textureGPU:n,glTextureType:i,isDefault:!0})}createTexture(e,t){const{gl:s,backend:r}=this,{levels:i,width:n,height:o,depth:a}=t,u=r.utils.convert(e.format,e.colorSpace),l=r.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.colorSpace,e.isVideoTexture),c=s.createTexture(),h=this.getGLTextureType(e);r.state.bindTexture(h,c),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,e.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,e.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE),this.setTextureParameters(h,e),e.isDataArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,i,d,n,o,a):e.isVideoTexture||s.texStorage2D(h,i,d,n,o),r.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}updateTexture(e,t){const{gl:s}=this,{width:r,height:i}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:u,glInternalFormat:l}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const d=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(o,n),e.isCompressedTexture){const r=e.mipmaps;for(let i=0;i0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,i,t,u,l)):s.renderbufferStorage(s.RENDERBUFFER,t,u,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(i>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,i,s.DEPTH24_STENCIL8,u,l):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,u,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,r,i){const{backend:n,gl:o}=this,{textureGPU:a,glFormat:u,glType:l}=this.backend.get(e),d=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,d),o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,a,0);const c=this._getTypedArrayType(l),h=r*i,p=h*this._getBytesPerTexel(u),g=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.bufferData(o.PIXEL_PACK_BUFFER,p,o.STREAM_READ),o.readPixels(t,s,r,i,u,l,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await n.utils._clientWaitAsync();const m=new c(h);return o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,m),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(d),m}_getTypedArrayType(e){const{gl:t}=this;return e===t.UNSIGNED_BYTE?Uint8Array:e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT?Uint16Array:e===t.UNSIGNED_INT?Uint32Array:e===t.UNSIGNED_FLOAT?Float32Array:void 0}_getBytesPerTexel(e){const{gl:t}=this;return e===t.RGBA?4:e===t.RGB?3:e===t.ALPHA?1:void 0}}class JT{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)),t}has(e){return this.availableExtensions.includes(e)}}class ex{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const tx={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"};class sx extends kT{constructor(e={}){super(e),this.isWebGLBackend=!0}init(e){super.init(e);const t=this.parameters,s=void 0!==t.context?t.context:e.domElement.getContext("webgl2");this.gl=s,this.extensions=new JT(this),this.capabilities=new ex(this),this.attributeUtils=new zT(this),this.textureUtils=new ZT(this),this.state=new jT(this),this.utils=new XT(this),this.extensions.get("EXT_color_buffer_float"),this._currentContext=null}get coordinateSystem(){return cs}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.gl}beginRender(e){const{gl:t}=this,s=this.get(e);s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e),e.viewport?this.updateViewport(e):t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight);const r=e.occlusionQueryCount;r>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(r),s.occlusionQueryObjects=new Array(r),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,r=this.get(e).previousContext,i=e.textures;if(null!==i)for(let e=0;e0){const i=r.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,i),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n);for(let s=0;s0){if(n>this.get(e).occlusionQueryIndex){const{gl:e}=this;e.endQuery(e.ANY_SAMPLES_PASSED)}this.resolveOccludedAsync(e)}}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:r}=t;if(s&&r){const e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let o=0;for(let t=0;t0&&e.add(r[t]),s[t]=null,i.deleteQuery(n),o++))}o1?a.drawElementsInstanced(T,c.count,e.type,m,x):a.drawElements(T,c.count,e.type,m),t.update(h,s,1)}else{const e=p.attributes.position,s=g.count!==1/0?g.count:e.count;x>1?a.drawArraysInstanced(T,0,s,x):a.drawArrays(T,0,s),t.update(h,s,1)}a.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(e){return e.id}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,r,i){return this.textureUtils.copyTextureToBuffer(e,t,s,r,i)}createSampler(){}destroySampler(){}createNodeBuilder(e,t,s=null){return new DT(e,t,s)}createProgram(e){const t=this.gl,{stage:s,code:r}=e,i="vertex"===s?t.createShader(t.VERTEX_SHADER):t.createShader(t.FRAGMENT_SHADER);t.shaderSource(i,r),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(){}createRenderPipeline(e){const t=this.gl,s=e.pipeline,{fragmentProgram:r,vertexProgram:i}=s,n=t.createProgram(),o=this.get(r).shaderGPU,a=this.get(i).shaderGPU;t.attachShader(n,o),t.attachShader(n,a),t.linkProgram(n),t.getProgramParameter(n,t.LINK_STATUS),t.useProgram(n);const u=e.getBindings();for(const e of u){const s=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const r=t.getUniformBlockIndex(n,e.name);t.uniformBlockBinding(n,r,s)}else if(e.isSampledTexture){const r=t.getUniformLocation(n,e.name);t.uniform1i(r,s)}}const l=t.createVertexArray(),d=e.getIndex(),c=e.getAttributes();if(t.bindVertexArray(l),null!==d){const e=this.get(d);t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.bufferGPU)}for(let e=0;etx[t]===e)),s=this.extensions;for(let e=0;e0){if(void 0===h){const r=[];h=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,h);const i=[],l=e.textures;for(let s=0;s,\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({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:ax,stripIndexFormat:Sx},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:ax,stripIndexFormat:Sx},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const r=t.format,{width:i,height:n}=t.size,o=this.getTransferPipeline(r),a=this.getFlipYPipeline(r),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:Zx,baseArrayLayer:s}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:Zx,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,s)=>{const r=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:xx,storeOp:fx,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(o,l,d),h(a,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,s=0){const r=this.getTransferPipeline(t.format),i=this.device.createCommandEncoder({}),n=r.getBindGroupLayout(0);let o=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:Zx,baseArrayLayer:s});for(let a=1;a1&&(d=Math.pow(2,Math.floor(Math.log2(d))),2===d&&(d=4));const c=e.isRenderTargetTexture?1:d;let h=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(h|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&(h|=GPUTextureUsage.RENDER_ATTACHMENT);const p={label:e.name,size:{width:i,height:n,depthOrArrayLayers:o},mipLevelCount:a,sampleCount:c,dimension:u,format:l,usage:h};if(e.isVideoTexture){const t=e.source.data,s=new VideoFrame(t);p.size.width=s.displayWidth,p.size.height=s.displayHeight,s.close(),r.externalTexture=t}else{if(void 0===l)return this.createDefaultTexture(e);r.texture=s.device.createTexture(p)}if(e.isRenderTargetTexture&&d>1){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=d,r.msaaTexture=s.device.createTexture(e)}r.initialized=!0,r.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else this._generateMipmaps(t.texture,t.textureDescriptorGPU)}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.parameters.sampleCount,format:Ax.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!0){const s=this.backend,{width:r,height:i}=s.getDrawingBufferSize(),n=this.depthTexture,o=s.get(n).texture;let a,u;if(t?(a=be,u=Ne):e&&(a=E,u=R),void 0!==o){if(n.image.width===r&&n.image.height===i&&n.format===a&&n.type===u)return o;this.destroyTexture(n)}return n.name="depthBuffer",n.format=a,n.type=u,n.image.width=r,n.image.height=i,this.createTexture(n,{sampleCount:s.parameters.sampleCount,width:r,height:i}),s.get(n).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:r}=s;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture||e.isData3DTexture)this._copyBufferToTexture(t.image,s.texture,r,0,!1);else if(e.isDataArrayTexture)for(let e=0;e]*\s*([a-z_0-9]+)?/i,gy=/[a-z_0-9]+|<(.*?)>+/gi,my={f32:"float"};class fy extends um{constructor(e){const{type:t,inputs:s,name:r,inputsCode:i,blockCode:n}=(e=>{const t=(e=e.trim()).match(py);if(null!==t&&4===t.length){const s=t[2],r=[];let i=null;for(;null!==(i=gy.exec(s));)r.push(i);const n=[];let o=0;for(;o "+this.type:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class Ty extends am{parseFunction(e){return new fy(e)}}const xy=window.GPUShaderStage,yy={vertex:xy?xy.VERTEX:1,fragment:xy?xy.FRAGMENT:2,compute:xy?xy.COMPUTE:4},by={instance:!0},Ny={"^^":"threejs_xor"},_y={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",mat3:"mat3x3",imat3:"mat3x3",umat3:"mat3x3",bmat3:"mat3x3",mat4:"mat4x4",imat4:"mat4x4",umat4:"mat4x4",bmat4:"mat4x4"},vy={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"threejs_mod_float",mod_vec2:"threejs_mod_vec2",mod_vec3:"threejs_mod_vec3",mod_vec4:"threejs_mod_vec4",lessThanEqual:"threejs_lessThanEqual",greaterThan:"threejs_greaterThan",inversesqrt:"inverseSqrt",bitcast:"bitcast"},Sy={threejs_xor:new qn("\nfn threejs_xor( a : bool, b : bool ) -> bool {\n\n\treturn ( a || b ) && !( a && b );\n\n}\n"),lessThanEqual:new qn("\nfn threejs_lessThanEqual( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x <= b.x, a.y <= b.y, a.z <= b.z );\n\n}\n"),greaterThan:new qn("\nfn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x > b.x, a.y > b.y, a.z > b.z );\n\n}\n"),mod_float:new qn("fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new qn("fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new qn("fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new qn("fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),repeatWrapping:new qn("\nfn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n")};class Ay extends oc{constructor(e,t,s=null){super(e,t,new Ty,s),this.uniformGroups={},this.builtins={}}needsColorSpaceToLinear(e){return!0===e.isVideoTexture&&e.colorSpace!==w}_generateTextureSample(e,t,s,r,i=this.shaderStage){return"fragment"===i?r?`textureSample( ${t}, ${t}_sampler, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureLod(e,t,s)}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`}_generateTextureSampleLevel(e,t,s,r,i,n=this.shaderStage){return"fragment"===n&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r} )`:this.generateTextureLod(e,t,s,r)}generateTextureLod(e,t,s,r="0"){this._include("repeatWrapping");return`textureLoad( ${t}, threejs_repeatWrapping( ${s}, ${`textureDimensions( ${t}, 0 )`} ), i32( ${r} ) )`}generateTextureLoad(e,t,s,r,i="0u"){return r?`textureLoad( ${t}, ${s}, ${r}, ${i} )`:`textureLoad( ${t}, ${s}, ${i} )`}isUnfilterable(e){return!0===e.isDataTexture&&e.type===x}generateTexture(e,t,s,r,i=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,"0",r,i):this._generateTextureSample(e,t,s,r,i),n}generateTextureCompare(e,t,s,r,i,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r} )`}generateTextureLevel(e,t,s,r,i,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,r,i,n),o}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,s=e.type;return"texture"===s||"cubeTexture"===s?t:"buffer"===s||"storageBuffer"===s?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=Ny[e];return void 0!==t?(this._include(t),t):null}getUniformFromNode(e,t,s,r=null){const i=super.getUniformFromNode(e,t,s,r),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let r;const o=this.bindings[s];if("texture"===t||"cubeTexture"===t){let n=null;if("texture"===t?n=new FT(i.name,i.node):"cubeTexture"===t&&(n=new BT(i.name,i.node)),n.store=!0===e.isStoreTextureNode,n.setVisibility(yy[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new oy(`${i.name}_sampler`,i.node);e.setVisibility(yy[s]),o.push(e,n),r=[e,n]}else o.push(n),r=[n]}else if("buffer"===t||"storageBuffer"===t){const i=new("storageBuffer"===t?ay:AT)("NodeBuffer_"+e.id,e.value);i.setVisibility(yy[s]),o.push(i),r=i}else{const n=e.groupNode,a=n.name,u=this.uniformGroups[s]||(this.uniformGroups[s]={});let l=u[a];if(void 0===l&&(l=new CT(a,n),l.setVisibility(yy[s]),u[a]=l,o.push(l)),!0===e.isArrayUniformNode){r=[];for(const s of e.nodes){const e=this.getNodeUniform(s,t);e.boundary=_T(e.itemSize),e.itemSize=vT(e.itemSize),l.addUniform(e),r.push(e)}}else r=this.getNodeUniform(i,t),l.addUniform(r)}n.uniformGPU=r,"vertex"===s&&(this.bindingsOffset.fragment=o.length)}return i}isReference(e){return super.isReference(e)||"texture_2d"===e||"texture_cube"===e||"texture_depth_2d"===e||"texture_storage_2d"===e}getBuiltin(e,t,s,r=this.shaderStage){const i=this.builtins[r]||(this.builtins[r]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:s}),t}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(e.name+" : "+this.getType(e.type));return`fn ${t.name}( ${r.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n\treturn ${s.result};\n\n}`}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}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")}isFlipY(){return!1}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:r,type:i}of s.values())t.push(`@builtin( ${e} ) ${r} : ${i}`);return t.join(",\n\t")}getAttributes(e){const t=[];if("compute"===e&&this.getBuiltin("global_invocation_id","id","vec3","attribute"),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const s=this.getAttributesArray();for(let e=0,r=s.length;e`)}return t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,r=s.length;e","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,r=this.vars[e];for(let i=0;i";else if(!0===t.isDataArrayTexture)r="texture_2d_array";else if(!0===t.isDepthTexture)r="texture_depth_2d";else if(!0===t.isVideoTexture)r="texture_external";else if(!0===i.node.isStoreTextureNode){r="texture_storage_2d<"+hy(t)+", write>"}else r="texture_2d";s.push(`@binding( ${o++} ) @group( 0 ) var ${i.name} : ${r};`)}else if("buffer"===i.type||"storageBuffer"===i.type){const e=i.node,t=this.getType(e.bufferType),s=e.bufferCount,n=s>0?", "+s:"",a=`\t${i.name} : array< ${t}${n} >\n`,u=e.isStorageBufferNode?"storage,read_write":"uniform";r.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,a,u,o++))}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name,s=n[t]||(n[t]={index:o++,snippets:[]});if(!0===Array.isArray(i.value)){const t=i.value.length;s.snippets.push(`uniform ${e}[ ${t} ] ${i.name}`)}else s.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))}let a=s.join("\n");return a+=r.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};for(const t in e){const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t);let r="// code\n\n";r+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${u}\n\t`),r+=`${i.code}\n\t`,e===n&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(a)s.returnType=o.nodeType,r+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;\n\n",r+=`output.color = ${i.result};\n\n\treturn output;`}}s.flow=r}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return _y[e]||e}isAvailable(e){return!0===by[e]}_getWGSLMethod(e){return void 0!==Sy[e]&&this._include(e),vy[e]}_include(e){const t=Sy[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\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\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// system\nvar instanceIndex : u32;\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x;\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,s,r=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${r} ) @group( ${i} )\nvar<${s}> ${e} : ${n};`}}class Ry{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=Ax.Depth24PlusStencil8:e.depth&&(t=Ax.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).texture.format}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):Ax.BGRA8Unorm,t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?rx:e.isLineSegments||e.isMesh&&!0===t.wireframe?ix:e.isLine?nx:e.isMesh?ox:void 0}getSampleCount(e){return null!==e.textures?e.sampleCount:this.backend.parameters.sampleCount}}const Ey=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),Cy=new Map([[z,["float16"]]]),wy=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class My{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),r=this.backend,i=r.get(s);let n=i.buffer;if(void 0===n){const e=r.device,o=s.array,a=o.byteLength+(4-o.byteLength%4)%4;n=e.createBuffer({label:s.name,size:a,usage:t,mappedAtCreation:!0}),new o.constructor(n.getMappedRange()).set(o),n.unmap(),i.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,r=s.device,i=s.get(t).buffer,n=t.array,o=t.updateRanges;if(0===o.length)r.queue.writeBuffer(i,0,n,0);else{for(let e=0,t=o.length;e1&&(_=Math.pow(2,Math.floor(Math.log2(_))),2===_&&(_=4)),d.pipeline=u.createRenderPipeline({vertex:Object.assign({},T,{buffers:h}),fragment:Object.assign({},x,{targets:f}),primitive:y,depthStencil:{format:N,depthWriteEnabled:s.depthWrite,depthCompare:b,stencilFront:g,stencilBack:{},stencilReadMask:s.stencilFuncMask,stencilWriteMask:s.stencilWriteMask},multisample:{count:_,alphaToCoverageEnabled:s.alphaToCoverage},layout:u.createPipelineLayout({bindGroupLayouts:[c.layout]})})}createComputePipeline(e,t){const s=this.backend,r=s.device,i=s.get(e.computeProgram).module,n=s.get(e),o=s.get(t);n.pipeline=r.createComputePipeline({compute:i,layout:r.createPipelineLayout({bindGroupLayouts:[o.layout]})})}_getBlending(e){let t,s;const r=e.blending;if(r===Ye){const r=null!==e.blendSrcAlpha?e.blendSrcAlpha:Fx.One,i=null!==e.blendDstAlpha?e.blendDstAlpha:Fx.Zero,n=null!==e.blendEquationAlpha?e.blendEquationAlpha:Fx.Add;t={srcFactor:this._getBlendFactor(e.blendSrc),dstFactor:this._getBlendFactor(e.blendDst),operation:this._getBlendOperation(e.blendEquation)},s={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(i),operation:this._getBlendOperation(n)}}else{const i=(e,r,i,n)=>{t={srcFactor:e,dstFactor:r,operation:Bx},s={srcFactor:i,dstFactor:n,operation:Bx}};if(e.premultipliedAlpha)switch(r){case Je:i(Fx.SrcAlpha,Fx.OneMinusSrcAlpha,Fx.One,Fx.OneMinusSrcAlpha);break;case Ze:i(Fx.SrcAlpha,Fx.One,Fx.One,Fx.One);break;case Qe:i(Fx.Zero,Fx.OneMinusSrc,Fx.Zero,Fx.One);break;case Ke:i(Fx.Zero,Fx.Src,Fx.Zero,Fx.SrcAlpha)}else switch(r){case Je:i(Fx.SrcAlpha,Fx.OneMinusSrcAlpha,Fx.One,Fx.OneMinusSrcAlpha);break;case Ze:i(Fx.SrcAlpha,Fx.One,Fx.SrcAlpha,Fx.One);break;case Qe:i(Fx.Zero,Fx.OneMinusSrc,Fx.Zero,Fx.One);break;case Ke:i(Fx.Zero,Fx.Src,Fx.Zero,Fx.Src)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s}}_getBlendFactor(e){let t;switch(e){case Ue:t=Fx.Zero;break;case Ie:t=Fx.One;break;case De:t=Fx.Src;break;case ze:t=Fx.OneMinusSrc;break;case Pe:t=Fx.SrcAlpha;break;case $e:t=Fx.OneMinusSrcAlpha;break;case Ge:t=Fx.Dst;break;case He:t=Fx.OneMinusDstColor;break;case ke:t=Fx.DstAlpha;break;case We:t=Fx.OneMinusDstAlpha;break;case Ve:t=Fx.SrcAlphaSaturated;break;case 211:t=Fx.Constant;break;case 212:t=Fx.OneMinusConstant}return t}_getStencilCompare(e){let t;switch(e.stencilFunc){case Ns:t=ux;break;case bs:t=mx;break;case ys:t=lx;break;case xs:t=cx;break;case Ts:t=dx;break;case fs:t=gx;break;case ms:t=hx;break;case gs:t=px}return t}_getStencilOperation(e){let t;switch(e){case ws:t=Vx;break;case Cs:t=Gx;break;case Es:t=kx;break;case Rs:t=zx;break;case As:t=$x;break;case Ss:t=Hx;break;case vs:t=Wx;break;case _s:t=jx}return t}_getBlendOperation(e){let t;switch(e){case Be:t=Bx;break;case Oe:t=Ox;break;case Le:t=Lx;break;case Fs:t=Ux;break;case Ms:t=Ix}return t}_getPrimitiveState(e,t,s){const r={},i=this.backend.utils;switch(r.topology=i.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?vx:Sx),s.side){case we:r.frontFace=yx,r.cullMode=_x;break;case O:r.frontFace=yx,r.cullMode=Nx;break;case Ce:r.frontFace=yx,r.cullMode=bx}return r}_getColorWriteMask(e){return!0===e.colorWrite?Px:Dx}_getDepthCompare(e){let t;if(!1===e.depthTest)t=mx;else{switch(e.depthFunc){case at:t=ux;break;case ot:t=mx;break;case nt:t=lx;break;case it:t=cx;break;case rt:t=dx;break;case st:t=gx;break;case tt:t=hx;break;case et:t=px}}return t}}let Oy=null;void 0!==navigator.gpu&&(Oy=await navigator.gpu.requestAdapter());class Ly extends kT{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.antialias=!0===e.antialias,!0===this.parameters.antialias?this.parameters.sampleCount=void 0===e.sampleCount?4:e.sampleCount:this.parameters.sampleCount=1,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.adapter=null,this.device=null,this.context=null,this.colorBuffer=null,this.utils=new Ry(this),this.attributeUtils=new My(this),this.bindingUtils=new Fy(this),this.pipelineUtils=new By(this),this.textureUtils=new cy(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters,s={powerPreference:t.powerPreference},r=await navigator.gpu.requestAdapter(s);if(null===r)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(iy),n=[];for(const e of i)r.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits},a=await r.requestDevice(o),u=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.adapter=r,this.device=a,this.context=u;const l=t.alpha?"premultiplied":"opaque";this.context.configure({device:this.device,format:Ax.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:l}),this.updateSize()}get coordinateSystem(){return y}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}beginRender(e){const t=this.get(e),s=this.device,r=e.occlusionQueryCount;let i;r>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=s.createQuerySet({type:"occlusion",count:r}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(r),t.lastOcclusionObject=null);const n={colorAttachments:[{view:null}],depthStencilAttachment:{view:null},occlusionQuerySet:i},o=n.colorAttachments[0],a=n.depthStencilAttachment,u=this.parameters.antialias;if(null!==e.textures){const t=e.textures;n.colorAttachments=[];const s=n.colorAttachments;for(let r=0;rt.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),s>0){const r=8*s;let i=this.occludedResolveCache.get(r);void 0===i&&(i=this.device.createBuffer({size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(r,i));const n=this.device.createBuffer({size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,r),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;eGy&&((1/(e-Gy)).toFixed(),await this._callback(e,{width:this.video.videoWidth,height:this.video.videoHeight})),Gy=e,this.animationID=Py((async()=>await this.animateLegacy()))}async animate(e,t){await this._callback(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initAnimate(){this.animateRef=async(e,t)=>await this.animate(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initLegacyAnimate(){this.animateLegacy()}start(){this.stop(),Dy?this.initAnimate():(Gy=new Date,this.initLegacyAnimate()),this.running=!0}stop(){this.running=!1,Dy?this.animateRef=()=>{}:Vy(this.animationID&&this.animationID.data&&this.animationID.data.handleId||this.animationID)}}const zy="requestVideoFrameCallback"in HTMLVideoElement.prototype,$y=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,Hy=window.cancelAnimationFrame||window.mozCancelAnimationFrame;let Wy;class jy{constructor(e,t){this._callback=e,this.video=t,this.animationID=null,this.running=!1,this.updateNodesRef=()=>{}}set nodes(e){this._nodes=e,e&&(this.updateNodesRef=()=>{this._nodes.nodeFrame.update()})}set callback(e){this._callback=e}async animateLegacy(){const e=this.video.currentTime;e>Wy&&((1/(e-Wy)).toFixed(),this.updateNodesRef(),await this._callback(e,{width:this.video.videoWidth,height:this.video.videoHeight})),Wy=e,this.animationID=$y((async()=>await this.animateLegacy()))}async animate(e,t){this.updateNodesRef(),await this._callback(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initAnimate(){this.animateRef=async(e,t)=>await this.animate(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initLegacyAnimate(){this.animateLegacy()}start(){this.stop(),zy?this.initAnimate():(Wy=new Date,this.initLegacyAnimate()),this.running=!0}stop(){this.running=!1,zy?this.animateRef=()=>{}:Hy(this.animationID&&this.animationID.data&&this.animationID.data.handleId||this.animationID)}}export{Yl as AONode,_p as AfterImageNode,sg as AmbientLightNode,$l as AnalyticLightNode,Cr as ArrayElementNode,Zi as ArrayUniformNode,Ji as AssignNode,rn as AttributeNode,Og as BRDF_GGX,Ng as BRDF_Lambert,qc as BitangentNode,Mh as BlendModeNode,gl as BufferAttributeNode,Nl as BufferNode,Gh as BumpMapNode,on as BypassNode,dn as CacheNode,ou as CameraNode,ng as CheckerNode,qn as CodeNode,Wh as ColorAdjustmentNode,Oa as ColorSpaceNode,Xp as ComputeNode,Qd as CondNode,Ur as ConstNode,hn as ContextNode,wr as ConvertNode,Vl as CubeTextureNode,Lg as DFGApprox,Bg as D_GGX,Jp as DirectionalLightNode,mc as DiscardNode,wo as EPSILON,rd as EnvironmentNode,Zl as EquirectUVNode,Va as ExpressionNode,bg as F_Schlick,kp as FogExp2Node,Dp as FogNode,Vp as FogRangeNode,Uh as FrontFacingNode,Cp as FunctionCallNode,Jn as FunctionNode,xc as FunctionOverloadingNode,pm as GLSLNodeParser,yp as GaussianBlurNode,hc as HashNode,rg as HemisphereLightNode,tg as IESSpotLightNode,Mo as INFINITY,xi as If,mn as IndexNode,yl as InstanceNode,lg as InstancedPointsNodeMaterial,Fr as JoinNode,Yp as LightNode,Kl as LightingContextNode,xn as LightingModel,kl as LightingNode,Wl as LightsNode,mg as Line2NodeMaterial,cg as LineBasicNodeMaterial,pg as LineDashedNodeMaterial,Nc as LoopNode,vc as MatcapUVNode,Bu as MaterialNode,Ka as MaterialReferenceNode,Co as MathNode,ka as MaxMipLevelNode,yg as MeshBasicNodeMaterial,Rg as MeshLambertNodeMaterial,Tg as MeshNormalNodeMaterial,Cg as MeshPhongNodeMaterial,Qg as MeshPhysicalNodeMaterial,Jg as MeshSSSNodeMaterial,Yg as MeshStandardNodeMaterial,mu as ModelNode,hl as ModelViewProjectionNode,Ul as MorphNode,xr as Node,Nn as NodeAttribute,oc as NodeBuilder,ln as NodeCache,An as NodeCode,ac as NodeFrame,uc as NodeFunctionInput,Rn as NodeKeywords,ag as NodeLoader,Od as NodeMaterial,nm as NodeMaterialLoader,om as NodeObjectLoader,sr as NodeShaderStage,ir as NodeType,_n as NodeUniform,rr as NodeUpdateType,mr as NodeUtils,vn as NodeVar,Sn as NodeVarying,Zh as NormalMapNode,vu as NormalNode,Za as Object3DNode,ao as OperatorNode,Mc as OscNode,dc as OutputStructNode,Uc as PackingNode,jn as ParameterNode,Ap as PassNode,Sg as PhongLightingModel,Xg as PhysicalLightingModel,Zp as PointLightNode,mh as PointUVNode,tm as PointsNodeMaterial,nl as PositionNode,tp as PosterizeNode,En as PropertyNode,Wp as RangeNode,Xa as ReferenceNode,Dl as ReflectVectorNode,Pc as RemapNode,kc as RotateUVNode,Th as SceneNode,Ig as Schlick_to_F0,Up as ScriptableNode,Mp as ScriptableValueNode,Lr as SetNode,ui as ShaderNode,Ml as SkinningNode,ed as SpecularMIPLevelNode,Or as SplitNode,eg as SpotLightNode,rm as SpriteNodeMaterial,$c as SpriteSheetUVNode,Jd as StackNode,bh as StorageBufferNode,ep as TBNViewMatrix,vl as TangentNode,Mr as TempNode,ph as TextureBicubicNode,$a as TextureNode,_h as TextureStoreNode,Ac as TimerNode,lp as ToneMappingNode,Wc as TriplanarTexturesNode,ro as UVNode,_r as UniformGroupNode,Ki as UniformNode,Sh as UserDataNode,Fg as V_GGX_SmithCorrelated,yn as VarNode,tn as VaryingNode,th as VertexColorNode,ky as VideoAnimation,vd as ViewportDepthNode,Nd as ViewportDepthTextureNode,ud as ViewportNode,hp as ViewportSharedTextureNode,Td as ViewportTextureNode,Os as WebGPU,Iy as WebGPUGLRenderer,Uy as WebGPURenderer,jy as WebGPUVideoAnimation,Yo as abs,Xo as acos,uo as add,ql as addLightNode,yr as addNodeClass,Pr as addNodeElement,Ld as addNodeMaterial,vp as afterImage,bo as and,yi as append,ji as arrayBuffer,jo as asin,en as assign,qo as atan,aa as atan2,nn as attribute,xh as backgroundBlurriness,yh as backgroundIntensity,vo as bitAnd,So as bitOr,Ao as bitXor,Yc as bitangentGeometry,Kc as bitangentLocal,Qc as bitangentView,Zc as bitangentWorld,oa as bitcast,Gi as bmat3,Hi as bmat4,Si as bool,_l as buffer,ml as bufferAttribute,kh as bumpMap,Fh as burn,Ci as bvec2,Bi as bvec3,Ii as bvec4,an as bypass,cn as cache,wp as call,lu as cameraFar,du as cameraLogDepth,uu as cameraNear,hu as cameraNormalMatrix,gu as cameraPosition,au as cameraProjectionMatrix,cu as cameraViewMatrix,pu as cameraWorldMatrix,_a as cbrt,Go as ceil,og as checker,Sa as clamp,On as clearcoat,Ln as clearcoatRoughness,Yn as code,bi as color,Ia as colorSpaceToLinear,Dc as colorToDirection,qp as compute,Zd as cond,pn as context,qi as convert,Ho as cos,br as createNodeFromType,Ud as createNodeMaterialFromType,fa as cross,Gl as cubeTexture,ea as dFdx,ta as dFdy,$n as dashSize,or as defaultBuildStages,nr as defaultShaderStages,Bo as degrees,zp as densityFog,wd as depth,Ep as depthPass,Fd as depthPixel,Md as depthTexture,ga as difference,Mn as diffuseColor,Ic as directionToColor,Tc as discard,pa as distance,ho as div,Bh as dodge,ma as dot,fl as dynamicBufferAttribute,Xi as element,go as equal,Jl as equirectUV,Oo as exp,Lo as exp2,Ga as expression,Dh as faceDirection,Ca as faceForward,Ni as float,Vo as floor,Pp as fog,zo as fract,Ar as frameGroup,wc as frameId,Ih as frontFacing,na as fwidth,Hn as gapSize,bp as gaussianBlur,ai as getConstNodeType,Ti as getCurrentStack,Qp as getDistanceAttenuation,wg as getGeometryRoughness,Mg as getRoughness,Lp as global,Zn as glsl,to as glslFn,To as greaterThan,yo as greaterThanEqual,pc as hash,qh as hue,Pi as imat3,zi as imat4,bl as instance,Tn as instanceIndex,Tl as instancedBufferAttribute,xl as instancedDynamicBufferAttribute,_i as int,Po as inverseSqrt,Dn as iridescence,Pn as iridescenceIOR,Vn as iridescenceThickness,Ri as ivec2,Mi as ivec3,Li as ivec4,Kn as js,gn as label,Qo as length,fo as lessThan,xo as lessThanEqual,Xl as lightNodes,Kp as lightTargetDirection,Ql as lightingContext,jl as lights,Ua as linearToColorSpace,Da as linearTosRGB,Uo as log,Io as log2,_c as loop,Yh as lumaCoeffs,Kh as luminance,Di as mat3,ki as mat4,Sc as matcapUV,Ou as materialAlphaTest,Hu as materialClearcoat,ju as materialClearcoatNormal,Wu as materialClearcoatRoughness,Lu as materialColor,Iu as materialEmissive,Ku as materialIridescence,Qu as materialIridescenceIOR,Zu as materialIridescenceThickness,rl as materialLineDashOffset,el as materialLineDashSize,tl as materialLineGapSize,Ju as materialLineScale,sl as materialLineWidth,zu as materialMetalness,$u as materialNormal,Du as materialOpacity,il as materialPointWidth,Qa as materialReference,Gu as materialReflectivity,Xu as materialRotation,ku as materialRoughness,qu as materialSheen,Yu as materialSheenRoughness,Uu as materialShininess,Pu as materialSpecularColor,Vu as materialSpecularStrength,la as max,za as maxMipLevel,Bn as metalness,ua as min,va as mix,da as mod,fu as modelDirection,xu as modelNormalMatrix,bu as modelPosition,Nu as modelScale,Tu as modelViewMatrix,_u as modelViewPosition,pl as modelViewProjection,yu as modelWorldMatrix,Il as morph,co as mul,Bf as mx_aastep,qf as mx_cell_noise_float,kf as mx_contrast,Yf as mx_fractal_noise_float,Kf as mx_fractal_noise_vec2,Qf as mx_fractal_noise_vec3,Zf as mx_fractal_noise_vec4,wf as mx_hsvtorgb,zf as mx_noise_float,$f as mx_noise_vec3,Hf as mx_noise_vec4,Lf as mx_ramplr,Uf as mx_ramptb,Mf as mx_rgbtohsv,Gf as mx_safepower,Df as mx_splitlr,Pf as mx_splittb,Ff as mx_srgb_texture_to_lin_rec709,Vf as mx_transform_uv,Wf as mx_worley_noise_float,jf as mx_worley_noise_vec2,Xf as mx_worley_noise_vec3,Zo as negate,ci as nodeArray,pi as nodeImmutable,li as nodeObject,di as nodeObjects,hi as nodeProxy,Su as normalGeometry,Au as normalLocal,Jh as normalMap,Ru as normalView,Eu as normalWorld,ko as normalize,Ja as objectDirection,Er as objectGroup,tu as objectNormalMatrix,ru as objectPosition,iu as objectScale,eu as objectViewMatrix,nu as objectViewPosition,su as objectWorldMatrix,Jo as oneMinus,No as or,Ad as orthographicDepthToViewZ,Lc as oscSawtooth,Fc as oscSine,Bc as oscSquare,Oc as oscTriangle,zn as output,cc as outputStruct,Oh as overlay,bc as overloadingFn,Xn as parameter,Rp as pass,Ed as perspectiveDepthToViewZ,fh as pointUV,Wn as pointWidth,ol as positionGeometry,al as positionLocal,dl as positionView,cl as positionViewDirection,ul as positionWorld,ll as positionWorldDirection,sp as posterize,Ta as pow,xa as pow2,ya as pow3,ba as pow4,Cn as property,Fo as radians,jp as range,Gp as rangeFog,ra as reciprocal,qa as reference,Ya as referenceIndex,ha as reflect,Pl as reflectVector,Ra as refract,po as remainder,Vc as remap,Gc as remapClamp,Rr as renderGroup,zc as rotateUV,Fn as roughness,sa as round,Pa as sRGBToLinear,ja as sampler,Aa as saturate,jh as saturation,Lh as screen,Ip as scriptable,Fp as scriptableValue,fi as setCurrentStack,gi as shader,ar as shaderStages,Un as sheen,In as sheenRoughness,Ro as shiftLeft,Eo as shiftRight,kn as shininess,Ko as sign,$o as sin,Fl as skinning,Ea as smoothstep,Gn as specularColor,td as specularMIPLevel,Yi as split,Hc as spritesheetUV,Do as sqrt,ec as stack,ca as step,Nh as storage,Wi as string,lo as sub,Wo as tan,Sl as tangentGeometry,Al as tangentLocal,Rl as tangentView,El as tangentWorld,bn as temp,Ha as texture,gh as textureBicubic,Wa as textureLoad,vh as textureStore,Cc as timerDelta,Ec as timerGlobal,Rc as timerLocal,dp as toneMapping,Na as transformDirection,Jc as transformedBitangentView,eh as transformedBitangentWorld,Mu as transformedClearcoatNormalView,Cu as transformedNormalView,wu as transformedNormalWorld,Cl as transformedTangentView,wl as transformedTangentWorld,Xc as triplanarTexture,jc as triplanarTextures,ia as trunc,mi as tslFn,vi as uint,Vi as umat3,$i as umat4,Qi as uniform,vr as uniformGroup,Ah as userData,io as uv,Ei as uvec2,Fi as uvec3,Ui as uvec4,sn as varying,wn as varyingProperty,Ai as vec2,wi as vec3,Oi as vec4,ur as vectorComponents,sh as vertexColor,fn as vertexIndex,Xh as vibrance,Sd as viewZToOrthographicDepth,Rd as viewZToPerspectiveDepth,cd as viewport,pd as viewportBottomLeft,md as viewportBottomRight,ld as viewportCoordinate,_d as viewportDepthTexture,yd as viewportMipTexture,dd as viewportResolution,pp as viewportSharedTexture,xd as viewportTexture,hd as viewportTopLeft,gd as viewportTopRight,Qn as wgsl,so as wgslFn,_o as xor}; +import{Plane as e,Matrix3 as t,Vector4 as s,DynamicDrawUsage as r,Uint32BufferAttribute as i,Uint16BufferAttribute as n,Color as o,Vector2 as a,Vector3 as u,Matrix4 as l,EventDispatcher as c,MathUtils as d,LinearSRGBColorSpace as h,SRGBColorSpace as p,StaticDrawUsage as g,InterleavedBuffer as m,InterleavedBufferAttribute as f,InstancedInterleavedBuffer as T,DataArrayTexture as x,FloatType as y,WebGPUCoordinateSystem as b,DepthTexture as N,NearestFilter as _,LessCompare as v,FramebufferTexture as S,LinearMipmapLinearFilter as A,ShaderMaterial as R,NoColorSpace as C,Material as E,WebGLCubeRenderTarget as w,BoxGeometry as M,BackSide as F,NoBlending as B,Mesh as O,Scene as U,LinearFilter as L,CubeCamera as I,RenderTarget as P,Float16BufferAttribute as D,REVISION as V,Object3D as G,HalfFloatType as k,LinearMipMapLinearFilter as z,TangentSpaceNormalMap as $,ObjectSpaceNormalMap as H,NoToneMapping as W,LinearToneMapping as j,ReinhardToneMapping as q,CineonToneMapping as X,ACESFilmicToneMapping as Y,AgXToneMapping as K,OrthographicCamera as Q,BufferGeometry as Z,Float32BufferAttribute as J,PointLight as ee,DirectionalLight as te,SpotLight as se,AmbientLight as re,HemisphereLight as ie,Loader as ne,FileLoader as oe,PointsMaterial as ae,LineBasicMaterial as ue,LineDashedMaterial as le,MeshNormalMaterial as ce,MeshBasicMaterial as de,MeshLambertMaterial as he,MeshPhongMaterial as pe,MeshStandardMaterial as ge,MeshPhysicalMaterial as me,SpriteMaterial as fe,MaterialLoader as Te,ObjectLoader as xe,DepthStencilFormat as ye,DepthFormat as be,UnsignedInt248Type as Ne,UnsignedIntType as _e,UnsignedByteType as ve,EquirectangularReflectionMapping as Se,EquirectangularRefractionMapping as Ae,CubeReflectionMapping as Re,CubeRefractionMapping as Ce,SphereGeometry as Ee,Frustum as we,DoubleSide as Me,FrontSide as Fe,DataTexture as Be,IntType as Oe,RedFormat as Ue,RGFormat as Le,RGBAFormat as Ie,createCanvasElement as Pe,AddEquation as De,SubtractEquation as Ve,ReverseSubtractEquation as Ge,ZeroFactor as ke,OneFactor as ze,SrcColorFactor as $e,SrcAlphaFactor as He,SrcAlphaSaturateFactor as We,DstColorFactor as je,DstAlphaFactor as qe,OneMinusSrcColorFactor as Xe,OneMinusSrcAlphaFactor as Ye,OneMinusDstColorFactor as Ke,OneMinusDstAlphaFactor as Qe,CullFaceNone as Ze,CullFaceBack as Je,CullFaceFront as et,CustomBlending as tt,MultiplyBlending as st,SubtractiveBlending as rt,AdditiveBlending as it,NormalBlending as nt,NotEqualDepth as ot,GreaterDepth as at,GreaterEqualDepth as ut,EqualDepth as lt,LessEqualDepth as ct,LessDepth as dt,AlwaysDepth as ht,NeverDepth as pt,UnsignedShort4444Type as gt,UnsignedShort5551Type as mt,ByteType as ft,ShortType as Tt,UnsignedShortType as xt,AlphaFormat as yt,LuminanceFormat as bt,LuminanceAlphaFormat as Nt,RedIntegerFormat as _t,RGIntegerFormat as vt,RGBAIntegerFormat as St,RGB_S3TC_DXT1_Format as At,RGBA_S3TC_DXT1_Format as Rt,RGBA_S3TC_DXT3_Format as Ct,RGBA_S3TC_DXT5_Format as Et,RGB_PVRTC_4BPPV1_Format as wt,RGB_PVRTC_2BPPV1_Format as Mt,RGBA_PVRTC_4BPPV1_Format as Ft,RGBA_PVRTC_2BPPV1_Format as Bt,RGB_ETC1_Format as Ot,RGB_ETC2_Format as Ut,RGBA_ETC2_EAC_Format as Lt,RGBA_ASTC_4x4_Format as It,RGBA_ASTC_5x4_Format as Pt,RGBA_ASTC_5x5_Format as Dt,RGBA_ASTC_6x5_Format as Vt,RGBA_ASTC_6x6_Format as Gt,RGBA_ASTC_8x5_Format as kt,RGBA_ASTC_8x6_Format as zt,RGBA_ASTC_8x8_Format as $t,RGBA_ASTC_10x5_Format as Ht,RGBA_ASTC_10x6_Format as Wt,RGBA_ASTC_10x8_Format as jt,RGBA_ASTC_10x10_Format as qt,RGBA_ASTC_12x10_Format as Xt,RGBA_ASTC_12x12_Format as Yt,RGBA_BPTC_Format as Kt,RED_RGTC1_Format as Qt,SIGNED_RED_RGTC1_Format as Zt,RED_GREEN_RGTC2_Format as Jt,SIGNED_RED_GREEN_RGTC2_Format as es,RepeatWrapping as ts,ClampToEdgeWrapping as ss,MirroredRepeatWrapping as rs,NearestMipmapNearestFilter as is,NearestMipmapLinearFilter as ns,LinearMipmapNearestFilter as os,NeverCompare as as,AlwaysCompare as us,LessEqualCompare as ls,EqualCompare as cs,GreaterEqualCompare as ds,GreaterCompare as hs,NotEqualCompare as ps,WebGLCoordinateSystem as gs,Texture as ms,CubeTexture as fs,NotEqualStencilFunc as Ts,GreaterStencilFunc as xs,GreaterEqualStencilFunc as ys,EqualStencilFunc as bs,LessEqualStencilFunc as Ns,LessStencilFunc as _s,AlwaysStencilFunc as vs,NeverStencilFunc as Ss,DecrementWrapStencilOp as As,IncrementWrapStencilOp as Rs,DecrementStencilOp as Cs,IncrementStencilOp as Es,InvertStencilOp as ws,ReplaceStencilOp as Ms,ZeroStencilOp as Fs,KeepStencilOp as Bs,MaxEquation as Os,MinEquation as Us}from"three";void 0===self.GPUShaderStage&&(self.GPUShaderStage={VERTEX:1,FRAGMENT:2,COMPUTE:4});let Ls=void 0!==navigator.gpu;"undefined"!=typeof window&&Ls&&(Ls=await navigator.gpu.requestAdapter());class Is{static isAvailable(){return Boolean(Ls)}static getStaticAdapter(){return Ls}static getErrorMessage(){const e=document.createElement("div");return e.id="webgpumessage",e.style.fontFamily="monospace",e.style.fontSize="13px",e.style.fontWeight="normal",e.style.textAlign="center",e.style.background="#fff",e.style.color="#000",e.style.padding="1.5em",e.style.maxWidth="400px",e.style.margin="5em auto 0",e.innerHTML='Your browser does not support WebGPU yet',e}}class Ps{constructor(e,t){this.nodes=e,this.info=t,this.animationLoop=null,this.requestId=null,this._init()}_init(){const e=(t,s)=>{this.requestId=self.requestAnimationFrame(e),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this.animationLoop&&this.animationLoop(t,s)};e()}dispose(){self.cancelAnimationFrame(this.requestId)}setAnimationLoop(e){this.animationLoop=e}}class Ds{constructor(){this.weakMap=new WeakMap}get(e){if(Array.isArray(e)){let t=this.weakMap;for(let s=0;s{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){const t=this.material;let s=this.clippingContext;Array.isArray(t.clippingPlanes)?(s!==e&&s||(s=new zs,this.clippingContext=s),s.update(e,t)):this.clippingContext!==e&&(this.clippingContext=e)}clippingNeedsUpdate(){return this.clippingContext.version!==this.clippingContextVersion&&(this.clippingContextVersion=this.clippingContext.version,!0)}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getIndex(){return this._geometries.getIndex(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],r=new Set;for(const i of e){const e=i.node&&i.node.attribute?i.node.attribute:t.getAttribute(i.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;r.add(n)}return this.attributes=s,this.vertexBuffers=Array.from(r.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const e in t){if(/^(is[A-Z])|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;let r=t[e];if(null!==r){const e=typeof r;"number"===e?r=0!==r?"1":"0":"object"===e&&(r="{}")}s+=r+","}return s+=this.clippingContextVersion+",",e.skeleton&&(s+=e.skeleton.bones.length+","),e.morphTargetInfluences&&(s+=e.morphTargetInfluences.length+","),s}get needsUpdate(){return this.initialNodesCacheKey!==this.getNodesCacheKey()}getNodesCacheKey(){return this._nodes.getCacheKey(this.scene,this.lightsNode)}getCacheKey(){return this.getMaterialCacheKey()+","+this.getNodesCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}class Ws{constructor(e,t,s,r,i,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=r,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,s,r,i,n,o){const a=this.getChainMap(o),u=[e,t,n,i];let l=a.get(u);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,r,i,n,o),a.set(u,l)):(l.updateClipping(n.clippingContext),(l.version!==t.version||l.needsUpdate||l.clippingNeedsUpdate())&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,s,r,i,n,o)):l.version=t.version)),l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Ds)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,r,i,n,o,a,u,l){const c=this.getChainMap(l),d=new Hs(e,t,s,r,i,n,o,a,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class js{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const qs=1,Xs=2,Ys=4,Ks=16;class Qs extends js{constructor(e){super(),this.backend=e}delete(e){void 0!==super.delete(e)&&this.backend.destroyAttribute(e)}update(e,t){const s=this.get(e);if(void 0===s.version)t===qs?this.backend.createAttribute(e):t===Xs?this.backend.createIndexAttribute(e):t===Ys&&this.backend.createStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version=0;--t)if(e[t]>=65535)return!0;return!1}(t)?i:n)(t,1);return o.version=Zs(e),o}class er extends js{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const r=t.index,i=e.getAttributes();null!==r&&this.attributes.delete(r);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",s)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)this.updateAttribute(e,qs);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Xs)}updateAttribute(e,t){const s=this.info.render.calls;this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndex(e){const{geometry:t,material:s}=e;let r=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=Js(t),e.set(t,s)):s.version!==Zs(t)&&(this.attributes.delete(s),s=Js(t),e.set(t,s)),r=s}return r}}class tr{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,drawCalls:0,triangles:0,points:0,lines:0},this.compute={calls:0,computeCalls:0},this.memory={geometries:0,textures:0},this.timestamp={compute:0,render:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine&&(this.render.lines+=s*(t-1))}updateTimestamp(e,t){this.timestamp[e]+=t}resetCompute(){this.compute.computeCalls=0,this.timestamp.compute=0}reset(){this.render.drawCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0,this.timestamp.render=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.timestamp.compute=0,this.timestamp.render=0,this.memory.geometries=0,this.memory.textures=0}}class sr{constructor(e){this.cacheKey=e,this.usedTimes=0}}class rr extends sr{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class ir extends sr{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let nr=0;class or{constructor(e,t,s=null,r=null){this.id=nr++,this.code=e,this.stage=t,this.transforms=s,this.attributes=r,this.usedTimes=0}}class ar extends js{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),o=new or(n.computeShader,"compute",n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let u=this.caches.get(a);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(e),u=this._getComputePipeline(e,o,a,t)),u.usedTimes++,o.usedTimes++,r.version=e.version,r.pipeline=u}return r.pipeline}getForRender(e,t=null){const{backend:s}=this,r=this.get(e);if(this._needsRenderUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState();let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new or(n.vertexShader,"vertex"),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let a=this.programs.fragment.get(n.fragmentShader);void 0===a&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),a=new or(n.fragmentShader,"fragment"),this.programs.fragment.set(n.fragmentShader,a),s.createProgram(a));const u=this._getRenderCacheKey(e,o,a);let l=this.caches.get(u);void 0===l?(i&&0===i.usedTimes&&this._releasePipeline(i),l=this._getRenderPipeline(e,o,a,u,t)):e.pipeline=l,l.usedTimes++,o.usedTimes++,a.usedTimes++,r.pipeline=l}return r.pipeline}delete(e){const t=this.get(e).pipeline;t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,r){s=s||this._getComputeCacheKey(e,t);let i=this.caches.get(s);return void 0===i&&(i=new ir(s,t),this.caches.set(s,i),this.backend.createComputePipeline(i,r)),i}_getRenderPipeline(e,t,s,r,i){r=r||this._getRenderCacheKey(e,t,s);let n=this.caches.get(r);return void 0===n&&(n=new rr(r,t,s),this.caches.set(r,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class ur extends js{constructor(e,t,s,r,i,n){super(),this.backend=e,this.textures=s,this.pipelines=i,this.attributes=r,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),s=this.get(e);return s.bindings!==t&&(s.bindings=t,this._init(t),this.backend.createBindings(t)),s.bindings}getForCompute(e){const t=this.get(e);if(void 0===t.bindings){const s=this.nodes.getForCompute(e).bindings;t.bindings=s,this._init(s),this.backend.createBindings(s)}return t.bindings}updateForCompute(e){this._update(e,this.getForCompute(e))}updateForRender(e){this._update(e,this.getForRender(e))}_init(e){for(const t of e)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute;this.attributes.update(e,Ys)}}_update(e,t){const{backend:s}=this;let r=!1;for(const e of t){if(e.isNodeUniformsGroup){if(!this.nodes.updateGroup(e))continue}if(e.isUniformBuffer){e.update()&&s.updateBinding(e)}else if(e.isSampledTexture){const t=e.texture;e.needsBindingsUpdate&&(r=!0);if(e.update()&&this.textures.updateTexture(e.texture),!0===t.isStorageTexture){const s=this.get(t);!0===e.store?s.needsMipmap=!0:!0===t.generateMipmaps&&this.textures.needsMipmaps(t)&&!0===s.needsMipmap&&(this.backend.generateMipmaps(t),s.needsMipmap=!1)}}}if(!0===r){const s=this.pipelines.getForRender(e);this.backend.updateBindings(t,s)}}}const lr={VERTEX:"vertex",FRAGMENT:"fragment"},cr={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},dr={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},hr=["fragment","vertex"],pr=["setup","analyze","generate"],gr=[...hr,"compute"],mr=["x","y","z","w"];function fr(e){let t="{";!0===e.isNode&&(t+=e.id);for(const{property:s,childNode:r}of Tr(e))t+=","+s.slice(0,-4)+":"+r.getCacheKey();return t+="}",t}function*Tr(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const r=e[s];if(!0===Array.isArray(r))for(let e=0;ee.charCodeAt(0))).buffer}var _r=Object.freeze({__proto__:null,getCacheKey:fr,getNodeChildren:Tr,getValueType:xr,getValueFromType:yr,arrayBufferToBase64:br,base64ToArrayBuffer:Nr});const vr=new Map;let Sr=0;class Ar extends c{constructor(e=null){super(),this.nodeType=e,this.updateType=cr.NONE,this.updateBeforeType=cr.NONE,this.uuid=d.generateUUID(),this.isNode=!0,Object.defineProperty(this,"id",{value:Sr++})}get type(){return this.constructor.type}getSelf(){return this.self||this}setReference(){return this}isGlobal(){return!1}*getChildren(){for(const{childNode:e}of Tr(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(){return fr(this)}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}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);for(const e of this.getChildren())t["_node"+e.id]=e;return null}construct(e){return this.setup(e)}increaseUsage(e){const t=e.getDataFromNode(this);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}analyze(e){if(1===this.increaseUsage(e)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){}update(){}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let r=null;const i=e.getBuildStage();if("setup"===i){this.setReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized||!1===e.context.tempRead){const s=e.stack.nodes.length;t.initialized=!0,t.outputNode=this.setup(e),null!==t.outputNode&&e.stack.nodes.length!==s&&(t.outputNode=e.stack);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}else if("analyze"===i)this.analyze(e);else if("generate"===i){if(1===this.generate.length){const s=this.getNodeType(e),i=e.getDataFromNode(this);r=i.snippet,void 0===r&&(r=this.generate(e)||"",i.snippet=r),r=e.format(r,s,t)}else r=this.generate(e,t)||""}return e.removeChain(this),r}getSerializeChildren(){return Tr(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:r,index:i,childNode:n}of t)void 0!==i?(void 0===s[r]&&(s[r]=Number.isInteger(i)?[]:{}),s[r][i]=n.toJSON(e.meta).uuid):s[r]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const r=[];for(const i of e.inputNodes[s])r.push(t[i]);this[s]=r}else if("object"==typeof e.inputNodes[s]){const r={};for(const i in e.inputNodes[s]){const n=e.inputNodes[s][i];r[i]=t[n]}this[s]=r}else{const r=e.inputNodes[s];this[s]=t[r]}}}toJSON(e){const{uuid:t,type:s}=this,r=void 0===e||"string"==typeof e;r&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const s in e){const r=e[s];delete r.metadata,t.push(r)}return t}if(void 0===i&&(i={uuid:t,type:s,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==r&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),r){const t=n(e.textures),s=n(e.images),r=n(e.nodes);t.length>0&&(i.textures=t),s.length>0&&(i.images=s),r.length>0&&(i.nodes=r)}return i}}function Rr(e,t){if("function"!=typeof t||!e)throw new Error(`Node class ${e} is not a class`);vr.has(e)||(vr.set(e,t),t.type=e)}function Cr(e){const t=vr.get(e);if(void 0!==t)return new t}class Er extends Ar{constructor(e){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(!1!==e.context.tempRead&&void 0!==r.propertyName)return e.format(r.propertyName,s,t);if(!1!==e.context.tempWrite&&"void"!==s&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${i}`),r.snippet=i,r.propertyName=o,e.format(r.propertyName,s,t)}}return super.build(e,t)}}Rr("TempNode",Er);class wr extends Ar{constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getNodeType(e)}generate(e){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}Rr("ArrayElementNode",wr);class Mr extends Ar{constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const r of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(r)||(s=r);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,r=this.getNodeType(e),i=s.build(e,r);return e.format(i,r,t)}}Rr("ConvertNode",Mr);class Fr extends Er{constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,s)=>t+e.getTypeLength(s.getNodeType(e))),0))}generate(e,t){const s=this.getNodeType(e),r=this.nodes,i=e.getComponentType(s),n=[];for(const t of r){let s=t.build(e);const r=e.getComponentType(t.getNodeType(e));r!==i&&(s=e.format(s,r,i)),n.push(s)}const o=`${e.getType(s)}( ${n.join(", ")} )`;return e.format(o,s,t)}}Rr("JoinNode",Fr);const Br=mr.join("");class Or extends Ar{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(mr.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const s=this.node,r=e.getTypeLength(s.getNodeType(e));let i=null;if(r>1){let n=null;this.getVectorLength()>=r&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);i=this.components.length===r&&this.components===Br.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else i=s.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}Rr("SplitNode",Or);class Ur extends Er{constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:r}=this,i=this.getNodeType(e),n=e.getTypeFromLength(s.length),o=r.build(e,n),a=t.build(e,i),u=e.getTypeLength(i),l=[];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"),kr={setup(e,t){const s=t.shift();return e(di(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Pr.assign(s,...e),s);if(Dr.has(t)){const r=Dr.get(t);return e.isStackNode?(...e)=>s.add(r(...e)):(...e)=>r(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Dr.has(t.slice(0,t.length-6))){const r=Dr.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],r(...e)):(...e)=>s.assign(r(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Gr(t),ci(new Or(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=(t=Gr(t.slice(3).toLowerCase())).split("").sort().join(""),s=>ci(new Ur(e,t,s));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),ci(new Or(e,t));if(!0===/^\d+$/.test(t))return ci(new wr(s,new Ir(Number(t),"uint")))}return Reflect.get(e,t,s)},set:(e,t,s,r)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,r):(r[t].assign(s),!0)},zr=new WeakMap,$r=new WeakMap,Hr=function(e,t=null){for(const s in e)e[s]=ci(e[s],t);return e},Wr=function(e,t=null){const s=e.length;for(let r=0;rci(null!==r?Object.assign(e,r):e);return null===t?(...t)=>i(new e(...hi(t))):null!==s?(s=ci(s),(...r)=>i(new e(t,...hi(r),s))):(...s)=>i(new e(t,...hi(s)))},qr=function(e,...t){return ci(new e(...hi(t)))};class Xr extends Ar{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){const{outputNode:t}=e.getNodeProperties(this);return t?t.getNodeType(e):super.getNodeType(e)}call(e){const{shaderNode:t,inputNodes:s}=this;if(t.layout){let r=$r.get(e.constructor);void 0===r&&(r=new WeakMap,$r.set(e.constructor,r));let i=r.get(t);return void 0===i&&(i=ci(e.buildFunctionNode(t)),r.set(t,i)),null!==e.currentFunctionNode&&e.currentFunctionNode.includes.push(i),ci(i.call(s))}const r=t.jsFunc,i=null!==s?r(s,e.stack,e):r(e.stack,e);return ci(i)}setup(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);return null===s?this.call(e).build(e,t):super.generate(e,t)}}class Yr extends Ar{constructor(e){super(),this.jsFunc=e,this.layout=null}get isArrayInput(){return/^\((\s+)?\[/.test(this.jsFunc.toString())}setLayout(e){return this.layout=e,this}call(e=null){return di(e),ci(new Xr(this,e))}setup(){return this.call()}}const Kr=[!1,!0],Qr=[0,1,2,3],Zr=[-1,-2],Jr=[.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],ei=new Map;for(const e of Kr)ei.set(e,new Ir(e));const ti=new Map;for(const e of Qr)ti.set(e,new Ir(e,"uint"));const si=new Map([...ti].map((e=>new Ir(e.value,"int"))));for(const e of Zr)si.set(e,new Ir(e,"int"));const ri=new Map([...si].map((e=>new Ir(e.value))));for(const e of Jr)ri.set(e,new Ir(e));for(const e of Jr)ri.set(-e,new Ir(-e));const ii={bool:ei,uint:ti,ints:si,float:ri},ni=new Map([...ei,...ri]),oi=(e,t)=>ni.has(e)?ni.get(e):!0===e.isNode?e:new Ir(e,t),ai=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[yr(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return ci(t.get(s[0]));if(1===s.length){const t=oi(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?ci(t):ci(new Mr(t,e))}const r=s.map((e=>oi(e)));return ci(new Fr(r,e))}},ui=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function li(e){return new Proxy(new Yr(e),kr)}const ci=(e,t=null)=>function(e,t=null){const s=xr(e);if("node"===s){let t=zr.get(e);return void 0===t&&(t=new Proxy(e,kr),zr.set(e,t),zr.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?ci(oi(e,t)):"shader"===s?fi(e):e}(e,t),di=(e,t=null)=>new Hr(e,t),hi=(e,t=null)=>new Wr(e,t),pi=(...e)=>new jr(...e),gi=(...e)=>new qr(...e),mi=e=>new li(e),fi=e=>{const t=new li(e),s=(...e)=>{let s;return di(e),s=e[0]&&e[0].isNode?[...e]:e[0],t.call(s)};return s.shaderNode=t,s.setLayout=e=>(t.setLayout(e),s),s};Rr("ShaderNode",li);const Ti=e=>{Pr=e},xi=()=>Pr,yi=(...e)=>Pr.if(...e);function bi(e){return Pr&&Pr.add(e),e}Vr("append",bi);const Ni=new ai("color"),_i=new ai("float",ii.float),vi=new ai("int",ii.int),Si=new ai("uint",ii.uint),Ai=new ai("bool",ii.bool),Ri=new ai("vec2"),Ci=new ai("ivec2"),Ei=new ai("uvec2"),wi=new ai("bvec2"),Mi=new ai("vec3"),Fi=new ai("ivec3"),Bi=new ai("uvec3"),Oi=new ai("bvec3"),Ui=new ai("vec4"),Li=new ai("ivec4"),Ii=new ai("uvec4"),Pi=new ai("bvec4"),Di=new ai("mat2"),Vi=new ai("imat2"),Gi=new ai("umat2"),ki=new ai("bmat2"),zi=new ai("mat3"),$i=new ai("imat3"),Hi=new ai("umat3"),Wi=new ai("bmat3"),ji=new ai("mat4"),qi=new ai("imat4"),Xi=new ai("umat4"),Yi=new ai("bmat4"),Ki=(e="")=>ci(new Ir(e,"string")),Qi=e=>ci(new Ir(e,"ArrayBuffer"));Vr("color",Ni),Vr("float",_i),Vr("int",vi),Vr("uint",Si),Vr("bool",Ai),Vr("vec2",Ri),Vr("ivec2",Ci),Vr("uvec2",Ei),Vr("bvec2",wi),Vr("vec3",Mi),Vr("ivec3",Fi),Vr("uvec3",Bi),Vr("bvec3",Oi),Vr("vec4",Ui),Vr("ivec4",Li),Vr("uvec4",Ii),Vr("bvec4",Pi),Vr("mat2",Di),Vr("imat2",Vi),Vr("umat2",Gi),Vr("bmat2",ki),Vr("mat3",zi),Vr("imat3",$i),Vr("umat3",Hi),Vr("bmat3",Wi),Vr("mat4",ji),Vr("imat4",qi),Vr("umat4",Xi),Vr("bmat4",Yi),Vr("string",Ki),Vr("arrayBuffer",Qi);const Zi=pi(wr),Ji=(e,t)=>ci(new Mr(ci(e),t)),en=(e,t)=>ci(new Or(ci(e),t));Vr("element",Zi),Vr("convert",Ji);class tn extends Er{constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return mr.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:r}=this,i=this.needsSplitAssign(e),n=s.getNodeType(e),o=s.context({assign:!0}).build(e),a=r.build(e,n),u=r.getNodeType(e),l=e.getDataFromNode(this);let c;if(!0===l.initialized)"void"!==t&&(c=o);else if(i){const r=e.getVarFromNode(this,null,n),i=e.getPropertyName(r);e.addLineFlowCode(`${i} = ${a}`);const u=s.node.context({assign:!0}).build(e);for(let t=0;tci(new on(e,t));Rr("AttributeNode",on);class un extends Ar{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.outputNode.build(e)}}const ln=pi(un);Vr("bypass",ln),Rr("BypassNode",un);let cn=0;class dn{constructor(){this.id=cn++,this.nodesData=new WeakMap}getNodeData(e){return this.nodesData.get(e)}setNodeData(e,t){this.nodesData.set(e,t)}}class hn extends Ar{constructor(e,t=new dn){super(),this.isCacheNode=!0,this.node=e,this.cache=t}getNodeType(e){return this.node.getNodeType(e)}build(e,...t){const s=e.getCache(),r=this.cache||e.globalCache;e.setCache(r);const i=this.node.build(e,...t);return e.setCache(s),i}}const pn=pi(hn);Vr("cache",pn),Vr("globalCache",(e=>pn(e,null))),Rr("CacheNode",hn);class gn extends Ar{constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.context=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.context});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.context});const r=this.node.build(e,t);return e.setContext(s),r}}const mn=pi(gn),fn=(e,t)=>mn(e,{label:t});Vr("context",mn),Vr("label",fn),Rr("ContextNode",gn);class Tn extends Ar{constructor(e){super("uint"),this.scope=e,this.isInstanceIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let r,i;if(s===Tn.VERTEX)r=e.getVertexIndex();else{if(s!==Tn.INSTANCE)throw new Error("THREE.IndexNode: Unknown scope: "+s);r=e.getInstanceIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=r;else{i=nn(this).build(e,t)}return i}}Tn.VERTEX="vertex",Tn.INSTANCE="instance";const xn=gi(Tn,Tn.VERTEX),yn=gi(Tn,Tn.INSTANCE);Rr("IndexNode",Tn);class bn{start(){}finish(){}direct(){}indirectDiffuse(){}indirectSpecular(){}ambientOcclusion(){}}class Nn extends Ar{constructor(e,t=null){super(),this.node=e,this.name=t,this.isVarNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s}=this,r=e.getVarFromNode(this,s,e.getVectorType(this.getNodeType(e))),i=e.getPropertyName(r),n=t.build(e,r.type);return e.addLineFlowCode(`${i} = ${n}`),i}}const _n=pi(Nn);Vr("temp",_n),Vr("toVar",((...e)=>_n(...e).append())),Rr("VarNode",Nn);class vn{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class Sn{constructor(e,t,s,r=void 0){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf(),this.needsUpdate=r}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class An{constructor(e,t){this.isNodeVar=!0,this.name=e,this.type=t}}class Rn extends An{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class Cn{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}class En{constructor(){this.keywords=[],this.nodes=[],this.keywordsCallback={}}getNode(e){let t=this.nodes[e];return void 0===t&&void 0!==this.keywordsCallback[e]&&(t=this.keywordsCallback[e](e),this.nodes[e]=t),t}addKeyword(e,t){return this.keywords.push(e),this.keywordsCallback[e]=t,this}parse(e){const t=this.keywords,s=new RegExp(`\\b${t.join("\\b|\\b")}\\b`,"g"),r=e.match(s),i=[];if(null!==r)for(const e of r){const t=this.getNode(e);void 0!==t&&-1===i.indexOf(t)&&i.push(t)}return i}include(e,t){const s=this.parse(t);for(const t of s)t.build(e)}}class wn extends Ar{constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Mn=(e,t)=>ci(new wn(e,t)),Fn=(e,t)=>ci(new wn(e,t,!0)),Bn=gi(wn,"vec4","DiffuseColor"),On=gi(wn,"float","Roughness"),Un=gi(wn,"float","Metalness"),Ln=gi(wn,"float","Clearcoat"),In=gi(wn,"float","ClearcoatRoughness"),Pn=gi(wn,"vec3","Sheen"),Dn=gi(wn,"float","SheenRoughness"),Vn=gi(wn,"float","Iridescence"),Gn=gi(wn,"float","IridescenceIOR"),kn=gi(wn,"float","IridescenceThickness"),zn=gi(wn,"color","SpecularColor"),$n=gi(wn,"float","Shininess"),Hn=gi(wn,"vec4","Output"),Wn=gi(wn,"float","dashSize"),jn=gi(wn,"float","gapSize"),qn=gi(wn,"float","pointWidth");Rr("PropertyNode",wn);class Xn extends wn{constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}const Yn=(e,t)=>ci(new Xn(e,t));Rr("ParameterNode",Xn);class Kn extends Ar{constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.language=s,this.includes=t}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const Qn=pi(Kn),Zn=(e,t)=>Qn(e,t,"js"),Jn=(e,t)=>Qn(e,t,"wgsl"),eo=(e,t)=>Qn(e,t,"glsl");Rr("CodeNode",Kn);class to extends Kn{constructor(e="",t=[],s=""){super(e,t,s),this.keywords={}}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),r=s.name,i=s.type,n=e.getCodeFromNode(this,i);""!==r&&(n.name=r);const o=e.getPropertyName(n);let a=this.getNodeFunction(e).getCode(o);const u=this.keywords,l=Object.keys(u);if(l.length>0)for(const t of l){const s=new RegExp(`\\b${t}\\b`,"g"),r=u[t].build(e,"property");a=a.replace(s,r)}return n.code=a+"\n","property"===t?o:e.format(`${o}()`,i,t)}}const so=(e,t=[],s="")=>{for(let e=0;er.call(...e);return i.functionNode=r,i},ro=(e,t)=>so(e,t,"glsl"),io=(e,t)=>so(e,t,"wgsl");Rr("FunctionNode",to);class no extends Ar{constructor(e,t=!1){super("string"),this.name=e,this.version=0,this.shared=t,this.isUniformGroup=!0}set needsUpdate(e){!0===e&&this.version++}}const oo=e=>new no(e),ao=e=>new no(e,!0),uo=ao("frame"),lo=ao("render"),co=oo("object");Rr("UniformGroupNode",no);class ho extends Lr{constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.groupNode=co}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}generate(e,t){const s=this.getNodeType(e),r=this.getUniformHash(e);let i=e.getNodeFromHash(r);void 0===i&&(e.setHashNode(this,r),i=this);const n=i.getInputType(e),o=e.getUniformFromNode(i,n,e.shaderStage,e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const po=(e,t)=>{const s=ui(t||e),r=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return ci(new ho(r,s))};Rr("UniformNode",ho);class go extends on{constructor(e=0){super(null,"vec2"),this.isUVNode=!0,this.index=e}getAttributeName(){const e=this.index;return"uv"+(e>0?e:"")}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const mo=(...e)=>ci(new go(...e));Rr("UVNode",go);class fo extends Ar{constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),r=this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${r} )`,this.getNodeType(e),t)}}const To=pi(fo);Vr("textureSize",To),Rr("TextureSizeNode",fo);class xo extends Er{constructor(e,t,s,...r){if(super(),this.op=e,r.length>0){let t=s;for(let s=0;s>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"=="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}return"float"===n&&e.isMatrix(o)?o:e.isMatrix(n)&&e.isVector(o)?e.getVectorFromMatrix(n):e.isVector(n)&&e.isMatrix(o)?e.getVectorFromMatrix(o):e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,r=this.aNode,i=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=r.getNodeType(e),a=void 0!==i?i.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s?e.isVector(o)?a=o:o=a="float":">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):e.isMatrix(o)&&e.isVector(a)?a=e.getVectorFromMatrix(o):o=e.isVector(o)&&e.isMatrix(a)?e.getVectorFromMatrix(a):a=n):o=a=n;const u=r.build(e,o),l=void 0!==i?i.build(e,a):null,c=e.getTypeLength(t),d=e.getFunctionOperator(s);return"void"!==t?"<"===s&&c>1?e.format(`${e.getMethod("lessThan")}( ${u}, ${l} )`,n,t):"<="===s&&c>1?e.format(`${e.getMethod("lessThanEqual")}( ${u}, ${l} )`,n,t):">"===s&&c>1?e.format(`${e.getMethod("greaterThan")}( ${u}, ${l} )`,n,t):">="===s&&c>1?e.format(`${e.getMethod("greaterThanEqual")}( ${u}, ${l} )`,n,t):"!"===s||"~"===s?e.format(`(${s}${u})`,o,t):d?e.format(`${d}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${s} ${l} )`,n,t):"void"!==o?d?e.format(`${d}( ${u}, ${l} )`,n,t):e.format(`${u} ${s} ${l}`,n,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const yo=pi(xo,"+"),bo=pi(xo,"-"),No=pi(xo,"*"),_o=pi(xo,"/"),vo=pi(xo,"%"),So=pi(xo,"=="),Ao=pi(xo,"!="),Ro=pi(xo,"<"),Co=pi(xo,">"),Eo=pi(xo,"<="),wo=pi(xo,">="),Mo=pi(xo,"&&"),Fo=pi(xo,"||"),Bo=pi(xo,"!"),Oo=pi(xo,"^^"),Uo=pi(xo,"&"),Lo=pi(xo,"~"),Io=pi(xo,"|"),Po=pi(xo,"^"),Do=pi(xo,"<<"),Vo=pi(xo,">>");Vr("add",yo),Vr("sub",bo),Vr("mul",No),Vr("div",_o),Vr("remainder",vo),Vr("equal",So),Vr("notEqual",Ao),Vr("lessThan",Ro),Vr("greaterThan",Co),Vr("lessThanEqual",Eo),Vr("greaterThanEqual",wo),Vr("and",Mo),Vr("or",Fo),Vr("not",Bo),Vr("xor",Oo),Vr("bitAnd",Uo),Vr("bitNot",Lo),Vr("bitOr",Io),Vr("bitXor",Po),Vr("shiftLeft",Do),Vr("shiftRight",Vo),Rr("OperatorNode",xo);class Go extends Er{constructor(e,t,s=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=s,this.cNode=r}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(r)?0:e.getTypeLength(r);return i>n&&i>o?t:n>o?s:o>i?r:t}getNodeType(e){const t=this.method;return t===Go.LENGTH||t===Go.DISTANCE||t===Go.DOT?"float":t===Go.CROSS?"vec3":t===Go.ALL?"bool":t===Go.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===Go.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){const s=this.method,r=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,u=!0===e.renderer.isWebGLRenderer;if(s===Go.TRANSFORM_DIRECTION){let s=n,r=o;e.isMatrix(s.getNodeType(e))?r=Ui(Mi(r),0):s=Ui(Mi(s),0);const i=No(s,r).xyz;return ia(i).build(e,t)}if(s===Go.NEGATE)return e.format("( - "+n.build(e,i)+" )",r,t);if(s===Go.ONE_MINUS)return bo(1,n).build(e,t);if(s===Go.RECIPROCAL)return _o(1,n).build(e,t);if(s===Go.DIFFERENCE)return ha(bo(n,o)).build(e,t);{const l=[];return s===Go.CROSS||s===Go.MOD?l.push(n.build(e,r),o.build(e,r)):s===Go.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),o.build(e,i)):u&&(s===Go.MIN||s===Go.MAX)||s===Go.MOD?l.push(n.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):s===Go.REFRACT?l.push(n.build(e,i),o.build(e,i),a.build(e,"float")):s===Go.MIX?l.push(n.build(e,i),o.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)):(l.push(n.build(e,i)),null!==o&&l.push(o.build(e,i)),null!==a&&l.push(a.build(e,i))),e.format(`${e.getMethod(s,r)}( ${l.join(", ")} )`,r,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Go.ALL="all",Go.ANY="any",Go.EQUALS="equals",Go.RADIANS="radians",Go.DEGREES="degrees",Go.EXP="exp",Go.EXP2="exp2",Go.LOG="log",Go.LOG2="log2",Go.SQRT="sqrt",Go.INVERSE_SQRT="inversesqrt",Go.FLOOR="floor",Go.CEIL="ceil",Go.NORMALIZE="normalize",Go.FRACT="fract",Go.SIN="sin",Go.COS="cos",Go.TAN="tan",Go.ASIN="asin",Go.ACOS="acos",Go.ATAN="atan",Go.ABS="abs",Go.SIGN="sign",Go.LENGTH="length",Go.NEGATE="negate",Go.ONE_MINUS="oneMinus",Go.DFDX="dFdx",Go.DFDY="dFdy",Go.ROUND="round",Go.RECIPROCAL="reciprocal",Go.TRUNC="trunc",Go.FWIDTH="fwidth",Go.BITCAST="bitcast",Go.ATAN2="atan2",Go.MIN="min",Go.MAX="max",Go.MOD="mod",Go.STEP="step",Go.REFLECT="reflect",Go.DISTANCE="distance",Go.DIFFERENCE="difference",Go.DOT="dot",Go.CROSS="cross",Go.POW="pow",Go.TRANSFORM_DIRECTION="transformDirection",Go.MIX="mix",Go.CLAMP="clamp",Go.REFRACT="refract",Go.SMOOTHSTEP="smoothstep",Go.FACEFORWARD="faceforward";const ko=_i(1e-6),zo=_i(1e6),$o=_i(Math.PI),Ho=_i(2*Math.PI),Wo=pi(Go,Go.ALL),jo=pi(Go,Go.ANY),qo=pi(Go,Go.EQUALS),Xo=pi(Go,Go.RADIANS),Yo=pi(Go,Go.DEGREES),Ko=pi(Go,Go.EXP),Qo=pi(Go,Go.EXP2),Zo=pi(Go,Go.LOG),Jo=pi(Go,Go.LOG2),ea=pi(Go,Go.SQRT),ta=pi(Go,Go.INVERSE_SQRT),sa=pi(Go,Go.FLOOR),ra=pi(Go,Go.CEIL),ia=pi(Go,Go.NORMALIZE),na=pi(Go,Go.FRACT),oa=pi(Go,Go.SIN),aa=pi(Go,Go.COS),ua=pi(Go,Go.TAN),la=pi(Go,Go.ASIN),ca=pi(Go,Go.ACOS),da=pi(Go,Go.ATAN),ha=pi(Go,Go.ABS),pa=pi(Go,Go.SIGN),ga=pi(Go,Go.LENGTH),ma=pi(Go,Go.NEGATE),fa=pi(Go,Go.ONE_MINUS),Ta=pi(Go,Go.DFDX),xa=pi(Go,Go.DFDY),ya=pi(Go,Go.ROUND),ba=pi(Go,Go.RECIPROCAL),Na=pi(Go,Go.TRUNC),_a=pi(Go,Go.FWIDTH),va=pi(Go,Go.BITCAST),Sa=pi(Go,Go.ATAN2),Aa=pi(Go,Go.MIN),Ra=pi(Go,Go.MAX),Ca=pi(Go,Go.MOD),Ea=pi(Go,Go.STEP),wa=pi(Go,Go.REFLECT),Ma=pi(Go,Go.DISTANCE),Fa=pi(Go,Go.DIFFERENCE),Ba=pi(Go,Go.DOT),Oa=pi(Go,Go.CROSS),Ua=pi(Go,Go.POW),La=pi(Go,Go.POW,2),Ia=pi(Go,Go.POW,3),Pa=pi(Go,Go.POW,4),Da=pi(Go,Go.TRANSFORM_DIRECTION),Va=e=>No(pa(e),Ua(ha(e),1/3)),Ga=e=>Ba(e,e),ka=pi(Go,Go.MIX),za=(e,t=0,s=1)=>ci(new Go(Go.CLAMP,ci(e),ci(t),ci(s))),$a=e=>za(e),Ha=pi(Go,Go.REFRACT),Wa=pi(Go,Go.SMOOTHSTEP),ja=pi(Go,Go.FACEFORWARD);Vr("all",Wo),Vr("any",jo),Vr("equals",qo),Vr("radians",Xo),Vr("degrees",Yo),Vr("exp",Ko),Vr("exp2",Qo),Vr("log",Zo),Vr("log2",Jo),Vr("sqrt",ea),Vr("inverseSqrt",ta),Vr("floor",sa),Vr("ceil",ra),Vr("normalize",ia),Vr("fract",na),Vr("sin",oa),Vr("cos",aa),Vr("tan",ua),Vr("asin",la),Vr("acos",ca),Vr("atan",da),Vr("abs",ha),Vr("sign",pa),Vr("length",ga),Vr("lengthSq",Ga),Vr("negate",ma),Vr("oneMinus",fa),Vr("dFdx",Ta),Vr("dFdy",xa),Vr("round",ya),Vr("reciprocal",ba),Vr("trunc",Na),Vr("fwidth",_a),Vr("atan2",Sa),Vr("min",Aa),Vr("max",Ra),Vr("mod",Ca),Vr("step",Ea),Vr("reflect",wa),Vr("distance",Ma),Vr("dot",Ba),Vr("cross",Oa),Vr("pow",Ua),Vr("pow2",La),Vr("pow3",Ia),Vr("pow4",Pa),Vr("transformDirection",Da),Vr("mix",((e,t,s)=>ka(t,s,e))),Vr("clamp",za),Vr("refract",Ha),Vr("smoothstep",((e,t,s)=>Wa(t,s,e))),Vr("faceForward",ja),Vr("difference",Fa),Vr("saturate",$a),Vr("cbrt",Va),Rr("MathNode",Go);const qa=fi((e=>{const{value:t}=e,{rgb:s}=t,r=s.mul(.9478672986).add(.0521327014).pow(2.4),i=s.mul(.0773993808),n=s.lessThanEqual(.04045),o=ka(r,i,n);return Ui(o,t.a)})),Xa=fi((e=>{const{value:t}=e,{rgb:s}=t,r=s.pow(.41666).mul(1.055).sub(.055),i=s.mul(12.92),n=s.lessThanEqual(.0031308),o=ka(r,i,n);return Ui(o,t.a)})),Ya=e=>{let t=null;return e===h?t="Linear":e===p&&(t="sRGB"),t},Ka=(e,t)=>Ya(e)+"To"+Ya(t);class Qa extends Er{constructor(e,t){super("vec4"),this.method=e,this.node=t}setup(){const{method:e,node:t}=this;return e===Qa.LINEAR_TO_LINEAR?t:Za[e]({value:t})}}Qa.LINEAR_TO_LINEAR="LinearToLinear",Qa.LINEAR_TO_sRGB="LinearTosRGB",Qa.sRGB_TO_LINEAR="sRGBToLinear";const Za={[Qa.LINEAR_TO_sRGB]:Xa,[Qa.sRGB_TO_LINEAR]:qa},Ja=(e,t)=>ci(new Qa(Ka(h,t),ci(e))),eu=(e,t)=>ci(new Qa(Ka(t,h),ci(e))),tu=pi(Qa,Qa.LINEAR_TO_sRGB),su=pi(Qa,Qa.sRGB_TO_LINEAR);Vr("linearTosRGB",tu),Vr("sRGBToLinear",su),Vr("linearToColorSpace",Ja),Vr("colorSpaceToLinear",eu),Rr("ColorSpaceNode",Qa);class ru extends Ar{constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),r=this.snippet;if("void"!==s)return e.format(`( ${r} )`,s,t);e.addLineFlowCode(r)}}const iu=pi(ru);Rr("ExpressionNode",ru);class nu extends ho{constructor(e){super(0),this.textureNode=e,this.updateType=cr.FRAME}get texture(){return this.textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const ou=pi(nu);Rr("MaxMipLevelNode",nu);class au extends ho{constructor(e,t=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.compareNode=null,this.depthNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=cr.NONE,this.setUpdateMatrix(null===t)}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":"vec4"}getInputType(){return"texture"}getDefaultUV(){return mo(this.value.channel)}setReference(){return this.value}getTransformedUV(e){const t=this.value;return po(t.matrix).mul(Mi(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?cr.FRAME:cr.NONE,this}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture&&!0!==s.isDepthTexture||(t=t.setY(t.y.oneMinus())),t}setup(e){const t=e.getNodeProperties(this);let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),null!==r&&void 0!==e.context.getTextureLevelAlgorithm&&(r=e.context.getTextureLevelAlgorithm(this,r)),t.uvNode=s,t.levelNode=r,t.compareNode=this.compareNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,r,i,n){const o=this.value;let a;return a=r?e.generateTextureLevel(o,t,s,r,i):n?e.generateTextureCompare(o,t,s,n,i):!1===this.sampler?e.generateTextureLoad(o,t,s,i):e.generateTexture(o,t,s,i),a}generate(e,t){const s=e.getNodeProperties(this),r=this.value;if(!r||!0!==r.isTexture)throw new Error("TextureNode: Need a three.js texture.");const i=super.generate(e,"property");if("sampler"===t)return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:r,compareNode:a,depthNode:u}=s,l=this.generateUV(e,t),c=r?r.build(e,"float"):null,d=u?u.build(e,"int"):null,h=a?a.build(e,"float"):null,p=e.getVarFromNode(this);o=e.getPropertyName(p);const g=this.generateSnippet(e,i,l,c,d,h);e.addLineFlowCode(`${o} = ${g}`),!1!==e.context.tempWrite&&(n.snippet=g,n.propertyName=o)}let a=o;const u=this.getNodeType(e);return e.needsColorSpaceToLinear(r)&&(a=eu(iu(a,u),r.colorSpace).setup(e).build(e,u)),e.format(a,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){const t=this.clone();return t.uvNode=e,ci(t)}blur(e){const t=this.clone();return t.levelNode=e.mul(ou(t)),ci(t)}level(e){const t=this.clone();return t.levelNode=e,t}size(e){return To(this,e)}compare(e){const t=this.clone();return t.compareNode=ci(e),ci(t)}depth(e){const t=this.clone();return t.depthNode=ci(e),ci(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value]}update(){const e=this.value;!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e}}const uu=pi(au),lu=(...e)=>uu(...e).setSampler(!1),cu=e=>(!0===e.isNode?e:uu(e)).convert("sampler");Vr("texture",uu),Rr("TextureNode",au);class du extends ho{constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getInputType(){return"buffer"}}const hu=(e,t,s)=>ci(new du(e,t,s));Rr("BufferNode",du);class pu extends wr{constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=super.generate(e),s=this.getNodeType();return e.format(t,"vec4",s)}}class gu extends du{constructor(e,t=null){super(null,"vec4"),this.array=e,this.elementType=t,this._elementType=null,this._elementLength=0,this.updateType=cr.RENDER,this.isArrayBufferNode=!0}getElementType(){return this.elementType||this._elementType}getElementLength(){return this._elementLength}update(){const{array:e,value:t}=this,s=this.getElementLength(),r=this.getElementType();if(1===s)for(let s=0;sci(new gu(e,t));Rr("UniformsNode",gu);class fu extends wr{constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,s,r)}}class Tu extends Ar{constructor(e,t,s=null,r=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=r,this.properties=e.split("."),this.reference=null,this.node=null,this.updateType=cr.OBJECT}element(e){return ci(new fu(this,ci(e)))}setNodeType(e){let t=null;t=null!==this.count?hu(null,e,this.count):Array.isArray(this.getValueFromReference())?mu(null,e):"texture"===e?uu(null):po(null,e),this.node=t}getNodeType(e){return this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;eci(new Tu(e,t,s)),yu=(e,t,s,r)=>ci(new Tu(e,t,r,s));Rr("ReferenceNode",Tu);class bu extends Tu{constructor(e,t,s=null){super(e,t,s),this.material=s}setReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Nu=(e,t,s)=>ci(new bu(e,t,s));Rr("MaterialReferenceNode",bu);class _u extends Ar{constructor(e=_u.VIEW_MATRIX,t=null){super(),this.scope=e,this.object3d=t,this.updateType=cr.OBJECT,this._uniformNode=new ho(null)}getNodeType(){const e=this.scope;return e===_u.WORLD_MATRIX||e===_u.VIEW_MATRIX?"mat4":e===_u.NORMAL_MATRIX?"mat3":e===_u.POSITION||e===_u.VIEW_POSITION||e===_u.DIRECTION||e===_u.SCALE?"vec3":void 0}update(e){const t=this.object3d,s=this._uniformNode,r=this.scope;if(r===_u.VIEW_MATRIX)s.value=t.modelViewMatrix;else if(r===_u.NORMAL_MATRIX)s.value=t.normalMatrix;else if(r===_u.WORLD_MATRIX)s.value=t.matrixWorld;else if(r===_u.POSITION)s.value=s.value||new u,s.value.setFromMatrixPosition(t.matrixWorld);else if(r===_u.SCALE)s.value=s.value||new u,s.value.setFromMatrixScale(t.matrixWorld);else if(r===_u.DIRECTION)s.value=s.value||new u,t.getWorldDirection(s.value);else if(r===_u.VIEW_POSITION){const r=e.camera;s.value=s.value||new u,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(r.matrixWorldInverse)}}generate(e){const t=this.scope;return t===_u.WORLD_MATRIX||t===_u.VIEW_MATRIX?this._uniformNode.nodeType="mat4":t===_u.NORMAL_MATRIX?this._uniformNode.nodeType="mat3":t!==_u.POSITION&&t!==_u.VIEW_POSITION&&t!==_u.DIRECTION&&t!==_u.SCALE||(this._uniformNode.nodeType="vec3"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}_u.VIEW_MATRIX="viewMatrix",_u.NORMAL_MATRIX="normalMatrix",_u.WORLD_MATRIX="worldMatrix",_u.POSITION="position",_u.SCALE="scale",_u.VIEW_POSITION="viewPosition",_u.DIRECTION="direction";const vu=pi(_u,_u.DIRECTION),Su=pi(_u,_u.VIEW_MATRIX),Au=pi(_u,_u.NORMAL_MATRIX),Ru=pi(_u,_u.WORLD_MATRIX),Cu=pi(_u,_u.POSITION),Eu=pi(_u,_u.SCALE),wu=pi(_u,_u.VIEW_POSITION);Rr("Object3DNode",_u);class Mu extends _u{constructor(e=Mu.POSITION){super(e),this.updateType=cr.RENDER}getNodeType(e){const t=this.scope;return t===Mu.PROJECTION_MATRIX||t===Mu.PROJECTION_MATRIX_INVERSE?"mat4":t===Mu.NEAR||t===Mu.FAR||t===Mu.LOG_DEPTH?"float":super.getNodeType(e)}update(e){const t=e.camera,s=this._uniformNode,r=this.scope;r===Mu.VIEW_MATRIX?s.value=t.matrixWorldInverse:r===Mu.PROJECTION_MATRIX?s.value=t.projectionMatrix:r===Mu.PROJECTION_MATRIX_INVERSE?s.value=t.projectionMatrixInverse:r===Mu.NEAR?s.value=t.near:r===Mu.FAR?s.value=t.far:r===Mu.LOG_DEPTH?s.value=2/(Math.log(t.far+1)/Math.LN2):(this.object3d=t,super.update(e))}generate(e){const t=this.scope;return t===Mu.PROJECTION_MATRIX||t===Mu.PROJECTION_MATRIX_INVERSE?this._uniformNode.nodeType="mat4":t!==Mu.NEAR&&t!==Mu.FAR&&t!==Mu.LOG_DEPTH||(this._uniformNode.nodeType="float"),super.generate(e)}}Mu.PROJECTION_MATRIX="projectionMatrix",Mu.PROJECTION_MATRIX_INVERSE="projectionMatrixInverse",Mu.NEAR="near",Mu.FAR="far",Mu.LOG_DEPTH="logDepth";const Fu=gi(Mu,Mu.PROJECTION_MATRIX),Bu=gi(Mu,Mu.PROJECTION_MATRIX_INVERSE),Ou=gi(Mu,Mu.NEAR),Uu=gi(Mu,Mu.FAR),Lu=gi(Mu,Mu.LOG_DEPTH),Iu=gi(Mu,Mu.VIEW_MATRIX),Pu=gi(Mu,Mu.NORMAL_MATRIX),Du=gi(Mu,Mu.WORLD_MATRIX),Vu=gi(Mu,Mu.POSITION);Rr("CameraNode",Mu);class Gu extends _u{constructor(e=Gu.VIEW_MATRIX){super(e)}update(e){this.object3d=e.object,super.update(e)}}const ku=gi(Gu,Gu.DIRECTION),zu=gi(Gu,Gu.VIEW_MATRIX).label("modelViewMatrix").temp("ModelViewMatrix"),$u=gi(Gu,Gu.NORMAL_MATRIX),Hu=gi(Gu,Gu.WORLD_MATRIX),Wu=gi(Gu,Gu.POSITION),ju=gi(Gu,Gu.SCALE),qu=gi(Gu,Gu.VIEW_POSITION);Rr("ModelNode",Gu);class Xu extends Ar{constructor(e=Xu.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`normal-${this.scope}`}generate(e){const t=this.scope;let s=null;if(t===Xu.GEOMETRY)s=an("normal","vec3");else if(t===Xu.LOCAL)s=nn(Yu);else if(t===Xu.VIEW){const e=$u.mul(Ku);s=ia(nn(e))}else if(t===Xu.WORLD){const e=Qu.transformDirection(Iu);s=ia(nn(e))}return s.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Xu.GEOMETRY="geometry",Xu.LOCAL="local",Xu.VIEW="view",Xu.WORLD="world";const Yu=gi(Xu,Xu.GEOMETRY),Ku=gi(Xu,Xu.LOCAL).temp("Normal"),Qu=gi(Xu,Xu.VIEW),Zu=gi(Xu,Xu.WORLD),Ju=Mn("vec3","TransformedNormalView"),el=Ju.transformDirection(Iu).normalize(),tl=Mn("vec3","TransformedClearcoatNormalView");Rr("NormalNode",Xu);const sl=new Map;class rl extends Ar{constructor(e){super(),this.scope=e}getCache(e,t){let s=sl.get(e);return void 0===s&&(s=Nu(e,t),sl.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let r=null;if(s===rl.COLOR){const e=this.getColor(s);r=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===rl.OPACITY){const e=this.getFloat(s);r=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===rl.SPECULAR_STRENGTH)r=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture(s).r:_i(1);else if(s===rl.ROUGHNESS){const e=this.getFloat(s);r=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===rl.METALNESS){const e=this.getFloat(s);r=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===rl.EMISSIVE){const e=this.getColor(s);r=t.emissiveMap&&!0===t.emissiveMap.isTexture?e.mul(this.getTexture(s)):e}else if(s===rl.NORMAL)r=t.normalMap?this.getTexture("normal").normalMap(this.getCache("normalScale","vec2")):t.bumpMap?this.getTexture("bump").r.bumpMap(this.getFloat("bumpScale")):Qu;else if(s===rl.CLEARCOAT){const e=this.getFloat(s);r=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===rl.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);r=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===rl.CLEARCOAT_NORMAL)r=t.clearcoatNormalMap?this.getTexture(s).normalMap(this.getCache(s+"Scale","vec2")):Qu;else if(s===rl.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));r=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===rl.SHEEN_ROUGHNESS){const e=this.getFloat(s);r=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,r=r.clamp(.07,1)}else if(s===rl.IRIDESCENCE_THICKNESS){const e=xu("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=xu("0","float",t.iridescenceThicknessRange);r=e.sub(i).mul(this.getTexture(s).g).add(i)}else r=e}else{const t=this.getNodeType(e);r=this.getCache(s,t)}return r}}rl.ALPHA_TEST="alphaTest",rl.COLOR="color",rl.OPACITY="opacity",rl.SHININESS="shininess",rl.SPECULAR_COLOR="specular",rl.SPECULAR_STRENGTH="specularStrength",rl.REFLECTIVITY="reflectivity",rl.ROUGHNESS="roughness",rl.METALNESS="metalness",rl.NORMAL="normal",rl.CLEARCOAT="clearcoat",rl.CLEARCOAT_ROUGHNESS="clearcoatRoughness",rl.CLEARCOAT_NORMAL="clearcoatNormal",rl.EMISSIVE="emissive",rl.ROTATION="rotation",rl.SHEEN="sheen",rl.SHEEN_ROUGHNESS="sheenRoughness",rl.IRIDESCENCE="iridescence",rl.IRIDESCENCE_IOR="iridescenceIOR",rl.IRIDESCENCE_THICKNESS="iridescenceThickness",rl.LINE_SCALE="scale",rl.LINE_DASH_SIZE="dashSize",rl.LINE_GAP_SIZE="gapSize",rl.LINE_WIDTH="linewidth",rl.LINE_DASH_OFFSET="dashOffset",rl.POINT_WIDTH="pointWidth";const il=gi(rl,rl.ALPHA_TEST),nl=gi(rl,rl.COLOR),ol=gi(rl,rl.SHININESS),al=gi(rl,rl.EMISSIVE),ul=gi(rl,rl.OPACITY),ll=gi(rl,rl.SPECULAR_COLOR),cl=gi(rl,rl.SPECULAR_STRENGTH),dl=gi(rl,rl.REFLECTIVITY),hl=gi(rl,rl.ROUGHNESS),pl=gi(rl,rl.METALNESS),gl=gi(rl,rl.NORMAL),ml=gi(rl,rl.CLEARCOAT),fl=gi(rl,rl.CLEARCOAT_ROUGHNESS),Tl=gi(rl,rl.CLEARCOAT_NORMAL),xl=gi(rl,rl.ROTATION),yl=gi(rl,rl.SHEEN),bl=gi(rl,rl.SHEEN_ROUGHNESS),Nl=gi(rl,rl.IRIDESCENCE),_l=gi(rl,rl.IRIDESCENCE_IOR),vl=gi(rl,rl.IRIDESCENCE_THICKNESS),Sl=gi(rl,rl.LINE_SCALE),Al=gi(rl,rl.LINE_DASH_SIZE),Rl=gi(rl,rl.LINE_GAP_SIZE),Cl=gi(rl,rl.LINE_WIDTH),El=gi(rl,rl.LINE_DASH_OFFSET),wl=gi(rl,rl.POINT_WIDTH);Rr("MaterialNode",rl);class Ml extends Ar{constructor(e=Ml.LOCAL){super("vec3"),this.scope=e}isGlobal(){return!0}getHash(){return`position-${this.scope}`}generate(e){const t=this.scope;let s=null;if(t===Ml.GEOMETRY)s=an("position","vec3");else if(t===Ml.LOCAL)s=nn(Fl);else if(t===Ml.WORLD){const e=Hu.mul(Bl);s=nn(e)}else if(t===Ml.VIEW){const e=zu.mul(Bl);s=nn(e)}else if(t===Ml.VIEW_DIRECTION){const e=Ll.negate();s=ia(nn(e))}else if(t===Ml.WORLD_DIRECTION){const e=Bl.transformDirection(Hu);s=ia(nn(e))}return s.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Ml.GEOMETRY="geometry",Ml.LOCAL="local",Ml.WORLD="world",Ml.WORLD_DIRECTION="worldDirection",Ml.VIEW="view",Ml.VIEW_DIRECTION="viewDirection";const Fl=gi(Ml,Ml.GEOMETRY),Bl=gi(Ml,Ml.LOCAL).temp("Position"),Ol=gi(Ml,Ml.WORLD),Ul=gi(Ml,Ml.WORLD_DIRECTION),Ll=gi(Ml,Ml.VIEW),Il=gi(Ml,Ml.VIEW_DIRECTION);Rr("PositionNode",Ml);class Pl extends Er{constructor(e=null){super("vec4"),this.positionNode=e}setup(e){if("fragment"===e.shaderStage)return nn(e.context.mvp);const t=this.positionNode||Bl;return Fu.mul(zu).mul(t)}}const Dl=pi(Pl);Rr("ModelViewProjectionNode",Pl);class Vl extends Lr{constructor(e,t=null,s=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=r,this.usage=g,this.instanced=!1,this.attribute=null,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),s=this.value,r=e.getTypeLength(t),i=this.bufferStride||r,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new m(s,i),a=new f(o,r,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),r=e.getPropertyName(s);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=r,i=r;else{i=nn(this).build(e,t)}return i}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this}setInstanced(e){return this.instanced=e,this}}const Gl=(e,t,s,r)=>ci(new Vl(e,t,s,r)),kl=(e,t,s,i)=>Gl(e,t,s,i).setUsage(r),zl=(e,t,s,r)=>Gl(e,t,s,r).setInstanced(!0),$l=(e,t,s,r)=>kl(e,t,s,r).setInstanced(!0);Vr("toAttribute",(e=>Gl(e.value))),Rr("BufferAttributeNode",Vl);class Hl extends Ar{constructor(e){super("void"),this.instanceMesh=e,this.instanceMatrixNode=null}setup(){let e=this.instanceMatrixNode;if(null===e){const t=this.instanceMesh.instanceMatrix,s=new T(t.array,16,1),i=t.usage===r?$l:zl,n=[i(s,"vec4",16,0),i(s,"vec4",16,4),i(s,"vec4",16,8),i(s,"vec4",16,12)];e=ji(...n),this.instanceMatrixNode=e}const t=e.mul(Bl).xyz,s=zi(e[0].xyz,e[1].xyz,e[2].xyz),i=Ku.div(Mi(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2]))),n=s.mul(i).xyz;Bl.assign(t),Ku.assign(n)}}const Wl=pi(Hl);Rr("InstanceNode",Hl);class jl extends Ar{constructor(e=jl.LOCAL){super(),this.scope=e}getHash(){return`tangent-${this.scope}`}getNodeType(){return this.scope===jl.GEOMETRY?"vec4":"vec3"}generate(e){const t=this.scope;let s=null;if(t===jl.GEOMETRY)s=an("tangent","vec4"),!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents();else if(t===jl.LOCAL)s=nn(ql.xyz);else if(t===jl.VIEW){const e=zu.mul(Ui(Xl,0)).xyz;s=ia(nn(e))}else if(t===jl.WORLD){const e=Yl.transformDirection(Iu);s=ia(nn(e))}return s.build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}jl.GEOMETRY="geometry",jl.LOCAL="local",jl.VIEW="view",jl.WORLD="world";const ql=gi(jl,jl.GEOMETRY),Xl=gi(jl,jl.LOCAL),Yl=gi(jl,jl.VIEW),Kl=gi(jl,jl.WORLD),Ql=_n(Yl,"TransformedTangentView"),Zl=ia(Ql.transformDirection(Iu));Rr("TangentNode",jl);class Jl extends Ar{constructor(e,t=!1){let s,r,i;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=cr.OBJECT,this.skinIndexNode=an("skinIndex","uvec4"),this.skinWeightNode=an("skinWeight","vec4"),t?(s=xu("bindMatrix","mat4"),r=xu("bindMatrixInverse","mat4"),i=yu("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(s=po(e.bindMatrix,"mat4"),r=po(e.bindMatrixInverse,"mat4"),i=hu(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=s,this.bindMatrixInverseNode=r,this.boneMatricesNode=i}setup(e){const{skinIndexNode:t,skinWeightNode:s,bindMatrixNode:r,bindMatrixInverseNode:i,boneMatricesNode:n}=this,o=n.element(t.x),a=n.element(t.y),u=n.element(t.z),l=n.element(t.w),c=r.mul(Bl),d=yo(o.mul(s.x).mul(c),a.mul(s.y).mul(c),u.mul(s.z).mul(c),l.mul(s.w).mul(c)),h=i.mul(d).xyz;let p=yo(s.x.mul(o),s.y.mul(a),s.z.mul(u),s.w.mul(l));p=i.mul(p).mul(r);const g=p.transformDirection(Ku).xyz;Bl.assign(h),Ku.assign(g),e.hasGeometryAttribute("tangent")&&Xl.assign(g)}generate(e,t){if("void"!==t)return Bl.build(e,t)}update(e){(this.useReference?e.object:this.skinnedMesh).skeleton.update()}}const ec=e=>ci(new Jl(e));Rr("SkinningNode",Jl);class tc extends Ar{constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt()+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;eNumber(n)?">=":"<"));const c={start:i,end:n,condition:u},d=c.start,h=c.end;let p="",g="",m="";l||(l="int"===a||"uint"===a?u.includes("<")?"++":"--":u.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(a,o)+" = "+d,g+=o+" "+u+" "+h,m+=o+" "+l;const f=`for ( ${p}; ${g}; ${m} )`;e.addFlowCode((0===t?"\n":"")+e.tab+f+" {\n\n").addFlowTab()}const i=mn(r,{tempWrite:!1}).build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,s=this.params.length-1;tci(new tc(hi(e,"int"))).append(),rc=()=>iu("continue").append(),ic=()=>iu("break").append();Vr("loop",((e,...t)=>ln(e,sc(...t)))),Rr("LoopNode",tc);const nc=new WeakMap,oc=new s,ac=fi((({bufferMap:e,influence:t,stride:s,width:r,depth:i,offset:n})=>{const o=vi(xn).mul(s).add(n),a=o.div(r),u=o.sub(a.mul(r));return lu(e,Ci(u,a)).depth(i).mul(t)}));class uc extends Ar{constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=po(1),this.updateType=cr.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,r=void 0!==t.morphAttributes.normal,i=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==i?i.length:0,{texture:o,stride:u,size:l}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,r=void 0!==e.morphAttributes.color,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==i?i.length:0;let o=nc.get(e);if(void 0===o||o.count!==n){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],c=e.morphAttributes.color||[];let d=0;!0===t&&(d=1),!0===s&&(d=2),!0===r&&(d=3);let h=e.attributes.position.count*d,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*n),f=new x(m,h,p,n);f.type=y,f.needsUpdate=!0;const T=4*d;for(let N=0;N{const t=xu("morphTargetInfluences","float").element(e);!0===s&&Bl.addAssign(ac({bufferMap:o,influence:t,stride:u,width:c,depth:e,offset:vi(0)})),!0===r&&Ku.addAssign(ac({bufferMap:o,influence:t,stride:u,width:c,depth:e,offset:vi(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 lc=pi(uc);Rr("MorphNode",uc);class cc extends Ar{constructor(){super("vec3")}getHash(){return"reflectVector"}setup(){return Il.negate().reflect(Ju).transformDirection(Iu)}}const dc=gi(cc);Rr("ReflectVectorNode",cc);class hc extends au{constructor(e,t=null,s=null){super(e,t,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){return dc}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==b&&s.isRenderTargetTexture?t:Mi(t.x.negate(),t.yz)}generateUV(e,t){return t.build(e,"vec3")}}const pc=pi(hc);Vr("cubeTexture",pc),Rr("CubeTextureNode",hc);class gc extends Ar{constructor(){super("vec3")}generate(){}}Rr("LightingNode",gc);let mc=null;class fc extends gc{constructor(e=null){super(),this.updateType=cr.FRAME,this.light=e,this.rtt=null,this.shadowNode=null,this.color=new o,this._defaultColorNode=po(this.color),this.colorNode=this._defaultColorNode,this.isAnalyticLightNode=!0}getCacheKey(){return super.getCacheKey()+"-"+this.light.id+"-"+(this.light.castShadow?"1":"0")}getHash(){return this.light.uuid}setupShadow(e){let t=this.shadowNode;if(null===t){null===mc&&(mc=e.createNodeMaterial(),mc.fragmentNode=Ui(0,0,0,1),mc.isShadowNodeMaterial=!0);const s=this.light.shadow,r=e.getRenderTarget(s.mapSize.width,s.mapSize.height),i=new N;i.minFilter=_,i.magFilter=_,i.image.width=s.mapSize.width,i.image.height=s.mapSize.height,i.compareFunction=v,r.depthTexture=i,s.camera.updateProjectionMatrix();const n=xu("bias","float",s),o=xu("normalBias","float",s);let a=po(s.matrix).mul(Ol.add(Zu.mul(o)));a=a.xyz.div(a.w);const u=a.x.greaterThanEqual(0).and(a.x.lessThanEqual(1)).and(a.y.greaterThanEqual(0)).and(a.y.lessThanEqual(1)).and(a.z.lessThanEqual(1));let l=a.z.add(n);e.renderer.coordinateSystem===b&&(l=l.mul(2).sub(1)),a=Mi(a.x,a.y.oneMinus(),l);const c=(e,t,s)=>uu(e,t).compare(s);t=c(i,a.xy,a.z);const d=uu(r.texture,a);this.rtt=r,this.colorNode=this.colorNode.mul(u.mix(1,t.mix(d.a.mix(1,d),1))),this.shadowNode=t,this.updateBeforeType=cr.RENDER}}setup(e){this.light.castShadow?this.setupShadow(e):null!==this.shadowNode&&this.disposeShadow()}updateShadow(e){const{rtt:t,light:s}=this,{renderer:r,scene:i}=e,n=i.overrideMaterial;i.overrideMaterial=mc,t.setSize(s.shadow.mapSize.width,s.shadow.mapSize.height),s.shadow.updateMatrices(s);const o=r.getRenderTarget(),a=r.getRenderObjectFunction();r.setRenderObjectFunction(((e,...t)=>{!0===e.castShadow&&r.renderObject(e,...t)})),r.setRenderTarget(t),r.render(i,s.shadow.camera),r.setRenderTarget(o),r.setRenderObjectFunction(a),i.overrideMaterial=n}disposeShadow(){this.rtt.dispose(),this.shadowNode=null,this.rtt=null,this.colorNode=this._defaultColorNode}updateBefore(e){const{light:t}=this;t.castShadow&&this.updateShadow(e)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}Rr("AnalyticLightNode",fc);const Tc=new WeakMap;class xc extends Ar{constructor(e=[]){super("vec3"),this.totalDiffuseNode=Mi().temp("totalDiffuse"),this.totalSpecularNode=Mi().temp("totalSpecular"),this.outgoingLightNode=Mi().temp("outgoingLight"),this.lightNodes=e,this._hash=null}get hasLight(){return this.lightNodes.length>0}getHash(){if(null===this._hash){const e=[];for(const t of this.lightNodes)e.push(t.getHash());this._hash="lights-"+e.join(",")}return this._hash}setup(e){const t=e.context,s=t.lightingModel;let r=this.outgoingLightNode;if(s){const{lightNodes:i,totalDiffuseNode:n,totalSpecularNode:o}=this;t.outgoingLight=r;const a=e.addStack();s.start(t,a,e);for(const t of i)t.build(e);s.indirectDiffuse(t,a,e),s.indirectSpecular(t,a,e),s.ambientOcclusion(t,a,e);const{backdrop:u,backdropAlpha:l}=t,{directDiffuse:c,directSpecular:d,indirectDiffuse:h,indirectSpecular:p}=t.reflectedLight;let g=c.add(h);null!==u&&(g=Mi(null!==l?l.mix(g,u):u)),n.assign(g),o.assign(d.add(p)),r.assign(n.add(o)),s.finish(t,a,e),r=r.bypass(e.removeStack())}return r}_getLightNodeById(e){for(const t of this.lightNodes)if(t.isAnalyticLightNode&&t.light.id===e)return t;return null}fromLights(e=[]){const t=[];e=(e=>e.sort(((e,t)=>e.id-t.id)))(e);for(const s of e){let e=this._getLightNodeById(s.id);if(null===e){const t=s.constructor,r=Tc.has(t)?Tc.get(t):fc;e=ci(new r(s))}t.push(e)}return this.lightNodes=t,this._hash=null,this}}const yc=e=>ci((new xc).fromLights(e)),bc=pi(xc);function Nc(e,t){if(!Tc.has(e)){if("function"!=typeof e)throw new Error(`Light ${e.name} is not a class`);if("function"!=typeof t||!t.type)throw new Error(`Light node ${t.type} is not a class`);Tc.set(e,t)}}class _c extends gc{constructor(e=null){super(),this.aoNode=e}setup(e){const t=this.aoNode.x.sub(1).mul(1).add(1);e.context.ambientOcclusion.mulAssign(t)}}Rr("AONode",_c);class vc extends gn{constructor(e,t=null,s=null,r=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=r,this._context=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Mi().temp("directDiffuse"),directSpecular:Mi().temp("directSpecular"),indirectDiffuse:Mi().temp("indirectDiffuse"),indirectSpecular:Mi().temp("indirectSpecular")};return{radiance:Mi().temp("radiance"),irradiance:Mi().temp("irradiance"),iblIrradiance:Mi().temp("iblIrradiance"),ambientOcclusion:_i(1).temp("ambientOcclusion"),reflectedLight:s,backdrop:e,backdropAlpha:t}}setup(e){return this.context=this._context||(this._context=this.getContext()),this.context.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Sc=pi(vc);Vr("lightingContext",Sc),Rr("LightingContextNode",vc);class Ac extends Er{constructor(e=Ul){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan2(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.negate().clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Ri(t,s)}}const Rc=pi(Ac);Rr("EquirectUVNode",Ac);class Cc extends Ar{constructor(e,t=null){super("float"),this.textureNode=e,this.roughnessNode=t}setup(){const{textureNode:e,roughnessNode:t}=this,s=ou(e),r=t.mul(t).mul(Math.PI).div(t.add(1));return s.add(r.log2()).clamp(0,s)}}const Ec=pi(Cc);Rr("SpecularMIPLevelNode",Cc);const wc=new WeakMap;class Mc extends gc{constructor(e=null){super(),this.envNode=e}setup(e){let t=this.envNode;if(t.isTextureNode&&!0!==t.value.isCubeTexture){let s=wc.get(t.value);if(void 0===s){const r=t.value,i=e.renderer,n=e.getCubeRenderTarget(512).fromEquirectangularTexture(i,r);s=pc(n.texture),wc.set(t.value,s)}t=s}const s=xu("envMapIntensity","float",e.material),r=mn(t,Fc(On,Ju)).mul(s),i=mn(t,Bc(el)).mul(Math.PI).mul(s),n=pn(r);e.context.radiance.addAssign(n),e.context.iblIrradiance.addAssign(i);const o=e.context.lightingModel.clearcoatRadiance;if(o){const e=mn(t,Fc(In,tl)).mul(s),r=pn(e);o.addAssign(r)}}}const Fc=(e,t)=>{let s=null,r=null;return{getUV:i=>{let n=null;return null===s&&(s=Il.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Iu)),i.isCubeTextureNode?n=s:i.isTextureNode&&(null===r&&(r=Rc(s)),n=r),n},getTextureLevel:()=>e,getTextureLevelAlgorithm:(e,t)=>Ec(e,t)}},Bc=e=>{let t=null;return{getUV:s=>{let r=null;return s.isCubeTextureNode?r=e:s.isTextureNode&&(null===t&&(t=Rc(e),t=Ri(t.x,t.y.oneMinus())),r=t),r},getTextureLevel:e=>ou(e)}};let Oc,Uc;Rr("EnvironmentNode",Mc);class Lc extends Ar{constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Lc.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=cr.NONE;return this.scope!==Lc.RESOLUTION&&this.scope!==Lc.VIEWPORT||(e=cr.FRAME),this.updateType=e,e}update({renderer:e}){this.scope===Lc.VIEWPORT?e.getViewport(Uc):e.getDrawingBufferSize(Oc)}setup(){const e=this.scope;let t=null;if(e===Lc.RESOLUTION)t=po(Oc||(Oc=new a));else if(e===Lc.VIEWPORT)t=po(Uc||(Uc=new s));else{t=Ic.div(Pc);let s=t.x,r=t.y;/bottom/i.test(e)&&(r=r.oneMinus()),/right/i.test(e)&&(s=s.oneMinus()),t=Ri(s,r)}return t}generate(e){if(this.scope===Lc.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Pc).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Lc.COORDINATE="coordinate",Lc.RESOLUTION="resolution",Lc.VIEWPORT="viewport",Lc.TOP_LEFT="topLeft",Lc.BOTTOM_LEFT="bottomLeft",Lc.TOP_RIGHT="topRight",Lc.BOTTOM_RIGHT="bottomRight";const Ic=gi(Lc,Lc.COORDINATE),Pc=gi(Lc,Lc.RESOLUTION),Dc=gi(Lc,Lc.VIEWPORT),Vc=gi(Lc,Lc.TOP_LEFT),Gc=gi(Lc,Lc.BOTTOM_LEFT),kc=gi(Lc,Lc.TOP_RIGHT),zc=gi(Lc,Lc.BOTTOM_RIGHT);Rr("ViewportNode",Lc);const $c=new a;class Hc extends au{constructor(e=Vc,t=null,s=null){null===s&&((s=new S).minFilter=A),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=cr.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize($c);const s=this.value;s.image.width===$c.width&&s.image.height===$c.height||(s.image.width=$c.width,s.image.height=$c.height,s.needsUpdate=!0);const r=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=r}clone(){return new this.constructor(this.uvNode,this.levelNode,this.value)}}const Wc=pi(Hc),jc=pi(Hc,null,null,{generateMipmaps:!0});Vr("viewportTexture",Wc),Vr("viewportMipTexture",jc),Rr("ViewportTextureNode",Hc);let qc=null;class Xc extends Hc{constructor(e=Vc,t=null){null===qc&&(qc=new N),super(e,t,qc)}}const Yc=pi(Xc);Vr("viewportDepthTexture",Yc),Rr("ViewportDepthTextureNode",Xc);class Kc extends Ar{constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===Kc.DEPTH_PIXEL?e.getFragDepth():super.generate(e)}setup(){const{scope:e}=this;let t=null;if(e===Kc.DEPTH)t=Qc(Ll.z,Ou,Uu);else if(e===Kc.DEPTH_TEXTURE){const e=this.valueNode||Yc(),s=ed(e,Ou,Uu);t=Qc(s,Ou,Uu)}else e===Kc.DEPTH_PIXEL&&null!==this.valueNode&&(t=td().assign(this.valueNode));return t}}const Qc=(e,t,s)=>e.add(t).div(t.sub(s)),Zc=(e,t,s)=>t.sub(s).mul(e).sub(t),Jc=(e,t,s)=>t.add(e).mul(s).div(t.sub(s).mul(e)),ed=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s));Kc.DEPTH="depth",Kc.DEPTH_TEXTURE="depthTexture",Kc.DEPTH_PIXEL="depthPixel";const td=pi(Kc,Kc.DEPTH_PIXEL),sd=gi(Kc,Kc.DEPTH),rd=pi(Kc,Kc.DEPTH_TEXTURE),id=gi(Kc,Kc.DEPTH_PIXEL);id.assign=e=>td(e),Rr("ViewportDepthNode",Kc);class nd extends Ar{constructor(e=nd.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{localClipIntersection:s,localClippingCount:r,globalClippingCount:i}=t,n=i+r,o=s?n-r:n;return this.scope===nd.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(t.planes,n,o):this.setupDefault(t.planes,n,o)}setupAlphaToCoverage(e,t,s){return fi((()=>{const r=mu(e),i=Mn("float","distanceToPlane"),n=Mn("float","distanceToGradient"),o=Mn("float","clipOpacity");let a;if(o.assign(1),sc(s,(({i:e})=>{a=r.element(e),i.assign(Ll.dot(a.xyz).negate().add(a.w)),n.assign(i.fwidth().div(2)),o.mulAssign(Wa(n.negate(),n,i)),o.equal(0).discard()})),s{a=r.element(t),i.assign(Ll.dot(a.xyz).negate().add(a.w)),n.assign(i.fwidth().div(2)),e.mulAssign(Wa(n.negate(),n,i).oneMinus())})),o.mulAssign(e.oneMinus())}Bn.a.mulAssign(o),Bn.a.equal(0).discard()}))()}setupDefault(e,t,s){return fi((()=>{const r=mu(e);let i;if(sc(s,(({i:e})=>{i=r.element(e),Ll.dot(i.xyz).greaterThan(i.w).discard()})),s{i=r.element(t),e.assign(Ll.dot(i.xyz).greaterThan(i.w).and(e))})),e.discard()}}))()}}nd.ALPHA_TO_COVERAGE="alphaToCoverage",nd.DEFAULT="default";class od extends Ar{constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){return e.getFrontFacing()}}const ad=gi(od),ud=_i(ad).mul(2).sub(1);Rr("FrontFacingNode",od);const ld=new Map;class cd extends R{constructor(){super(),this.isNodeMaterial=!0,this.type=this.constructor.type,this.forceSinglePass=!1,this.fog=!0,this.lights=!0,this.normals=!0,this.colorSpaced=!0,this.lightsNode=null,this.envNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.positionNode=null,this.depthNode=null,this.shadowNode=null,this.outputNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+fr(this)}build(e){this.setup(e)}setup(e){let t;e.addStack(),e.stack.outputNode=this.vertexNode||this.setupPosition(e),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(null===this.fragmentNode){!0===this.depthWrite&&this.setupDepth(e),!0===this.normals&&this.setupNormal(e),this.setupDiffuseColor(e),this.setupVariants(e);const r=this.setupLighting(e);null!==s&&e.stack.add(s),t=this.setupOutput(e,Ui(r,Bn.a)),Hn.assign(t),null!==this.outputNode&&(t=this.outputNode)}else t=this.setupOutput(e,this.fragmentNode);e.stack.outputNode=t,e.addFlow("fragment",e.removeStack())}setupClipping(e){const{globalClippingCount:t,localClippingCount:s}=e.clippingContext;let r=null;return(t||s)&&(this.alphaToCoverage?r=ci(new nd(nd.ALPHA_TO_COVERAGE)):e.stack.add(ci(new nd))),r}setupDepth(e){const{renderer:t}=e;let s=this.depthNode;if(null===s&&!0===t.logarithmicDepthBuffer){s=Dl().w.add(1).log2().mul(Lu).mul(.5)}null!==s&&id.assign(s).append()}setupPosition(e){const{object:t}=e,s=t.geometry;var r;e.addStack(),(s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&lc(t).append(),!0===t.isSkinnedMesh&&(r=t,ci(new Jl(r,!0))).append(),t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&!0===e.isAvailable("instance")&&Wl(t).append(),null!==this.positionNode&&Bl.assign(this.positionNode);const i=Dl();return e.context.vertex=e.removeStack(),e.context.mvp=i,i}setupDiffuseColor({geometry:e}){let t=this.colorNode?Ui(this.colorNode):nl;!0===this.vertexColors&&e.hasAttribute("color")&&(t=Ui(t.xyz.mul(an("color","vec3")),t.a)),Bn.assign(t);const s=this.opacityNode?_i(this.opacityNode):ul;if(Bn.a.assign(Bn.a.mul(s)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?_i(this.alphaTestNode):il;Bn.a.lessThanEqual(e).discard()}}setupVariants(){}setupNormal(){if(!0===this.flatShading){const e=Ll.dFdx().cross(Ll.dFdy()).normalize();Ju.assign(e.mul(ud))}else{const e=this.normalNode?Mi(this.normalNode):gl;Ju.assign(e.mul(ud))}}getEnvNode(e){let t=null;return this.envNode?t=this.envNode:this.envMap?t=this.envMap.isCubeTexture?pc(this.envMap):uu(this.envMap):e.environmentNode&&(t=e.environmentNode),t}setupLights(e){const t=this.getEnvNode(e),s=[];t&&s.push(new Mc(t)),e.material.aoMap&&s.push(new _c(uu(e.material.aoMap)));let r=this.lightsNode||e.lightsNode;return s.length>0&&(r=bc([...r.lightNodes,...s])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:r,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=Bn.rgb;if(n&&!1!==n.hasLight){const t=this.setupLightingModel(e);o=Sc(n,t,s,r)}else null!==s&&(o=Mi(null!==r?ka(o,s,r):s));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(o=o.add(Mi(i||al))),o}setupOutput(e,t){const s=e.renderer,r=e.toneMappingNode;if(!0===this.toneMapped&&r&&(t=Ui(r.context({color:t.rgb}),t.a)),!0===this.fog){const s=e.fogNode;s&&(t=Ui(s.mixAssign(t.rgb),t.a))}if(!0===this.colorSpaced){const e=s.currentColorSpace;e!==h&&e!==C&&(t=t.linearToColorSpace(e))}return t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.clone()))}Object.assign(this.defines,e.defines);const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const s=E.prototype.toJSON.call(this,e),r=Tr(this);s.inputNodes={};for(const{property:t,childNode:i}of r)s.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const s in e){const r=e[s];delete r.metadata,t.push(r)}return t}if(t){const t=i(e.textures),r=i(e.images),n=i(e.nodes);t.length>0&&(s.textures=t),r.length>0&&(s.images=r),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.positionNode=e.positionNode,this.depthNode=e.depthNode,this.shadowNode=e.shadowNode,this.outputNode=e.outputNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}static fromMaterial(e){if(!0===e.isNodeMaterial)return e;const t=hd(e.type.replace("Material","NodeMaterial"));if(void 0===t)throw new Error(`NodeMaterial: Material "${e.type}" is not compatible.`);for(const s in e)t[s]=e[s];return t}}function dd(e,t){if("function"!=typeof t||!e)throw new Error(`Node material ${e} is not a class`);ld.has(e)||(ld.set(e,t),t.type=e)}function hd(e){const t=ld.get(e);if(void 0!==t)return new t}dd("NodeMaterial",cd);class pd{constructor(e,t=null){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 gd extends pd{constructor(e,t=0){super(e,t),this.isFloatUniform=!0,this.boundary=4,this.itemSize=1}}class md extends pd{constructor(e,t=new a){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class fd extends pd{constructor(e,t=new u){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Td extends pd{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class xd extends pd{constructor(e,t=new o){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class yd extends pd{constructor(e,s=new t){super(e,s),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class bd extends pd{constructor(e,t=new l){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Nd extends gd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class _d extends md{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class vd extends fd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Sd extends Td{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Ad extends xd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Rd extends yd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Cd extends bd{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}}class Ed extends Ar{constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const t=this.ifNode.getNodeType(e);if(null!==this.elseNode){const s=this.elseNode.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(t))return s}return t}generate(e,t){const s=this.getNodeType(e),r={tempWrite:!1},i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{ifNode:n,elseNode:o}=this,a="void"!==t,u=a?Mn(s).build(e):"";i.nodeProperty=u;const l=mn(this.condNode).build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${l} ) {\n\n`).addFlowTab();let c=mn(n,r).build(e,s);if(c&&(c=a?u+" = "+c+";":"return "+c+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=mn(o,r).build(e,s);t&&(t=a?u+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,s,t)}}const wd=pi(Ed);Vr("cond",wd),Rr("CondNode",Ed);class Md extends Ar{constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}add(e){return this.nodes.push(e),this}if(e,t){const s=new li(t);return this._currentCond=wd(e,s),this.add(this._currentCond)}elseif(e,t){const s=new li(t),r=wd(e,s);return this._currentCond.elseNode=r,this._currentCond=r,this}else(e){return this._currentCond.elseNode=new li(e),this}build(e,...t){const s=xi();Ti(this);for(const t of this.nodes)t.build(e,"void");return Ti(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}}const Fd=pi(Md);Rr("StackNode",Md);class Bd extends w{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,r=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 M(5,5,5),n=Rc(Ul),o=hd("MeshBasicNodeMaterial");o.colorNode=uu(t,n,0),o.side=F,o.blending=B;const a=new O(i,o),u=new U;u.add(a),t.minFilter===A&&(t.minFilter=L);return new I(1,10,this).update(e,u),t.minFilter=s,t.currentGenerateMipmaps=r,a.geometry.dispose(),a.material.dispose(),this}}const Od=new Ds,Ud=new Map([[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Ld=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Id=e=>(e=Number(e))+(e%1?"":".0");class Pd{constructor(e,t,s,r=null,i=null){this.object=e,this.material=i||e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=r,this.nodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.hashNodes={},this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.toneMappingNode=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.bindingsOffset={vertex:0,fragment:0,compute:0},this.bindingsArray=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=Fd(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={keywords:new En,material:this.material},this.cache=new dn,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getRenderTarget(e,t,s){return new P(e,t,s)}getCubeRenderTarget(e,t){return new Bd(e,t)}includes(e){return this.nodes.includes(e)}_getSharedBindings(e){const t=[];for(const s of e)if(!0===s.shared){const e=s.getNodes();let r=Od.get(e);void 0===r&&(Od.set(e,s),r=s),t.push(r)}else t.push(s);return t}getBindings(){let e=this.bindingsArray;if(null===e){const t=this.bindings;this.bindingsArray=e=this._getSharedBindings(null!==this.material?[...t.vertex,...t.fragment]:t.compute)}return e}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}buildUpdateNodes(){for(const e of this.nodes){const t=e.getUpdateType(),s=e.getUpdateBeforeType();t!==cr.NONE&&this.updateNodes.push(e.getSelf()),s!==cr.NONE&&this.updateBeforeNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}setCache(e){this.cache=e}getCache(){return this.cache}isAvailable(){return!1}getVertexIndex(){}getInstanceIndex(){}getFrontFacing(){}getFragCoord(){}isFlipY(){return!1}generateTexture(){}generateTextureLod(){}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new o:"vec2"===e?t=new a:"vec3"===e?t=new u:"vec4"===e&&(t=new s)),"float"===e)return Id(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${Id(t.r)}, ${Id(t.g)}, ${Id(t.b)} )`;const r=this.getTypeLength(e),i=this.getComponentType(e),n=e=>this.generateConst(i,e);if(2===r)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)} )`;if(3===r)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)} )`;if(4===r)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)}, ${n(t.w)} )`;if(r>4&&t&&(t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(n).join(", ")} )`;if(r>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}generateMethod(e){return e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const s=this.attributes;for(const t of s)if(t.name===e)return t;const r=new vn(e,t);return s.push(r),r}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e}needsColorSpaceToLinear(){return!1}getTextureColorSpaceFromMap(e){let t;return t=e&&e.isTexture?e.colorSpace:e&&e.isWebGLRenderTarget?e.texture.colorSpace:C,t}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?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;const s=Ud.get(e);return("float"===t?"":t[0])+s}getTypeFromArray(e){return Ld.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,r=e.itemSize,i=e.normalized;let n;return e instanceof D||!0===i||(n=this.getTypeFromArray(s)),this.getTypeFromLength(r,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){return this.stack=Fd(this.stack),this.stacks.push(xi()||this.stack),Ti(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Ti(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let r=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getNodeData(e);return void 0===r&&(r={},s.setNodeData(e,r)),void 0===r[t]&&(r[t]={}),r[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let r=s.bufferAttribute;if(void 0===r){const i=this.uniforms.index++;r=new vn("nodeAttribute"+i,t,e),this.bufferAttributes.push(r),s.bufferAttribute=r}return r}getStructTypeFromNode(e,t=this.shaderStage){const s=this.getDataFromNode(e,t);if(void 0===s.structType){const r=this.structs.index++;e.name=`StructType${r}`,this.structs[t].push(e),s.structType=e}return e}getUniformFromNode(e,t,s=this.shaderStage,r=null){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.uniform;if(void 0===n){const o=this.uniforms.index++;n=new Sn(r||"nodeUniform"+o,t,e),this.uniforms[s].push(n),i.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),r=this.shaderStage){const i=this.getDataFromNode(e,r);let n=i.variable;if(void 0===n){const e=this.vars[r]||(this.vars[r]=[]);null===t&&(t="nodeVar"+e.length),n=new An(t,s),e.push(n),i.variable=n}return n}getVaryingFromNode(e,t=null,s=e.getNodeType(this)){const r=this.getDataFromNode(e,"any");let i=r.varying;if(void 0===i){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),i=new Rn(t,s),e.push(i),r.varying=i}return i}getCodeFromNode(e,t,s=this.shaderStage){const r=this.getDataFromNode(e);let i=r.code;if(void 0===i){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;i=new Cn("nodeCode"+n,t),e.push(i),r.code=i}return i}addLineFlowCode(e){return""===e||(e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}buildFunctionNode(e){const t=new to,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout;let s;if(e.isArrayInput){s=[];for(const e of t.inputs)s.push(new Xn(e.type,e.name))}else{s={};for(const e of t.inputs)s[e.name]=new Xn(e.type,e.name)}e.layout=null;const r=e.call(s),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowStagesNode(e,t=null){const s=this.flow,r=this.vars,i=this.buildStage,n={code:""};this.flow=n,this.vars={};for(const s of pr)this.setBuildStage(s),n.result=e.build(this,t);return n.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=r,this.setBuildStage(i),n}getFunctionOperator(){return null}flowChildNode(e,t=null){const s=this.flow,r={code:""};return this.flow=r,r.result=e.build(this,t),this.flow=s,r}flowNodeFromShaderStage(e,t,s=null,r=null){const i=this.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==r&&(n.code+=`${this.tab+r} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(i),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){}getVaryings(){}getVar(e,t){return`${this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){}build(e=!0){const{object:t,material:s}=this;e&&(null!==s?cd.fromMaterial(s).build(this):this.addFlow("compute",t));for(const e of pr){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of gr){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t)return new Nd(e);if("vec2"===t)return new _d(e);if("vec3"===t)return new vd(e);if("vec4"===t)return new Sd(e);if("color"===t)return new Ad(e);if("mat3"===t)return new Rd(e);if("mat4"===t)return new Cd(e);throw new Error(`Uniform "${t}" not declared.`)}createNodeMaterial(e="NodeMaterial"){return hd(e)}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const r=this.getTypeLength(t),i=this.getTypeLength(s);return r>4||i>4||0===i?e:r===i?`${this.getType(s)}( ${e} )`:r>i?this.format(`${e}.${"xyz".slice(0,i)}`,this.getTypeFromLength(i,this.getComponentType(t)),s):4===i&&r>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===r?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===r&&i>1&&t[0]!==s[0]&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${V} - NodeMaterial System\n`}}class Dd{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.startTime=null,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return void 0===s&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.setReference(this);if(t===cr.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(e)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(e,this.frameId)}else if(t===cr.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(e)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(e,this.renderId)}else t===cr.OBJECT&&e.updateBefore(this)}updateNode(e){const t=e.getUpdateType(),s=e.setReference(this);if(t===cr.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(e)!==this.frameId&&!1!==e.update(this)&&t.set(e,this.frameId)}else if(t===cr.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(e)!==this.renderId&&!1!==e.update(this)&&t.set(e,this.renderId)}else t===cr.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 Vd{constructor(e,t,s=null,r="",i=!1){this.type=e,this.name=t,this.count=s,this.qualifier=r,this.isConst=i}}Vd.isNodeFunctionInput=!0;class Gd extends Ar{constructor(e){super(),this.types=e,this.isStructTypeNode=!0}getMemberTypes(){return this.types}}Rr("StructTypeNode",Gd);class kd extends Ar{constructor(...e){super(),this.isOutputStructNode=!0,this.members=e}setup(e){super.setup(e);const t=this.members,s=[];for(let r=0;rUa(No(4,e.mul(bo(1,e))),t),jd=(e,t)=>e.lessThan(.5)?Wd(e.mul(2),t).div(2):bo(1,Wd(No(bo(1,e),2),t).div(2)),qd=(e,t,s)=>Ua(_o(Ua(e,t),yo(Ua(e,t),Ua(bo(1,e),s))),1/t),Xd=(e,t)=>oa($o.mul(t.mul(e).sub(1))).div($o.mul(t.mul(e).sub(1)));Vr("parabola",Wd),Vr("gain",jd),Vr("pcurve",qd),Vr("sinc",Xd);const Yd=fi((([e])=>e.fract().sub(.5).abs())),Kd=fi((([e])=>Mi(Yd(e.z.add(Yd(e.y.mul(1)))),Yd(e.z.add(Yd(e.x.mul(1)))),Yd(e.y.add(Yd(e.x.mul(1))))))),Qd=fi((([e,t,s])=>{const r=Mi(e).toVar(),i=_i(1.4).toVar(),n=_i(0).toVar(),o=Mi(r).toVar();return sc({start:_i(0),end:_i(3),type:"float",condition:"<="},(()=>{const e=Mi(Kd(o.mul(2))).toVar();r.addAssign(e.add(s.mul(_i(.1).mul(t)))),o.mulAssign(1.8),i.mulAssign(1.5),r.mulAssign(1.2);const a=_i(Yd(r.z.add(Yd(r.x.add(Yd(r.y)))))).toVar();n.addAssign(a.div(i)),o.addAssign(.14)})),n}));let Zd;Yd.setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Kd.setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Qd.setLayout({name:"triNoise3D",type:"float",inputs:[{name:"p",type:"vec3"},{name:"spd",type:"float"},{name:"time",type:"float"}]});class Jd extends Ed{constructor(e){Zd=Zd||iu("discard"),super(e,Zd)}}const eh=pi(Jd),th=e=>eh(e).append();Vr("discard",th),Rr("DiscardNode",Jd);class sh extends Ar{constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let s=this._candidateFnCall;if(null===s){let r=null,i=-1;for(const s of this.functionNodes){const n=s.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const o=n.inputs;if(t.length===o.length){let n=0;for(let s=0;si&&(r=s,i=n)}}this._candidateFnCall=s=r(...t)}return s}}const rh=pi(sh),ih=e=>(...t)=>rh(e,...t);Rr("FunctionOverloadingNode",sh);class nh extends Er{constructor(){super("vec2")}setup(){const e=Mi(Il.z,0,Il.x.negate()).normalize(),t=Il.cross(e);return Ri(e.dot(Ju),t.dot(Ju)).mul(.495).add(.5)}}const oh=gi(nh);Rr("MatcapUVNode",nh);class ah extends ho{constructor(e=ah.LOCAL,t=1,s=0){super(s),this.scope=e,this.scale=t,this.updateType=cr.FRAME}update(e){const t=this.scope,s=this.scale;t===ah.LOCAL?this.value+=e.deltaTime*s:t===ah.DELTA?this.value=e.deltaTime*s:t===ah.FRAME?this.value=e.frameId:this.value=e.time*s}serialize(e){super.serialize(e),e.scope=this.scope,e.scale=this.scale}deserialize(e){super.deserialize(e),this.scope=e.scope,this.scale=e.scale}}ah.LOCAL="local",ah.GLOBAL="global",ah.DELTA="delta",ah.FRAME="frame";const uh=(e,t=0)=>ci(new ah(ah.LOCAL,e,t)),lh=(e,t=0)=>ci(new ah(ah.GLOBAL,e,t)),ch=(e,t=0)=>ci(new ah(ah.DELTA,e,t)),dh=gi(ah,ah.FRAME).uint();Rr("TimerNode",ah);class hh extends Ar{constructor(e=hh.SINE,t=uh()){super(),this.method=e,this.timeNode=t}getNodeType(e){return this.timeNode.getNodeType(e)}setup(){const e=this.method,t=ci(this.timeNode);let s=null;return e===hh.SINE?s=t.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5):e===hh.SQUARE?s=t.fract().round():e===hh.TRIANGLE?s=t.add(.5).fract().mul(2).sub(1).abs():e===hh.SAWTOOTH&&(s=t.fract()),s}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}hh.SINE="sine",hh.SQUARE="square",hh.TRIANGLE="triangle",hh.SAWTOOTH="sawtooth";const ph=pi(hh,hh.SINE),gh=pi(hh,hh.SQUARE),mh=pi(hh,hh.TRIANGLE),fh=pi(hh,hh.SAWTOOTH);Rr("OscNode",hh);class Th extends Er{constructor(e,t){super(),this.scope=e,this.node=t}getNodeType(e){return this.node.getNodeType(e)}setup(){const{scope:e,node:t}=this;let s=null;return e===Th.DIRECTION_TO_COLOR?s=t.mul(.5).add(.5):e===Th.COLOR_TO_DIRECTION&&(s=t.mul(2).sub(1)),s}}Th.DIRECTION_TO_COLOR="directionToColor",Th.COLOR_TO_DIRECTION="colorToDirection";const xh=pi(Th,Th.DIRECTION_TO_COLOR),yh=pi(Th,Th.COLOR_TO_DIRECTION);Vr("directionToColor",xh),Vr("colorToDirection",yh),Rr("PackingNode",Th);class bh extends Ar{constructor(e,t,s,r=_i(0),i=_i(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=r,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:r,outHighNode:i,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(i.sub(r)).add(r)}}const Nh=pi(bh,null,null,{doClamp:!1}),_h=pi(bh);Vr("remap",Nh),Vr("remapClamp",_h),Rr("RemapNode",bh);class vh extends Er{constructor(e,t,s=Ri(.5)){super("vec2"),this.uvNode=e,this.rotationNode=t,this.centerNode=s}setup(){const{uvNode:e,rotationNode:t,centerNode:s}=this;return e.sub(s).rotate(t).add(s)}}const Sh=pi(vh);Vr("rotateUV",Sh),Rr("RotateUVNode",vh);class Ah extends Er{constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),r=t.sin();return Di(e,r,r.negate(),e).mul(s)}{const e=t,r=ji(Ui(1,0,0,0),Ui(0,aa(e.x),oa(e.x).negate(),0),Ui(0,oa(e.x),aa(e.x),0),Ui(0,0,0,1)),i=ji(Ui(aa(e.y),0,oa(e.y),0),Ui(0,1,0,0),Ui(oa(e.y).negate(),0,aa(e.y),0),Ui(0,0,0,1)),n=ji(Ui(aa(e.z),oa(e.z).negate(),0,0),Ui(oa(e.z),aa(e.z),0,0),Ui(0,0,1,0),Ui(0,0,0,1));return r.mul(i).mul(n).mul(Ui(s,1)).xyz}}}const Rh=pi(Ah);Vr("rotate",Rh),Rr("RotateNode",Ah);class Ch extends Ar{constructor(e,t=mo(),s=_i(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:r,height:i}=s,n=e.mod(r.mul(i)).floor(),o=n.mod(r),a=i.sub(n.add(1).div(r).ceil()),u=s.reciprocal(),l=Ri(o,a);return t.add(l).mul(u)}}const Eh=pi(Ch);Rr("SpriteSheetUVNode",Ch);class wh extends wr{constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}setup(e){return!1===e.isAvailable("storageBuffer")&&(this.node.instanceIndex||!0!==this.node.bufferObject||e.setupPBO(this.node)),super.setup(e)}generate(e,t){let s;const r=e.context.assign;if(!1===e.isAvailable("storageBuffer")){const{node:t}=this;s=t.instanceIndex||!0!==this.node.bufferObject||!0===r?t.build(e):e.generatePBO(this)}else s=super.generate(e);if(!0!==r){const r=this.getNodeType(e);s=e.format(s,r,t)}return s}}const Mh=pi(wh);Vr("storageElement",Mh),Rr("StorageArrayElementNode",wh);class Fh extends Ar{constructor(e,t=null,s=null,r=_i(1),i=Bl,n=Ku){super("vec4"),this.textureXNode=e,this.textureYNode=t,this.textureZNode=s,this.scaleNode=r,this.positionNode=i,this.normalNode=n}setup(){const{textureXNode:e,textureYNode:t,textureZNode:s,scaleNode:r,positionNode:i,normalNode:n}=this;let o=n.abs().normalize();o=o.div(o.dot(Mi(1)));const a=i.yz.mul(r),u=i.zx.mul(r),l=i.xy.mul(r),c=e.value,d=null!==t?t.value:c,h=null!==s?s.value:c,p=uu(c,a).mul(o.x),g=uu(d,u).mul(o.y),m=uu(h,l).mul(o.z);return yo(p,g,m)}}const Bh=pi(Fh),Oh=(...e)=>Bh(...e);Vr("triplanarTexture",Oh),Rr("TriplanarTexturesNode",Fh);const Uh=new e,Lh=new u,Ih=new u,Ph=new u,Dh=new l,Vh=new u(0,0,-1),Gh=new s,kh=new u,zh=new u,$h=new s,Hh=new a,Wh=new P,jh=Ri(Vc.x.oneMinus(),Vc.y);let qh=!1;class Xh extends au{constructor(e={}){super(Wh.texture,jh);const{target:t=new G,resolution:s=1,generateMipmaps:r=!1,bounces:i=!0}=e;this.target=t,this.resolution=s,this.generateMipmaps=r,this.bounces=i,this.updateBeforeType=i?cr.RENDER:cr.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new WeakMap}_updateResolution(e,t){const s=this.resolution;t.getDrawingBufferSize(Hh),e.setSize(Math.round(Hh.width*s),Math.round(Hh.height*s))}setup(e){return this._updateResolution(Wh,e.renderer),super.setup(e)}getTextureNode(){return this.textureNode}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 P(0,0,{type:k}),!0===this.generateMipmaps&&(t.texture.minFilter=z,t.texture.generateMipmaps=!0),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&qh)return!1;qh=!0;const{scene:t,camera:s,renderer:r,material:i}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);if(r.getDrawingBufferSize(Hh),this._updateResolution(a,r),Ih.setFromMatrixPosition(n.matrixWorld),Ph.setFromMatrixPosition(s.matrixWorld),Dh.extractRotation(n.matrixWorld),Lh.set(0,0,1),Lh.applyMatrix4(Dh),kh.subVectors(Ih,Ph),kh.dot(Lh)>0)return;kh.reflect(Lh).negate(),kh.add(Ih),Dh.extractRotation(s.matrixWorld),Vh.set(0,0,-1),Vh.applyMatrix4(Dh),Vh.add(Ph),zh.subVectors(Ih,Vh),zh.reflect(Lh).negate(),zh.add(Ih),o.coordinateSystem=s.coordinateSystem,o.position.copy(kh),o.up.set(0,1,0),o.up.applyMatrix4(Dh),o.up.reflect(Lh),o.lookAt(zh),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),Uh.setFromNormalAndCoplanarPoint(Lh,Ih),Uh.applyMatrix4(o.matrixWorldInverse),Gh.set(Uh.normal.x,Uh.normal.y,Uh.normal.z,Uh.constant);const u=o.projectionMatrix;$h.x=(Math.sign(Gh.x)+u.elements[8])/u.elements[0],$h.y=(Math.sign(Gh.y)+u.elements[9])/u.elements[5],$h.z=-1,$h.w=(1+u.elements[10])/u.elements[14],Gh.multiplyScalar(1/Gh.dot($h));u.elements[2]=Gh.x,u.elements[6]=Gh.y,u.elements[10]=Gh.z-0,u.elements[14]=Gh.w,this.value=a.texture,i.visible=!1;const l=r.getRenderTarget();r.setRenderTarget(a),r.render(t,o),r.setRenderTarget(l),i.visible=!0,qh=!1}}const Yh=e=>ci(new Xh(e));class Kh extends Ar{constructor(e=Kh.LOCAL){super("vec3"),this.scope=e}getHash(){return`bitangent-${this.scope}`}generate(e){const t=this.scope;let s;t===Kh.GEOMETRY?s=Yu.cross(ql):t===Kh.LOCAL?s=Ku.cross(Xl):t===Kh.VIEW?s=Qu.cross(Yl):t===Kh.WORLD&&(s=Zu.cross(Kl));const r=s.mul(ql.w).xyz;return ia(nn(r)).build(e,this.getNodeType(e))}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Kh.GEOMETRY="geometry",Kh.LOCAL="local",Kh.VIEW="view",Kh.WORLD="world";const Qh=gi(Kh,Kh.GEOMETRY),Zh=gi(Kh,Kh.LOCAL),Jh=gi(Kh,Kh.VIEW),ep=gi(Kh,Kh.WORLD),tp=ia(Ju.cross(Ql).mul(ql.w)),sp=ia(tp.transformDirection(Iu));Rr("BitangentNode",Kh);const rp=zi(Yl,Jh,Qu),ip=Il.mul(rp),np=(e,t)=>e.sub(ip.mul(t));class op extends on{constructor(e=0){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 ap=(...e)=>ci(new op(...e));Rr("VertexColorNode",op);const up=1/6,lp=e=>No(up,No(e,No(e,e.negate().add(3)).sub(3)).add(1)),cp=e=>No(up,No(e,No(e,No(3,e).sub(6))).add(4)),dp=e=>No(up,No(e,No(e,No(-3,e).add(3)).add(3)).add(1)),hp=e=>No(up,Ua(e,3)),pp=e=>lp(e).add(cp(e)),gp=e=>dp(e).add(hp(e)),mp=e=>yo(-1,cp(e).div(lp(e).add(cp(e)))),fp=e=>yo(1,hp(e).div(dp(e).add(hp(e)))),Tp=(e,t,s)=>{const r=e.uvNode,i=No(r,t.zw).add(.5),n=sa(i),o=na(i),a=pp(o.x),u=gp(o.x),l=mp(o.x),c=fp(o.x),d=mp(o.y),h=fp(o.y),p=Ri(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),g=Ri(n.x.add(c),n.y.add(d)).sub(.5).mul(t.xy),m=Ri(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Ri(n.x.add(c),n.y.add(h)).sub(.5).mul(t.xy),T=pp(o.y).mul(yo(a.mul(e.uv(p).level(s)),u.mul(e.uv(g).level(s)))),x=gp(o.y).mul(yo(a.mul(e.uv(m).level(s)),u.mul(e.uv(f).level(s))));return T.add(x)};class xp extends Er{constructor(e,t=_i(3)){super("vec4"),this.textureNode=e,this.blurNode=t}setup(){return((e,t)=>{const s=Ri(e.size(vi(t))),r=Ri(e.size(vi(t.add(1)))),i=_o(1,s),n=_o(1,r),o=Tp(e,Ui(i,s),sa(t)),a=Tp(e,Ui(n,r),ra(t));return na(t).mix(o,a)})(this.textureNode,this.blurNode)}}const yp=pi(xp);Vr("bicubic",yp),Rr("TextureBicubicNode",xp);class bp extends Ar{constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const Np=gi(bp);Rr("PointUVNode",bp);class _p extends Ar{constructor(e=_p.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let r;return t===_p.BACKGROUND_BLURRINESS?r=xu("backgroundBlurriness","float",s):t===_p.BACKGROUND_INTENSITY&&(r=xu("backgroundIntensity","float",s)),r}}_p.BACKGROUND_BLURRINESS="backgroundBlurriness",_p.BACKGROUND_INTENSITY="backgroundIntensity";const vp=gi(_p,_p.BACKGROUND_BLURRINESS),Sp=gi(_p,_p.BACKGROUND_INTENSITY);Rr("SceneNode",_p);class Ap extends du{constructor(e,t,s=0){super(e,t,s),this.isStorageBufferNode=!0,this.bufferObject=!1,this._attribute=null,this._varying=null}getInputType(){return"storageBuffer"}element(e){return Mh(this,e)}setBufferObject(e){return this.bufferObject=e,this}generate(e){if(e.isAvailable("storageBuffer"))return super.generate(e);const t=this.getNodeType(e);null===this._attribute&&(this._attribute=Gl(this.value),this._varying=nn(this._attribute));const s=this._varying.build(e,t);return e.registerTransform(s,this._attribute),s}}const Rp=(e,t,s)=>ci(new Ap(e,t,s)),Cp=(e,t,s)=>ci(new Ap(e,t,s).setBufferObject(!0));Rr("StorageBufferNode",Ap);class Ep extends au{constructor(e,t,s=null){super(e,t),this.storeNode=s,this.isStoreTextureNode=!0}getInputType(){return"storageTexture"}setup(e){super.setup(e);e.getNodeProperties(this).storeNode=this.storeNode}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:r}=t,i=super.generate(e,"property"),n=s.build(e,"uvec2"),o=r.build(e,"vec4"),a=e.generateTextureStore(e,i,n,o);e.addLineFlowCode(a)}}const wp=pi(Ep),Mp=(e,t,s)=>{const r=wp(e,t,s);return null!==s&&r.append(),r};Rr("TextureStoreNode",Ep);class Fp extends Tu{constructor(e,t,s=null){super(e,t,s),this.userData=s}update(e){this.reference=null!==this.userData?this.userData:e.object.userData,super.update(e)}}const Bp=(e,t,s)=>ci(new Fp(e,t,s));Rr("UserDataNode",Fp);const Op=fi((({base:e,blend:t})=>{const s=s=>t[s].lessThan(ko).cond(t[s],e[s].oneMinus().div(t[s]).oneMinus().max(0));return Mi(s("x"),s("y"),s("z"))})).setLayout({name:"burnColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Up=fi((({base:e,blend:t})=>{const s=s=>t[s].equal(1).cond(t[s],e[s].div(t[s].oneMinus()).max(0));return Mi(s("x"),s("y"),s("z"))})).setLayout({name:"dodgeColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Lp=fi((({base:e,blend:t})=>{const s=s=>e[s].oneMinus().mul(t[s].oneMinus()).oneMinus();return Mi(s("x"),s("y"),s("z"))})).setLayout({name:"screenColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Ip=fi((({base:e,blend:t})=>{const s=s=>e[s].lessThan(.5).cond(e[s].mul(t[s],2),e[s].oneMinus().mul(t[s].oneMinus()).oneMinus());return Mi(s("x"),s("y"),s("z"))})).setLayout({name:"overlayColor",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]});class Pp extends Er{constructor(e,t,s){super(),this.blendMode=e,this.baseNode=t,this.blendNode=s}setup(){const{blendMode:e,baseNode:t,blendNode:s}=this,r={base:t,blend:s};let i=null;return e===Pp.BURN?i=Op(r):e===Pp.DODGE?i=Up(r):e===Pp.SCREEN?i=Lp(r):e===Pp.OVERLAY&&(i=Ip(r)),i}}Pp.BURN="burn",Pp.DODGE="dodge",Pp.SCREEN="screen",Pp.OVERLAY="overlay";const Dp=pi(Pp,Pp.BURN),Vp=pi(Pp,Pp.DODGE),Gp=pi(Pp,Pp.OVERLAY),kp=pi(Pp,Pp.SCREEN);Vr("burn",Dp),Vr("dodge",Vp),Vr("overlay",Gp),Vr("screen",kp),Rr("BlendModeNode",Pp);const zp=fi((({textureNode:e,bumpScale:t})=>{let s=e;if(!0!==s.isTextureNode&&s.traverse((e=>{!0===e.isTextureNode&&(s=e)})),!0!==s.isTextureNode)throw new Error("THREE.TSL: dHdxy_fwd() requires a TextureNode.");const r=_i(e),i=s.uvNode||mo(),n=t=>e.cache().context({getUV:()=>t,forceUVContext:!0});return Ri(_i(n(i.add(i.dFdx()))).sub(r),_i(n(i.add(i.dFdy()))).sub(r)).mul(t)})),$p=fi((e=>{const{surf_pos:t,surf_norm:s,dHdxy:r}=e,i=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(i),u=i.dot(o).mul(ud),l=u.sign().mul(r.x.mul(o).add(r.y.mul(a)));return u.abs().mul(s).sub(l).normalize()}));class Hp extends Er{constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=zp({textureNode:this.textureNode,bumpScale:e});return $p({surf_pos:Ll,surf_norm:Qu,dHdxy:t})}}const Wp=pi(Hp);Vr("bumpMap",Wp),Rr("BumpMapNode",Hp);const jp=fi((({color:e,adjustment:t})=>t.mix(eg(e.rgb),e.rgb))),qp=fi((({color:e,adjustment:t})=>{const s=yo(e.r,e.g,e.b).div(3),r=e.r.max(e.g.max(e.b)),i=r.sub(s).mul(t).mul(-3);return ka(e.rgb,r,i)})),Xp=fi((({color:e,adjustment:t})=>{const s=Mi(.57735,.57735,.57735),r=t.cos();return Mi(e.rgb.mul(r).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(Ba(s,e.rgb).mul(r.oneMinus())))))}));class Yp extends Er{constructor(e,t,s=_i(1)){super("vec3"),this.method=e,this.colorNode=t,this.adjustmentNode=s}setup(){const{method:e,colorNode:t,adjustmentNode:s}=this,r={color:t,adjustment:s};let i=null;return e===Yp.SATURATION?i=jp(r):e===Yp.VIBRANCE?i=qp(r):e===Yp.HUE&&(i=Xp(r)),i}}Yp.SATURATION="saturation",Yp.VIBRANCE="vibrance",Yp.HUE="hue";const Kp=pi(Yp,Yp.SATURATION),Qp=pi(Yp,Yp.VIBRANCE),Zp=pi(Yp,Yp.HUE),Jp=Mi(.2125,.7154,.0721),eg=(e,t=Jp)=>Ba(e,t),tg=(e,t)=>ka(Mi(0),e,eg(e).sub(t).max(0));Vr("saturation",Kp),Vr("vibrance",Qp),Vr("hue",Zp),Vr("threshold",tg),Rr("ColorAdjustmentNode",Yp);const sg=fi((e=>{const{eye_pos:t,surf_norm:s,mapN:r,uv:i}=e,n=t.dFdx(),o=t.dFdy(),a=i.dFdx(),u=i.dFdy(),l=s,c=o.cross(l),d=l.cross(n),h=c.mul(a.x).add(d.mul(u.x)),p=c.mul(a.y).add(d.mul(u.y)),g=h.dot(h).max(p.dot(p)),m=ud.mul(g.inverseSqrt());return yo(h.mul(r.x,m),p.mul(r.y,m),l.mul(r.z)).normalize()}));class rg extends Er{constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=$}setup(e){const{normalMapType:t,scaleNode:s}=this;let r=this.node.mul(2).sub(1);null!==s&&(r=Mi(r.xy.mul(s),r.z));let i=null;if(t===H)i=$u.mul(r).normalize();else if(t===$){i=!0===e.hasGeometryAttribute("tangent")?rp.mul(r).normalize():sg({eye_pos:Ll,surf_norm:Qu,mapN:r,uv:mo()})}return i}}const ig=pi(rg);Vr("normalMap",ig),Rr("NormalMapNode",rg);class ng extends Er{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 og=pi(ng);Vr("posterize",og),Rr("PosterizeNode",ng);const ag=fi((({color:e,exposure:t})=>e.mul(t).clamp())),ug=fi((({color:e,exposure:t})=>(e=e.mul(t)).div(e.add(1)).clamp())),lg=fi((({color:e,exposure:t})=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(r).pow(2.2)})),cg=fi((({color:e})=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)})),dg=fi((({color:e,exposure:t})=>{const s=zi(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=zi(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=cg({color:e}),(e=r.mul(e)).clamp()})),hg=zi(Mi(1.6605,-.1246,-.0182),Mi(-.5876,1.1329,-.1006),Mi(-.0728,-.0083,1.1187)),pg=zi(Mi(.6274,.0691,.0164),Mi(.3293,.9195,.088),Mi(.0433,.0113,.8956)),gg=fi((([e])=>{const t=Mi(e).toVar(),s=Mi(t.mul(t)).toVar(),r=Mi(s.mul(s)).toVar();return _i(15.5).mul(r.mul(s)).sub(No(40.14,r.mul(t))).add(No(31.96,r).sub(No(6.868,s.mul(t))).add(No(.4298,s).add(No(.1191,t).sub(.00232))))})),mg=fi((({color:e,exposure:t})=>{const s=Mi(e).toVar(),r=zi(Mi(.856627153315983,.137318972929847,.11189821299995),Mi(.0951212405381588,.761241990602591,.0767994186031903),Mi(.0482516061458583,.101439036467562,.811302368396859)),i=zi(Mi(1.1271005818144368,-.1413297634984383,-.14132976349843826),Mi(-.11060664309660323,1.157823702216272,-.11060664309660294),Mi(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=_i(-12.47393),o=_i(4.026069);return s.mulAssign(t),s.assign(pg.mul(s)),s.assign(r.mul(s)),s.assign(Ra(s,1e-10)),s.assign(Jo(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(za(s,0,1)),s.assign(gg(s)),s.assign(i.mul(s)),s.assign(Ua(Ra(Mi(0),s),Mi(2.2))),s.assign(hg.mul(s)),s.assign(za(s,0,1)),s})),fg={[j]:ag,[q]:ug,[X]:lg,[Y]:dg,[K]:mg};class Tg extends Er{constructor(e=W,t=_i(1),s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}getCacheKey(){let e=super.getCacheKey();return e="{toneMapping:"+this.toneMapping+",nodes:"+e+"}",e}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(s===W)return t;const r={exposure:this.exposureNode,color:t},i=fg[s];let n=null;return n=i?i(r):t,n}}const xg=(e,t,s)=>ci(new Tg(e,ci(t),ci(s)));Rr("ToneMappingNode",Tg);let yg=null;class bg extends Hc{constructor(e=Vc,t=null){null===yg&&(yg=new S),super(e,t,yg)}}const Ng=pi(bg);Vr("viewportSharedTexture",Ng),Rr("ViewportSharedTextureNode",bg);class _g extends au{constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class vg extends Er{constructor(e,t,s){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this._pixelRatio=1,this._width=1,this._height=1;const r=new N;r.isRenderTargetTexture=!0,r.name="PostProcessingDepth";const i=new P(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:k});i.texture.name="PostProcessing",i.depthTexture=r,this.renderTarget=i,this.updateBeforeType=cr.FRAME,this._textureNode=ci(new _g(this,i.texture)),this._depthTextureNode=ci(new _g(this,r)),this._depthNode=null,this._cameraNear=po(0),this._cameraFar=po(0),this.isPassNode=!0}isGlobal(){return!0}getTextureNode(){return this._textureNode}getTextureDepthNode(){return this._depthTextureNode}getDepthNode(){if(null===this._depthNode){const e=this._cameraNear,t=this._cameraFar;this._depthNode=Qc(ed(this._depthTextureNode,e,t),e,t)}return this._depthNode}setup(){return this.scope===vg.COLOR?this.getTextureNode():this.getDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s,camera:r}=this;this._pixelRatio=t.getPixelRatio();const i=t.getSize(new a);this.setSize(i.width,i.height);const n=t.toneMapping,o=t.toneMappingNode,u=t.getRenderTarget();this._cameraNear.value=r.near,this._cameraFar.value=r.far,t.toneMapping=W,t.toneMappingNode=null,t.setRenderTarget(this.renderTarget),t.render(s,r),t.toneMapping=n,t.toneMappingNode=o,t.setRenderTarget(u)}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,r=this._height*this._pixelRatio;this.renderTarget.setSize(s,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}vg.COLOR="color",vg.DEPTH="depth";const Sg=(e,t)=>ci(new vg(vg.COLOR,e,t)),Ag=(e,t)=>ci(new _g(e,t)),Rg=(e,t)=>ci(new vg(vg.DEPTH,e,t));Rr("PassNode",vg);const Cg=new Q(-1,1,1,-1,0,1);const Eg=new class extends Z{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new J([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new J(t,2))}};class wg{constructor(e=null){this._mesh=new O(Eg,e)}dispose(){this._mesh.geometry.dispose()}async renderAsync(e){await e.renderAsync(this._mesh,Cg)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}get render(){return this.renderAsync}}const Mg=new wg,Fg=new wg;class Bg extends Er{constructor(e,t=2){super("vec4"),this.textureNode=e,this.sigma=t,this.directionNode=Ri(1),this._invSize=po(new a),this._passDirection=po(new a),this._horizontalRT=new P,this._horizontalRT.texture.name="GaussianBlurNode.horizontal",this._verticalRT=new P,this._verticalRT.texture.name="GaussianBlurNode.vertical",this._textureNode=Ag(this,this._verticalRT.texture),this.updateBeforeType=cr.RENDER,this.resolution=new a(1,1)}setSize(e,t){e=Math.max(Math.round(e*this.resolution.x),1),t=Math.max(Math.round(t*this.resolution.y),1),this._invSize.value.set(1/e,1/t),this._horizontalRT.setSize(e,t),this._verticalRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,s=this.textureNode,r=s.value,i=t.getRenderTarget(),n=s.value;Mg.material=this._material,Fg.material=this._material,this.setSize(r.image.width,r.image.height);const o=r.type;this._horizontalRT.texture.type=o,this._verticalRT.texture.type=o,t.setRenderTarget(this._horizontalRT),this._passDirection.value.set(1,0),Mg.render(t),s.value=this._horizontalRT.texture,t.setRenderTarget(this._verticalRT),this._passDirection.value.set(0,1),Fg.render(t),t.setRenderTarget(i),s.value=n}getTextureNode(){return this._textureNode}setup(e){const t=this.textureNode;if(!0!==t.isTextureNode)return Ui();const s=t.uvNode||mo(),r=e=>t.cache().context({getUV:()=>e,forceUVContext:!0}),i=fi((()=>{const e=3+2*this.sigma,t=this._getCoefficients(e),i=this._invSize,n=Ri(this.directionNode).mul(this._passDirection),o=_i(t[0]).toVar(),a=Ui(r(s).mul(o)).toVar();for(let u=1;uci(new Bg(ci(e),t));Vr("gaussianBlur",Og);const Ug=new wg;class Lg extends Er{constructor(e,t=.96){super(e),this.textureNode=e,this.textureNodeOld=uu(),this.damp=po(t),this._compRT=new P,this._compRT.texture.name="AfterImageNode.comp",this._oldRT=new P,this._oldRT.texture.name="AfterImageNode.old",this._textureNode=Ag(this,this._compRT.texture),this.updateBeforeType=cr.RENDER}getTextureNode(){return this._textureNode}setSize(e,t){this._compRT.setSize(e,t),this._oldRT.setSize(e,t)}updateBefore(e){const{renderer:t}=e,s=this.textureNode,r=s.value,i=r.type;this._compRT.texture.type=i,this._oldRT.texture.type=i;const n=t.getRenderTarget(),o=s.value;this.textureNodeOld.value=this._oldRT.texture,t.setRenderTarget(this._compRT),Ug.render(t);const a=this._oldRT;this._oldRT=this._compRT,this._compRT=a,this.setSize(r.image.width,r.image.height),t.setRenderTarget(n),s.value=o}setup(e){const t=this.textureNode,s=this.textureNodeOld;if(!0!==t.isTextureNode)return Ui();const r=t.uvNode||mo();s.uvNode=r;const i=fi((([e,t])=>{const s=_i(t).toVar(),r=Ui(e).toVar();return Ra(pa(r.sub(s)),0)})),n=fi((()=>{const e=Ui(s),n=Ui((e=>t.cache().context({getUV:()=>e,forceUVContext:!0}))(r));return e.mulAssign(this.damp.mul(i(e,.1))),Ra(n,e)})),o=this._materialComposed||(this._materialComposed=e.createNodeMaterial());o.fragmentNode=n(),Ug.material=o;return e.getNodeProperties(this).textureNode=t,this._textureNode}}const Ig=(e,t)=>ci(new Lg(ci(e),t));Vr("afterImage",Ig);const Pg=new wg;class Dg extends Er{constructor(e,t,s,r){super("vec4"),this.textureNode=e,this.tresholdNode=t,this.scaleNode=s,this.colorNode=Mi(.1,0,1),this.samples=r,this.resolution=new a(1,1),this._renderTarget=new P,this._renderTarget.texture.name="anamorphic",this._invSize=po(new a),this._textureNode=Ag(this,this._renderTarget.texture),this.updateBeforeType=cr.RENDER}getTextureNode(){return this._textureNode}setSize(e,t){this._invSize.value.set(1/e,1/t),e=Math.max(Math.round(e*this.resolution.x),1),t=Math.max(Math.round(t*this.resolution.y),1),this._renderTarget.setSize(e,t)}updateBefore(e){const{renderer:t}=e,s=this.textureNode,r=s.value;this._renderTarget.texture.type=r.type;const i=t.getRenderTarget(),n=s.value;Pg.material=this._material,this.setSize(r.image.width,r.image.height),t.setRenderTarget(this._renderTarget),Pg.render(t),t.setRenderTarget(i),s.value=n}setup(e){const t=this.textureNode;if(!0!==t.isTextureNode)return Ui();const s=t.uvNode||mo(),r=fi((()=>{const e=this.samples,r=Math.floor(e/2),i=Mi(0).toVar();return sc({start:-r,end:r},(({i:e})=>{const n=_i(e).abs().div(r).oneMinus(),o=(e=>t.cache().context({getUV:()=>e,forceUVContext:!0}))(Ri(s.x.add(this._invSize.x.mul(e).mul(this.scaleNode)),s.y)),a=tg(o,this.tresholdNode).mul(n);i.addAssign(a)})),i.mul(this.colorNode)}));(this._material||(this._material=e.createNodeMaterial())).fragmentNode=r();return e.getNodeProperties(this).textureNode=t,this._textureNode}}const Vg=(e,t=.9,s=3,r=32)=>ci(new Dg(ci(e),ci(t),ci(s),r));Vr("anamorphic",Vg);class Gg extends Er{constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],s=this.functionNode,r=s.getInputs(e),i=this.parameters;if(Array.isArray(i))for(let s=0;s(t=t.length>1||t[0]&&!0===t[0].isNode?hi(t):di(t[0]),ci(new Gg(ci(e),t)));Vr("call",kg),Rr("FunctionCallNode",Gg);class zg extends Ar{constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outpuType=null,this.events=new c,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:_i()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=br(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?Nr(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 $g=pi(zg);Vr("scriptableValue",$g),Rr("ScriptableValueNode",zg);class Hg extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const r=t(...s);return this.set(e,r),r}}}class Wg{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 jg=new Hg;class qg extends Ar{constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new Hg,this._output=$g(),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 s=this._outputs;return void 0===s[e]?s[e]=$g(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=$g(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[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 s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...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 Wg(this),t=jg.get("THREE"),s=jg.get("TSL"),r=this.getMethod(this.codeNode),i=[e,this._local,jg,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=r(...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:_i()}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+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),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()}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 Xg=pi(qg);Vr("scriptable",Xg),Rr("ScriptableNode",qg);class Yg extends Ar{constructor(e,t){super("float"),this.isFogNode=!0,this.colorNode=e,this.factorNode=t}mixAssign(e){return ka(e,this.colorNode,this)}setup(){return this.factorNode}}const Kg=pi(Yg);Vr("fog",Kg),Rr("FogNode",Yg);class Qg extends Yg{constructor(e,t,s){super(e),this.isFogRangeNode=!0,this.nearNode=t,this.farNode=s}setup(){return Wa(this.nearNode,this.farNode,Ll.z.negate())}}const Zg=pi(Qg);Vr("rangeFog",Zg),Rr("FogRangeNode",Qg);class Jg extends Yg{constructor(e,t){super(e),this.isFogExp2Node=!0,this.densityNode=t}setup(){const e=Ll.z.negate(),t=this.densityNode;return t.mul(t,e,e).negate().exp().oneMinus()}}const em=pi(Jg);Vr("densityFog",em),Rr("FogExp2Node",Jg);let tm=null,sm=null;class rm extends Ar{constructor(e=_i(),t=_i()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(xr(this.minNode.value)),s=e.getTypeLength(xr(this.maxNode.value));return t>s?t:s}getNodeType(e){return!0===e.object.isInstancedMesh?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let r=null;if(!0===t.isInstancedMesh){const i=this.minNode.value,n=this.maxNode.value,o=e.getTypeLength(xr(i)),a=e.getTypeLength(xr(n));tm=tm||new s,sm=sm||new s,tm.setScalar(0),sm.setScalar(0),1===o?tm.setScalar(i):i.isColor?tm.set(i.r,i.g,i.b):tm.set(i.x,i.y,i.z||0,i.w||0),1===a?sm.setScalar(n):n.isColor?sm.set(n.r,n.g,n.b):sm.set(n.x,n.y,n.z||0,n.w||0);const u=4,l=u*t.count,c=new Float32Array(l);for(let e=0;eci(new nm(ci(e),t,s));Vr("compute",om),Rr("ComputeNode",nm);class am extends Ar{constructor(e=am.TARGET_DIRECTION,t=null){super(),this.scope=e,this.light=t}setup(){const{scope:e,light:t}=this;let s=null;return e===am.TARGET_DIRECTION&&(s=Iu.transformDirection(Cu(t).sub(Cu(t.target)))),s}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}am.TARGET_DIRECTION="targetDirection";const um=pi(am,am.TARGET_DIRECTION);Rr("LightNode",am);const lm=fi((e=>{const{lightDistance:t,cutoffDistance:s,decayExponent:r}=e,i=t.pow(r).max(.01).reciprocal();return s.greaterThan(0).cond(i.mul(t.div(s).pow4().oneMinus().clamp().pow2()),i)}));class cm extends fc{constructor(e=null){super(e),this.cutoffDistanceNode=po(0),this.decayExponentNode=po(0)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setup(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:r,light:i}=this,n=e.context.lightingModel,o=wu(i).sub(Ll),a=o.normalize(),u=o.length(),l=lm({lightDistance:u,cutoffDistance:s,decayExponent:r}),c=t.mul(l),d=e.context.reflectedLight;n.direct({lightDirection:a,lightColor:c,reflectedLight:d},e.stack,e)}}Rr("PointLightNode",cm),Nc(ee,cm);class dm extends fc{constructor(e=null){super(e)}setup(e){super.setup(e);const t=e.context.lightingModel,s=this.colorNode,r=um(this.light),i=e.context.reflectedLight;t.direct({lightDirection:r,lightColor:s,reflectedLight:i},e.stack,e)}}Rr("DirectionalLightNode",dm),Nc(te,dm);class hm extends fc{constructor(e=null){super(e),this.coneCosNode=po(0),this.penumbraCosNode=po(0),this.cutoffDistanceNode=po(0),this.decayExponentNode=po(0)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e){const{coneCosNode:t,penumbraCosNode:s}=this;return Wa(t,s,e)}setup(e){super.setup(e);const t=e.context.lightingModel,{colorNode:s,cutoffDistanceNode:r,decayExponentNode:i,light:n}=this,o=wu(n).sub(Ll),a=o.normalize(),u=a.dot(um(n)),l=this.getSpotAttenuation(u),c=o.length(),d=lm({lightDistance:c,cutoffDistance:r,decayExponent:i}),h=s.mul(l).mul(d),p=e.context.reflectedLight;t.direct({lightDirection:a,lightColor:h,reflectedLight:p},e.stack,e)}}Rr("SpotLightNode",hm),Nc(se,hm);class pm extends hm{getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const r=e.acos().mul(1/Math.PI);s=uu(t,Ri(r,0),0).r}else s=super.getSpotAttenuation(e);return s}}Rr("IESSpotLightNode",pm),Nc(class extends se{constructor(e,t,s,r,i,n){super(e,t,s,r,i,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}},pm);class gm extends fc{constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}Rr("AmbientLightNode",gm),Nc(re,gm);class mm extends fc{constructor(e=null){super(e),this.lightPositionNode=Cu(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=po(new o)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:r}=this,i=Qu.dot(r).mul(.5).add(.5),n=ka(s,t,i);e.context.irradiance.addAssign(n)}}Rr("HemisphereLightNode",mm),Nc(ie,mm);const fm=fi((e=>{const t=e.uv.mul(2),s=t.x.floor(),r=t.y.floor();return s.add(r).mod(2).sign()}));class Tm extends Er{constructor(e=mo()){super("float"),this.uvNode=e}setup(){return fm({uv:this.uvNode})}}const xm=pi(Tm);Vr("checker",xm),Rr("CheckerNode",Tm);class ym extends ne{constructor(e){super(e),this.textures={}}load(e,t,s,r){const i=new oe(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,(s=>{try{t(this.parse(JSON.parse(s)))}catch(t){r&&r(t),this.manager.itemError(e)}}),s,r)}parseNodes(e){const t={};if(void 0!==e){for(const s of e){const{uuid:e,type:r}=s;t[e]=ci(Cr(r)),t[e].uuid=e}const s={nodes:t,textures:this.textures};for(const r of e){r.meta=s;t[r.uuid].deserialize(r),delete r.meta}}return t}parse(e){const t=ci(Cr(e.type));t.uuid=e.uuid;const s={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=s,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}}const bm=new ae;class Nm extends cd{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.pointWidth=1,this.pointColorNode=null,this.setDefaultValues(bm),this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor;this.vertexNode=fi((()=>{nn(Ri(),"vUv").assign(mo());const e=an("instancePosition"),t=Mn("vec4","mvPos");t.assign(zu.mul(Ui(e,1)));const s=Dc.z.div(Dc.w),r=Fu.mul(t),i=Mn("vec2","offset");return i.assign(Fl.xy),i.assign(i.mul(wl)),i.assign(i.div(Dc.z)),i.y.assign(i.y.mul(s)),i.assign(i.mul(r.w)),r.assign(r.add(Ui(i,0,0))),r}))(),this.fragmentNode=fi((()=>{const s=nn(Ri(),"vUv"),r=Mn("float","alpha");r.assign(1);const i=s.x,n=s.y,o=i.mul(i).add(n.mul(n));if(e){const e=Mn("float","dlen");e.assign(o.fwidth()),r.assign(Wa(e.oneMinus(),e.add(1),o).oneMinus())}else o.greaterThan(1).discard();let a;if(this.pointColorNode)a=this.pointColorNode;else if(t){a=an("instanceColor").mul(nl)}else a=nl;return Ui(a,r)}))(),this.needsUpdate=!0}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}dd("InstancedPointsNodeMaterial",Nm);const _m=new ue;class vm extends cd{constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(_m),this.setValues(e)}}dd("LineBasicNodeMaterial",vm);const Sm=new le;class Am extends cd{constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.lights=!1,this.normals=!1,this.setDefaultValues(Sm),this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode,t=this.dashScaleNode?_i(this.dashScaleNode):Sl,s=this.dashSizeNode?_i(this.dashSizeNode):Al,r=this.dashSizeNode?_i(this.dashGapNode):Rl;Wn.assign(s),jn.assign(r);const i=nn(an("lineDistance").mul(t));(e?i.add(e):i).mod(Wn.add(jn)).greaterThan(Wn).discard()}}dd("LineDashedNodeMaterial",Am);const Rm=new le;class Cm extends cd{constructor(e={}){super(),this.normals=!1,this.lights=!1,this.setDefaultValues(Rm),this.useAlphaToCoverage=!0,this.useColor=e.vertexColors,this.useDash=e.dashed,this.useWorldUnits=!1,this.dashOffset=0,this.lineWidth=1,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setupShaders(),this.setValues(e)}setupShaders(){const e=this.alphaToCoverage,t=this.useColor,s=this.dashed,r=this.worldUnits,i=fi((({start:e,end:t})=>{const s=Fu.element(2).element(2),r=Fu.element(3).element(2).mul(-.5).div(s).sub(e.z).div(t.z.sub(e.z));return Ui(ka(e.xyz,t.xyz,r),t.w)}));this.vertexNode=fi((()=>{Fn("vec2","vUv").assign(mo());const e=an("instanceStart"),t=an("instanceEnd"),n=Mn("vec4","start"),o=Mn("vec4","end");n.assign(zu.mul(Ui(e,1))),o.assign(zu.mul(Ui(t,1))),r&&(Fn("vec3","worldStart").assign(n.xyz),Fn("vec3","worldEnd").assign(o.xyz));const a=Dc.z.div(Dc.w),u=Fu.element(2).element(3).equal(-1);yi(u,(()=>{yi(n.z.lessThan(0).and(o.z.greaterThan(0)),(()=>{o.assign(i({start:n,end:o}))})).elseif(o.z.lessThan(0).and(n.z.greaterThanEqual(0)),(()=>{n.assign(i({start:o,end:n}))}))}));const l=Fu.mul(n),c=Fu.mul(o),d=l.xyz.div(l.w),h=c.xyz.div(c.w),p=h.xy.sub(d.xy).temp();p.x.assign(p.x.mul(a)),p.assign(p.normalize());const g=_n(Ui());if(r){const e=o.xyz.sub(n.xyz).normalize(),t=ka(n.xyz,o.xyz,.5).normalize(),r=e.cross(t).normalize(),i=e.cross(r),a=Fn("vec4","worldPos");a.assign(Fl.y.lessThan(.5).cond(n,o));const u=Cl.mul(.5);a.addAssign(Ui(Fl.x.lessThan(0).cond(r.mul(u),r.mul(u).negate()),0)),s||(a.addAssign(Ui(Fl.y.lessThan(.5).cond(e.mul(u).negate(),e.mul(u)),0)),a.addAssign(Ui(i.mul(u),0)),yi(Fl.y.greaterThan(1).or(Fl.y.lessThan(0)),(()=>{a.subAssign(Ui(i.mul(2).mul(u),0))}))),g.assign(Fu.mul(a));const l=_n(Mi());l.assign(Fl.y.lessThan(.5).cond(d,h)),g.z.assign(l.z.mul(g.w))}else{const e=Mn("vec2","offset");e.assign(Ri(p.y,p.x.negate())),p.x.assign(p.x.div(a)),e.x.assign(e.x.div(a)),e.assign(Fl.x.lessThan(0).cond(e.negate(),e)),yi(Fl.y.lessThan(0),(()=>{e.assign(e.sub(p))})).elseif(Fl.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(Cl)),e.assign(e.div(Dc.w)),g.assign(Fl.y.lessThan(.5).cond(l,c)),e.assign(e.mul(g.w)),g.assign(g.add(Ui(e,0,0)))}return g}))();const n=fi((({p1:e,p2:t,p3:s,p4:r})=>{const i=e.sub(s),n=r.sub(s),o=t.sub(e),a=i.dot(n),u=n.dot(o),l=i.dot(o),c=n.dot(n),d=o.dot(o).mul(c).sub(u.mul(u)),h=a.mul(u).sub(l.mul(c)).div(d).clamp(),p=a.add(u.mul(h)).div(c).clamp();return Ri(h,p)}));this.fragmentNode=fi((()=>{const i=Fn("vec2","vUv");if(s){const e=this.offsetNode?_i(this.offsetNodeNode):El,t=this.dashScaleNode?_i(this.dashScaleNode):Sl,s=this.dashSizeNode?_i(this.dashSizeNode):Al,r=this.dashSizeNode?_i(this.dashGapNode):Rl;Wn.assign(s),jn.assign(r);const n=an("instanceDistanceStart"),o=an("instanceDistanceEnd"),a=Fl.y.lessThan(.5).cond(t.mul(n),Sl.mul(o)),u=nn(a.add(El)),l=e?u.add(e):u;i.y.lessThan(-1).or(i.y.greaterThan(1)).discard(),l.mod(Wn.add(jn)).greaterThan(Wn).discard()}const o=Mn("float","alpha");if(o.assign(1),r){const t=Fn("vec3","worldStart"),r=Fn("vec3","worldEnd"),i=Fn("vec4","worldPos").xyz.normalize().mul(1e5),a=r.sub(t),u=n({p1:t,p2:r,p3:Mi(0,0,0),p4:i}),l=t.add(a.mul(u.x)),c=i.mul(u.y),d=l.sub(c).length().div(Cl);if(!s)if(e){const e=d.fwidth();o.assign(Wa(e.negate().add(.5),e.add(.5),d).oneMinus())}else d.greaterThan(.5).discard()}else if(e){const e=i.x,t=i.y.greaterThan(0).cond(i.y.sub(1),i.y.add(1)),s=e.mul(e).add(t.mul(t)),r=Mn("float","dlen");r.assign(s.fwidth()),yi(i.y.abs().greaterThan(1),(()=>{o.assign(Wa(r.oneMinus(),r.add(1),s).oneMinus())}))}else yi(i.y.abs().greaterThan(1),(()=>{const e=i.x,t=i.y.greaterThan(0).cond(i.y.sub(1),i.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()}));let a;if(this.lineColorNode)a=this.lineColorNode;else if(t){const e=an("instanceColorStart"),t=an("instanceColorEnd");a=Fl.y.lessThan(.5).cond(e,t).mul(nl)}else a=nl;return Ui(a,o)}))(),this.needsUpdate=!0}get worldUnits(){return this.useWorldUnits}set worldUnits(e){this.useWorldUnits!==e&&(this.useWorldUnits=e,this.setupShaders())}get dashed(){return this.useDash}set dashed(e){this.useDash!==e&&(this.useDash=e,this.setupShaders())}get alphaToCoverage(){return this.useAlphaToCoverage}set alphaToCoverage(e){this.useAlphaToCoverage!==e&&(this.useAlphaToCoverage=e,this.setupShaders())}}dd("Line2NodeMaterial",Cm);const Em=new ce;class wm extends cd{constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.colorSpaced=!1,this.setDefaultValues(Em),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?_i(this.opacityNode):ul;Bn.assign(Ui(xh(Ju),e))}}dd("MeshNormalNodeMaterial",wm);const Mm=new de;class Fm extends cd{constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!1,this.setDefaultValues(Mm),this.setValues(e)}}dd("MeshBasicNodeMaterial",Fm);const Bm=fi((({f0:e,f90:t,dotVH:s})=>{const r=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(r.oneMinus()).add(t.mul(r))})),Om=fi((e=>e.diffuseColor.mul(1/Math.PI))),Um=fi((({dotNH:e})=>$n.mul(.5/Math.PI).add(1).mul(e.pow($n)))),Lm=fi((({lightDirection:e})=>{const t=e.add(Il).normalize(),s=Ju.dot(t).clamp(),r=Il.dot(t).clamp(),i=Bm({f0:zn,f90:1,dotVH:r}),n=_i(.25),o=Um({dotNH:s});return i.mul(n).mul(o)}));class Im extends bn{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const r=Ju.dot(e).clamp().mul(t);s.directDiffuse.addAssign(r.mul(Om({diffuseColor:Bn.rgb}))),!0===this.specular&&s.directSpecular.addAssign(r.mul(Lm({lightDirection:e})).mul(cl))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Om({diffuseColor:Bn})))}}const Pm=new he;class Dm extends cd{constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Pm),this.setValues(e)}setupLightingModel(){return new Im(!1)}}dd("MeshLambertNodeMaterial",Dm);const Vm=new pe;class Gm extends cd{constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Vm),this.setValues(e)}setupLightingModel(){return new Im}setupVariants(){const e=(this.shininessNode?_i(this.shininessNode):ol).max(1e-4);$n.assign(e);const t=this.specularNode||ll;zn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}dd("MeshPhongNodeMaterial",Gm);const km=fi((()=>{const e=Yu.dFdx().abs().max(Yu.dFdy().abs());return e.x.max(e.y).max(e.z)})),zm=fi((e=>{const{roughness:t}=e,s=km();let r=t.max(.0525);return r=r.add(s),r=r.min(1),r})),$m=fi((e=>{const{alpha:t,dotNL:s,dotNV:r}=e,i=t.pow2(),n=s.mul(i.add(i.oneMinus().mul(r.pow2())).sqrt()),o=r.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt());return _o(.5,n.add(o).max(ko))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Hm=fi((({alpha:e,dotNH:t})=>{const s=e.pow2(),r=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(r.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),Wm=fi((e=>{const{lightDirection:t,f0:s,f90:r,roughness:i,iridescenceFresnel:n}=e,o=e.normalView||Ju,a=i.pow2(),u=t.add(Il).normalize(),l=o.dot(t).clamp(),c=o.dot(Il).clamp(),d=o.dot(u).clamp(),h=Il.dot(u).clamp();let p=Bm({f0:s,f90:r,dotVH:h});n&&(p=Vn.mix(p,n));const g=$m({alpha:a,dotNL:l,dotNV:c}),m=Hm({alpha:a,dotNH:d});return p.mul(g).mul(m)})),jm=fi((({roughness:e,dotNV:t})=>{const s=Ui(-1,-.0275,-.572,.022),r=Ui(1,.0425,1.04,-.04),i=e.mul(s).add(r),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return Ri(-1.04,1.04).mul(n).add(i.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),qm=fi((e=>{const{dotNV:t,specularColor:s,specularF90:r,roughness:i}=e,n=jm({dotNV:t,roughness:i});return s.mul(n.x).add(r.mul(n.y))})),Xm=fi((({f:e,f90:t,dotVH:s})=>{const r=s.oneMinus().saturate(),i=r.mul(r),n=r.mul(i,i).clamp(0,.9999);return e.sub(Mi(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"}]}),Ym=fi((({roughness:e,dotNH:t})=>{const s=e.pow2(),r=_i(1).div(s),i=t.pow2().oneMinus().max(.0078125);return _i(2).add(r).mul(i.pow(r.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),Km=fi((({dotNV:e,dotNL:t})=>_i(1).div(_i(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Qm=fi((({lightDirection:e})=>{const t=e.add(Il).normalize(),s=Ju.dot(e).clamp(),r=Ju.dot(Il).clamp(),i=Ju.dot(t).clamp(),n=Ym({roughness:Dn,dotNH:i}),o=Km({dotNV:r,dotNL:s});return Pn.mul(n).mul(o)})),Zm=zi(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Jm=(e,t)=>e.sub(t).div(e.add(t)).pow2(),ef=(e,t)=>{const s=e.mul(2*Math.PI*1e-9),r=Mi(54856e-17,44201e-17,52481e-17),i=Mi(1681e3,1795300,2208400),n=Mi(43278e5,93046e5,66121e5),o=_i(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=r.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());a=Mi(a.x.add(o),a.y,a.z).div(1.0685e-7);return Zm.mul(a)},tf=fi((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:r,baseF0:i})=>{const n=ka(e,t,Wa(0,.03,r)),o=e.div(n).pow2().mul(_i(1).sub(s.pow2())),a=_i(1).sub(o).sqrt(),u=Jm(n,e),l=Bm({f0:u,f90:1,dotVH:s}),c=l.oneMinus(),d=n.lessThan(e).cond(Math.PI,0),h=_i(Math.PI).sub(d),p=(e=>{const t=e.sqrt();return Mi(1).add(t).div(Mi(1).sub(t))})(i.clamp(0,.9999)),g=Jm(p,n.vec3()),m=Bm({f0:g,f90:1,dotVH:a}),f=Mi(p.x.lessThan(n).cond(Math.PI,0),p.y.lessThan(n).cond(Math.PI,0),p.z.lessThan(n).cond(Math.PI,0)),T=n.mul(r,a,2),x=Mi(h).add(f),y=l.mul(m).clamp(1e-5,.9999),b=y.sqrt(),N=c.pow2().mul(m).div(Mi(1).sub(y));let _=l.add(N),v=N.sub(c);for(let e=1;e<=2;++e){v=v.mul(b);const t=ef(_i(e).mul(T),_i(e).mul(x)).mul(2);_=_.add(v.mul(t))}return _.max(Mi(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"}]}),sf=fi((({normal:e,viewDir:t,roughness:s})=>{const r=e.dot(t).saturate(),i=s.pow2(),n=wd(s.lessThan(.25),_i(-339.2).mul(i).add(_i(161.4).mul(s)).sub(25.9),_i(-8.48).mul(i).add(_i(14.3).mul(s)).sub(9.95)),o=wd(s.lessThan(.25),_i(44).mul(i).sub(_i(23.7).mul(s)).add(3.26),_i(1.97).mul(i).sub(_i(3.27).mul(s)).add(.72));return wd(s.lessThan(.25),0,_i(.1).mul(s).sub(.025)).add(n.mul(r).add(o).exp()).mul(1/Math.PI).saturate()})),rf=Mi(.04),nf=Mi(1);class of extends bn{constructor(e=!1,t=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(){if(!0===this.clearcoat&&(this.clearcoatRadiance=Mi().temp("clearcoatRadiance"),this.clearcoatSpecularDirect=Mi().temp("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Mi().temp("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Mi().temp("sheenSpecularDirect"),this.sheenSpecularIndirect=Mi().temp("sheenSpecularIndirect")),!0===this.iridescence){const e=Ju.dot(Il).clamp();this.iridescenceFresnel=tf({outsideIOR:_i(1),eta2:Gn,cosTheta1:e,thinFilmThickness:kn,baseF0:zn}),this.iridescenceF0=Xm({f:this.iridescenceFresnel,f90:1,dotVH:e})}}computeMultiscattering(e,t,s=_i(1)){const r=Ju.dot(Il).clamp(),i=jm({roughness:On,dotNV:r}),n=(this.iridescenceF0?Vn.mix(zn,this.iridescenceF0):zn).mul(i.x).add(s.mul(i.y)),o=i.x.add(i.y).oneMinus(),a=zn.add(zn.oneMinus().mul(.047619)),u=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(u.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const r=Ju.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(r.mul(Qm({lightDirection:e}))),!0===this.clearcoat){const s=tl.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(Wm({lightDirection:e,f0:rf,f90:nf,roughness:In,normalView:tl})))}s.directDiffuse.addAssign(r.mul(Om({diffuseColor:Bn.rgb}))),s.directSpecular.addAssign(r.mul(Wm({lightDirection:e,f0:zn,f90:1,roughness:On,iridescence:this.iridescence,iridescenceFresnel:this.iridescenceFresnel})))}indirectDiffuse({irradiance:e,reflectedLight:t}){t.indirectDiffuse.addAssign(e.mul(Om({diffuseColor:Bn})))}indirectSpecular({radiance:e,iblIrradiance:t,reflectedLight:s}){if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(t.mul(Pn,sf({normal:Ju,viewDir:Il,roughness:Dn}))),!0===this.clearcoat){const e=tl.dot(Il).clamp(),t=qm({dotNV:e,specularColor:rf,specularF90:nf,roughness:In});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=Mi().temp("singleScattering"),i=Mi().temp("multiScattering"),n=t.mul(1/Math.PI);this.computeMultiscattering(r,i);const o=r.add(i),a=Bn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(e.mul(r)),s.indirectSpecular.addAssign(i.mul(n)),s.indirectDiffuse.addAssign(a.mul(n))}ambientOcclusion({ambientOcclusion:e,reflectedLight:t}){const s=Ju.dot(Il).clamp().add(e),r=On.mul(-16).oneMinus().negate().exp2(),i=e.sub(s.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(e),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(e),t.indirectDiffuse.mulAssign(e),t.indirectSpecular.mulAssign(i)}finish(e){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=tl.dot(Il).clamp(),s=Bm({dotVH:e,f0:rf,f90:nf}),r=t.mul(Ln.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Ln));t.assign(r)}if(!0===this.sheen){const e=Pn.r.max(Pn.g).max(Pn.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const af=new ge;class uf extends cd{constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(af),this.setValues(e)}setupLightingModel(){return new of}setupVariants(){const e=this.metalnessNode?_i(this.metalnessNode):pl;Un.assign(e);let t=this.roughnessNode?_i(this.roughnessNode):hl;t=zm({roughness:t}),On.assign(t);const s=ka(Mi(.04),Bn.rgb,e);zn.assign(s),Bn.assign(Ui(Bn.rgb.mul(e.oneMinus()),Bn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}dd("MeshStandardNodeMaterial",uf);const lf=new me;class cf extends uf{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.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.setDefaultValues(lf),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}setupLightingModel(){return new of(this.useClearcoat,this.useSheen,this.useIridescence)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?_i(this.clearcoatNode):ml,t=this.clearcoatRoughnessNode?_i(this.clearcoatRoughnessNode):fl;Ln.assign(e),In.assign(t)}if(this.useSheen){const e=this.sheenNode?Mi(this.sheenNode):yl,t=this.sheenRoughnessNode?_i(this.sheenRoughnessNode):bl;Pn.assign(e),Dn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?_i(this.iridescenceNode):Nl,t=this.iridescenceIORNode?_i(this.iridescenceIORNode):_l,s=this.iridescenceThicknessNode?_i(this.iridescenceThicknessNode):vl;Vn.assign(e),Gn.assign(t),kn.assign(s)}}setupNormal(e){super.setupNormal(e);const t=this.clearcoatNormalNode?Mi(this.clearcoatNormalNode):Tl;tl.assign(t)}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,super.copy(e)}}dd("MeshPhysicalNodeMaterial",cf);class df extends of{constructor(e,t,s,r){super(e,t,s),this.useSSS=r}direct({lightDirection:e,lightColor:t,reflectedLight:s},r,i){if(!0===this.useSSS){const r=i.material,{thicknessColorNode:n,thicknessDistortionNode:o,thicknessAmbientNode:a,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:c}=r,d=e.add(Ju.mul(o)).normalize(),h=_i(Il.dot(d.negate()).saturate().pow(l).mul(c)),p=Mi(h.add(a).mul(n));s.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:s},r,i)}}class hf extends cf{constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=_i(.1),this.thicknessAmbientNode=_i(0),this.thicknessAttenuationNode=_i(.1),this.thicknessPowerNode=_i(2),this.thicknessScaleNode=_i(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new df(this.useClearcoat,this.useSheen,this.useIridescence,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)}}dd("MeshSSSNodeMaterial",hf);const pf=new ae;class gf extends cd{constructor(e){super(),this.isPointsNodeMaterial=!0,this.lights=!1,this.normals=!1,this.transparent=!0,this.sizeNode=null,this.setDefaultValues(pf),this.setValues(e)}copy(e){return this.sizeNode=e.sizeNode,super.copy(e)}}dd("PointsNodeMaterial",gf);const mf=new fe;class ff extends cd{constructor(e){super(),this.isSpriteNodeMaterial=!0,this.lights=!1,this.normals=!1,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.setDefaultValues(mf),this.setValues(e)}setupPosition({object:e,context:t}){const{positionNode:s,rotationNode:r,scaleNode:i}=this,n=Bl;let o=zu.mul(Mi(s||0)),a=Ri(Hu[0].xyz.length(),Hu[1].xyz.length());null!==i&&(a=a.mul(i));let u=n.xy;e.center&&!0===e.center.isVector2&&(u=u.sub(po(e.center).sub(.5))),u=u.mul(a);const l=_i(r||xl),c=u.rotate(l);o=Ui(o.xy.add(c),o.zw);const d=Fu.mul(o);return t.vertex=n,d}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}}dd("SpriteNodeMaterial",ff);const Tf=Te.createMaterialFromType;Te.createMaterialFromType=function(e){const t=hd(e);return void 0!==t?t:Tf.call(this,e)};class xf extends Te{constructor(e){super(e),this.nodes={}}parse(e){const t=super.parse(e),s=this.nodes,r=e.inputNodes;for(const e in r){const i=r[e];t[e]=s[i]}return t}setNodes(e){return this.nodes=e,this}}class yf extends xe{constructor(e){super(e),this._nodesJSON=null}parse(e,t){this._nodesJSON=e.nodes;const s=super.parse(e,t);return this._nodesJSON=null,s}parseNodes(e,t){if(void 0!==e){const s=new ym;return s.setTextures(t),s.parseNodes(e)}return{}}parseMaterials(e,t){const s={};if(void 0!==e){const r=this.parseNodes(this._nodesJSON,t),i=new xf;i.setTextures(t),i.setNodes(r);for(let t=0,r=e.length;t{const t=(e=e.trim()).indexOf(Sf),s=-1!==t?e.slice(t+12):e,r=s.match(_f);if(null!==r&&5===r.length){const i=r[4],n=[];let o=null;for(;null!==(o=vf.exec(i));)n.push(o);const a=[];let u=0;for(;u{const r=_i(s).toVar(),i=_i(t).toVar(),n=Ai(e).toVar();return wd(n,i,r)})),Ef=fi((([e,t])=>{const s=Ai(t).toVar(),r=_i(e).toVar();return wd(s,r.negate(),r)})),wf=fi((([e])=>{const t=_i(e).toVar();return vi(sa(t))})),Mf=fi((([e,t])=>{const s=_i(e).toVar();return t.assign(wf(s)),s.sub(_i(t))})),Ff=fi((([e,t,s,r,i,n])=>{const o=_i(n).toVar(),a=_i(i).toVar(),u=_i(r).toVar(),l=_i(s).toVar(),c=_i(t).toVar(),d=_i(e).toVar(),h=_i(bo(1,a)).toVar();return bo(1,o).mul(d.mul(h).add(c.mul(a))).add(o.mul(l.mul(h).add(u.mul(a))))})),Bf=fi((([e,t,s,r,i,n])=>{const o=_i(n).toVar(),a=_i(i).toVar(),u=Mi(r).toVar(),l=Mi(s).toVar(),c=Mi(t).toVar(),d=Mi(e).toVar(),h=_i(bo(1,a)).toVar();return bo(1,o).mul(d.mul(h).add(c.mul(a))).add(o.mul(l.mul(h).add(u.mul(a))))})),Of=ih([Ff,Bf]),Uf=fi((([e,t,s,r,i,n,o,a,u,l,c])=>{const d=_i(c).toVar(),h=_i(l).toVar(),p=_i(u).toVar(),g=_i(a).toVar(),m=_i(o).toVar(),f=_i(n).toVar(),T=_i(i).toVar(),x=_i(r).toVar(),y=_i(s).toVar(),b=_i(t).toVar(),N=_i(e).toVar(),_=_i(bo(1,p)).toVar(),v=_i(bo(1,h)).toVar();return _i(bo(1,d)).toVar().mul(v.mul(N.mul(_).add(b.mul(p))).add(h.mul(y.mul(_).add(x.mul(p))))).add(d.mul(v.mul(T.mul(_).add(f.mul(p))).add(h.mul(m.mul(_).add(g.mul(p))))))})),Lf=fi((([e,t,s,r,i,n,o,a,u,l,c])=>{const d=_i(c).toVar(),h=_i(l).toVar(),p=_i(u).toVar(),g=Mi(a).toVar(),m=Mi(o).toVar(),f=Mi(n).toVar(),T=Mi(i).toVar(),x=Mi(r).toVar(),y=Mi(s).toVar(),b=Mi(t).toVar(),N=Mi(e).toVar(),_=_i(bo(1,p)).toVar(),v=_i(bo(1,h)).toVar();return _i(bo(1,d)).toVar().mul(v.mul(N.mul(_).add(b.mul(p))).add(h.mul(y.mul(_).add(x.mul(p))))).add(d.mul(v.mul(T.mul(_).add(f.mul(p))).add(h.mul(m.mul(_).add(g.mul(p))))))})),If=ih([Uf,Lf]),Pf=fi((([e,t,s])=>{const r=_i(s).toVar(),i=_i(t).toVar(),n=Si(e).toVar(),o=Si(n.bitAnd(Si(7))).toVar(),a=_i(Cf(o.lessThan(Si(4)),i,r)).toVar(),u=_i(No(2,Cf(o.lessThan(Si(4)),r,i))).toVar();return Ef(a,Ai(o.bitAnd(Si(1)))).add(Ef(u,Ai(o.bitAnd(Si(2)))))})),Df=fi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=_i(t).toVar(),a=Si(e).toVar(),u=Si(a.bitAnd(Si(15))).toVar(),l=_i(Cf(u.lessThan(Si(8)),o,n)).toVar(),c=_i(Cf(u.lessThan(Si(4)),n,Cf(u.equal(Si(12)).or(u.equal(Si(14))),o,i))).toVar();return Ef(l,Ai(u.bitAnd(Si(1)))).add(Ef(c,Ai(u.bitAnd(Si(2)))))})),Vf=ih([Pf,Df]),Gf=fi((([e,t,s])=>{const r=_i(s).toVar(),i=_i(t).toVar(),n=Bi(e).toVar();return Mi(Vf(n.x,i,r),Vf(n.y,i,r),Vf(n.z,i,r))})),kf=fi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=_i(t).toVar(),a=Bi(e).toVar();return Mi(Vf(a.x,o,n,i),Vf(a.y,o,n,i),Vf(a.z,o,n,i))})),zf=ih([Gf,kf]),$f=fi((([e])=>{const t=_i(e).toVar();return No(.6616,t)})),Hf=fi((([e])=>{const t=_i(e).toVar();return No(.982,t)})),Wf=fi((([e])=>{const t=Mi(e).toVar();return No(.6616,t)})),jf=ih([$f,Wf]),qf=fi((([e])=>{const t=Mi(e).toVar();return No(.982,t)})),Xf=ih([Hf,qf]),Yf=fi((([e,t])=>{const s=vi(t).toVar(),r=Si(e).toVar();return r.shiftLeft(s).bitOr(r.shiftRight(vi(32).sub(s)))})),Kf=fi((([e,t,s])=>{e.subAssign(s),e.bitXorAssign(Yf(s,vi(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(Yf(e,vi(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(Yf(t,vi(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(Yf(s,vi(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(Yf(e,vi(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(Yf(t,vi(4))),t.addAssign(e)})),Qf=fi((([e,t,s])=>{const r=Si(s).toVar(),i=Si(t).toVar(),n=Si(e).toVar();return r.bitXorAssign(i),r.subAssign(Yf(i,vi(14))),n.bitXorAssign(r),n.subAssign(Yf(r,vi(11))),i.bitXorAssign(n),i.subAssign(Yf(n,vi(25))),r.bitXorAssign(i),r.subAssign(Yf(i,vi(16))),n.bitXorAssign(r),n.subAssign(Yf(r,vi(4))),i.bitXorAssign(n),i.subAssign(Yf(n,vi(14))),r.bitXorAssign(i),r.subAssign(Yf(i,vi(24))),r})),Zf=fi((([e])=>{const t=Si(e).toVar();return _i(t).div(_i(Si(vi(4294967295))))})),Jf=fi((([e])=>{const t=_i(e).toVar();return t.mul(t.mul(t.mul(t.mul(t.mul(6).sub(15)).add(10))))})),eT=fi((([e])=>{const t=vi(e).toVar(),s=Si(Si(1)).toVar(),r=Si(Si(vi(3735928559)).add(s.shiftLeft(Si(2)).add(Si(13)))).toVar();return Qf(r.add(Si(t)),r,r)})),tT=fi((([e,t])=>{const s=vi(t).toVar(),r=vi(e).toVar(),i=Si(Si(2)).toVar(),n=Si().toVar(),o=Si().toVar(),a=Si().toVar();return n.assign(o.assign(a.assign(Si(vi(3735928559)).add(i.shiftLeft(Si(2)).add(Si(13)))))),n.addAssign(Si(r)),o.addAssign(Si(s)),Qf(n,o,a)})),sT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=vi(t).toVar(),n=vi(e).toVar(),o=Si(Si(3)).toVar(),a=Si().toVar(),u=Si().toVar(),l=Si().toVar();return a.assign(u.assign(l.assign(Si(vi(3735928559)).add(o.shiftLeft(Si(2)).add(Si(13)))))),a.addAssign(Si(n)),u.addAssign(Si(i)),l.addAssign(Si(r)),Qf(a,u,l)})),rT=fi((([e,t,s,r])=>{const i=vi(r).toVar(),n=vi(s).toVar(),o=vi(t).toVar(),a=vi(e).toVar(),u=Si(Si(4)).toVar(),l=Si().toVar(),c=Si().toVar(),d=Si().toVar();return l.assign(c.assign(d.assign(Si(vi(3735928559)).add(u.shiftLeft(Si(2)).add(Si(13)))))),l.addAssign(Si(a)),c.addAssign(Si(o)),d.addAssign(Si(n)),Kf(l,c,d),l.addAssign(Si(i)),Qf(l,c,d)})),iT=fi((([e,t,s,r,i])=>{const n=vi(i).toVar(),o=vi(r).toVar(),a=vi(s).toVar(),u=vi(t).toVar(),l=vi(e).toVar(),c=Si(Si(5)).toVar(),d=Si().toVar(),h=Si().toVar(),p=Si().toVar();return d.assign(h.assign(p.assign(Si(vi(3735928559)).add(c.shiftLeft(Si(2)).add(Si(13)))))),d.addAssign(Si(l)),h.addAssign(Si(u)),p.addAssign(Si(a)),Kf(d,h,p),d.addAssign(Si(o)),h.addAssign(Si(n)),Qf(d,h,p)})),nT=ih([eT,tT,sT,rT,iT]),oT=fi((([e,t])=>{const s=vi(t).toVar(),r=vi(e).toVar(),i=Si(nT(r,s)).toVar(),n=Bi().toVar();return n.x.assign(i.bitAnd(vi(255))),n.y.assign(i.shiftRight(vi(8)).bitAnd(vi(255))),n.z.assign(i.shiftRight(vi(16)).bitAnd(vi(255))),n})),aT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=vi(t).toVar(),n=vi(e).toVar(),o=Si(nT(n,i,r)).toVar(),a=Bi().toVar();return a.x.assign(o.bitAnd(vi(255))),a.y.assign(o.shiftRight(vi(8)).bitAnd(vi(255))),a.z.assign(o.shiftRight(vi(16)).bitAnd(vi(255))),a})),uT=ih([oT,aT]),lT=fi((([e])=>{const t=Ri(e).toVar(),s=vi().toVar(),r=vi().toVar(),i=_i(Mf(t.x,s)).toVar(),n=_i(Mf(t.y,r)).toVar(),o=_i(Jf(i)).toVar(),a=_i(Jf(n)).toVar(),u=_i(Of(Vf(nT(s,r),i,n),Vf(nT(s.add(vi(1)),r),i.sub(1),n),Vf(nT(s,r.add(vi(1))),i,n.sub(1)),Vf(nT(s.add(vi(1)),r.add(vi(1))),i.sub(1),n.sub(1)),o,a)).toVar();return jf(u)})),cT=fi((([e])=>{const t=Mi(e).toVar(),s=vi().toVar(),r=vi().toVar(),i=vi().toVar(),n=_i(Mf(t.x,s)).toVar(),o=_i(Mf(t.y,r)).toVar(),a=_i(Mf(t.z,i)).toVar(),u=_i(Jf(n)).toVar(),l=_i(Jf(o)).toVar(),c=_i(Jf(a)).toVar(),d=_i(If(Vf(nT(s,r,i),n,o,a),Vf(nT(s.add(vi(1)),r,i),n.sub(1),o,a),Vf(nT(s,r.add(vi(1)),i),n,o.sub(1),a),Vf(nT(s.add(vi(1)),r.add(vi(1)),i),n.sub(1),o.sub(1),a),Vf(nT(s,r,i.add(vi(1))),n,o,a.sub(1)),Vf(nT(s.add(vi(1)),r,i.add(vi(1))),n.sub(1),o,a.sub(1)),Vf(nT(s,r.add(vi(1)),i.add(vi(1))),n,o.sub(1),a.sub(1)),Vf(nT(s.add(vi(1)),r.add(vi(1)),i.add(vi(1))),n.sub(1),o.sub(1),a.sub(1)),u,l,c)).toVar();return Xf(d)})),dT=ih([lT,cT]),hT=fi((([e])=>{const t=Ri(e).toVar(),s=vi().toVar(),r=vi().toVar(),i=_i(Mf(t.x,s)).toVar(),n=_i(Mf(t.y,r)).toVar(),o=_i(Jf(i)).toVar(),a=_i(Jf(n)).toVar(),u=Mi(Of(zf(uT(s,r),i,n),zf(uT(s.add(vi(1)),r),i.sub(1),n),zf(uT(s,r.add(vi(1))),i,n.sub(1)),zf(uT(s.add(vi(1)),r.add(vi(1))),i.sub(1),n.sub(1)),o,a)).toVar();return jf(u)})),pT=fi((([e])=>{const t=Mi(e).toVar(),s=vi().toVar(),r=vi().toVar(),i=vi().toVar(),n=_i(Mf(t.x,s)).toVar(),o=_i(Mf(t.y,r)).toVar(),a=_i(Mf(t.z,i)).toVar(),u=_i(Jf(n)).toVar(),l=_i(Jf(o)).toVar(),c=_i(Jf(a)).toVar(),d=Mi(If(zf(uT(s,r,i),n,o,a),zf(uT(s.add(vi(1)),r,i),n.sub(1),o,a),zf(uT(s,r.add(vi(1)),i),n,o.sub(1),a),zf(uT(s.add(vi(1)),r.add(vi(1)),i),n.sub(1),o.sub(1),a),zf(uT(s,r,i.add(vi(1))),n,o,a.sub(1)),zf(uT(s.add(vi(1)),r,i.add(vi(1))),n.sub(1),o,a.sub(1)),zf(uT(s,r.add(vi(1)),i.add(vi(1))),n,o.sub(1),a.sub(1)),zf(uT(s.add(vi(1)),r.add(vi(1)),i.add(vi(1))),n.sub(1),o.sub(1),a.sub(1)),u,l,c)).toVar();return Xf(d)})),gT=ih([hT,pT]),mT=fi((([e])=>{const t=_i(e).toVar(),s=vi(wf(t)).toVar();return Zf(nT(s))})),fT=fi((([e])=>{const t=Ri(e).toVar(),s=vi(wf(t.x)).toVar(),r=vi(wf(t.y)).toVar();return Zf(nT(s,r))})),TT=fi((([e])=>{const t=Mi(e).toVar(),s=vi(wf(t.x)).toVar(),r=vi(wf(t.y)).toVar(),i=vi(wf(t.z)).toVar();return Zf(nT(s,r,i))})),xT=fi((([e])=>{const t=Ui(e).toVar(),s=vi(wf(t.x)).toVar(),r=vi(wf(t.y)).toVar(),i=vi(wf(t.z)).toVar(),n=vi(wf(t.w)).toVar();return Zf(nT(s,r,i,n))})),yT=ih([mT,fT,TT,xT]),bT=fi((([e])=>{const t=_i(e).toVar(),s=vi(wf(t)).toVar();return Mi(Zf(nT(s,vi(0))),Zf(nT(s,vi(1))),Zf(nT(s,vi(2))))})),NT=fi((([e])=>{const t=Ri(e).toVar(),s=vi(wf(t.x)).toVar(),r=vi(wf(t.y)).toVar();return Mi(Zf(nT(s,r,vi(0))),Zf(nT(s,r,vi(1))),Zf(nT(s,r,vi(2))))})),_T=fi((([e])=>{const t=Mi(e).toVar(),s=vi(wf(t.x)).toVar(),r=vi(wf(t.y)).toVar(),i=vi(wf(t.z)).toVar();return Mi(Zf(nT(s,r,i,vi(0))),Zf(nT(s,r,i,vi(1))),Zf(nT(s,r,i,vi(2))))})),vT=fi((([e])=>{const t=Ui(e).toVar(),s=vi(wf(t.x)).toVar(),r=vi(wf(t.y)).toVar(),i=vi(wf(t.z)).toVar(),n=vi(wf(t.w)).toVar();return Mi(Zf(nT(s,r,i,n,vi(0))),Zf(nT(s,r,i,n,vi(1))),Zf(nT(s,r,i,n,vi(2))))})),ST=ih([bT,NT,_T,vT]),AT=fi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=vi(t).toVar(),a=Mi(e).toVar(),u=_i(0).toVar(),l=_i(1).toVar();return sc({start:vi(0),end:o},(({i:e})=>{u.addAssign(l.mul(dT(a))),l.mulAssign(i),a.mulAssign(n)})),u})),RT=fi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=vi(t).toVar(),a=Mi(e).toVar(),u=Mi(0).toVar(),l=_i(1).toVar();return sc({start:vi(0),end:o},(({i:e})=>{u.addAssign(l.mul(gT(a))),l.mulAssign(i),a.mulAssign(n)})),u})),CT=fi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=vi(t).toVar(),a=Mi(e).toVar();return Ri(AT(a,o,n,i),AT(a.add(Mi(vi(19),vi(193),vi(17))),o,n,i))})),ET=fi((([e,t,s,r])=>{const i=_i(r).toVar(),n=_i(s).toVar(),o=vi(t).toVar(),a=Mi(e).toVar(),u=Mi(RT(a,o,n,i)).toVar(),l=_i(AT(a.add(Mi(vi(19),vi(193),vi(17))),o,n,i)).toVar();return Ui(u,l)})),wT=fi((([e,t,s,r,i,n,o])=>{const a=vi(o).toVar(),u=_i(n).toVar(),l=vi(i).toVar(),c=vi(r).toVar(),d=vi(s).toVar(),h=vi(t).toVar(),p=Ri(e).toVar(),g=Mi(ST(Ri(h.add(c),d.add(l)))).toVar(),m=Ri(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Ri(Ri(_i(h),_i(d)).add(m)).toVar(),T=Ri(f.sub(p)).toVar();return yi(a.equal(vi(2)),(()=>ha(T.x).add(ha(T.y)))),yi(a.equal(vi(3)),(()=>Ra(ha(T.x),ha(T.y)))),Ba(T,T)})),MT=fi((([e,t,s,r,i,n,o,a,u])=>{const l=vi(u).toVar(),c=_i(a).toVar(),d=vi(o).toVar(),h=vi(n).toVar(),p=vi(i).toVar(),g=vi(r).toVar(),m=vi(s).toVar(),f=vi(t).toVar(),T=Mi(e).toVar(),x=Mi(ST(Mi(f.add(p),m.add(h),g.add(d)))).toVar();x.subAssign(.5),x.mulAssign(c),x.addAssign(.5);const y=Mi(Mi(_i(f),_i(m),_i(g)).add(x)).toVar(),b=Mi(y.sub(T)).toVar();return yi(l.equal(vi(2)),(()=>ha(b.x).add(ha(b.y).add(ha(b.z))))),yi(l.equal(vi(3)),(()=>Ra(Ra(ha(b.x),ha(b.y)),ha(b.z)))),Ba(b,b)})),FT=ih([wT,MT]),BT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=_i(t).toVar(),n=Ri(e).toVar(),o=vi().toVar(),a=vi().toVar(),u=Ri(Mf(n.x,o),Mf(n.y,a)).toVar(),l=_i(1e6).toVar();return sc({start:-1,end:vi(1),name:"x",condition:"<="},(({x:e})=>{sc({start:-1,end:vi(1),name:"y",condition:"<="},(({y:t})=>{const s=_i(FT(u,e,t,o,a,i,r)).toVar();l.assign(Aa(l,s))}))})),yi(r.equal(vi(0)),(()=>{l.assign(ea(l))})),l})),OT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=_i(t).toVar(),n=Ri(e).toVar(),o=vi().toVar(),a=vi().toVar(),u=Ri(Mf(n.x,o),Mf(n.y,a)).toVar(),l=Ri(1e6,1e6).toVar();return sc({start:-1,end:vi(1),name:"x",condition:"<="},(({x:e})=>{sc({start:-1,end:vi(1),name:"y",condition:"<="},(({y:t})=>{const s=_i(FT(u,e,t,o,a,i,r)).toVar();yi(s.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(s)})).elseif(s.lessThan(l.y),(()=>{l.y.assign(s)}))}))})),yi(r.equal(vi(0)),(()=>{l.assign(ea(l))})),l})),UT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=_i(t).toVar(),n=Ri(e).toVar(),o=vi().toVar(),a=vi().toVar(),u=Ri(Mf(n.x,o),Mf(n.y,a)).toVar(),l=Mi(1e6,1e6,1e6).toVar();return sc({start:-1,end:vi(1),name:"x",condition:"<="},(({x:e})=>{sc({start:-1,end:vi(1),name:"y",condition:"<="},(({y:t})=>{const s=_i(FT(u,e,t,o,a,i,r)).toVar();yi(s.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(s)})).elseif(s.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(s)})).elseif(s.lessThan(l.z),(()=>{l.z.assign(s)}))}))})),yi(r.equal(vi(0)),(()=>{l.assign(ea(l))})),l})),LT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=_i(t).toVar(),n=Mi(e).toVar(),o=vi().toVar(),a=vi().toVar(),u=vi().toVar(),l=Mi(Mf(n.x,o),Mf(n.y,a),Mf(n.z,u)).toVar(),c=_i(1e6).toVar();return sc({start:-1,end:vi(1),name:"x",condition:"<="},(({x:e})=>{sc({start:-1,end:vi(1),name:"y",condition:"<="},(({y:t})=>{sc({start:-1,end:vi(1),name:"z",condition:"<="},(({z:s})=>{const n=_i(FT(l,e,t,s,o,a,u,i,r)).toVar();c.assign(Aa(c,n))}))}))})),yi(r.equal(vi(0)),(()=>{c.assign(ea(c))})),c})),IT=ih([BT,LT]),PT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=_i(t).toVar(),n=Mi(e).toVar(),o=vi().toVar(),a=vi().toVar(),u=vi().toVar(),l=Mi(Mf(n.x,o),Mf(n.y,a),Mf(n.z,u)).toVar(),c=Ri(1e6,1e6).toVar();return sc({start:-1,end:vi(1),name:"x",condition:"<="},(({x:e})=>{sc({start:-1,end:vi(1),name:"y",condition:"<="},(({y:t})=>{sc({start:-1,end:vi(1),name:"z",condition:"<="},(({z:s})=>{const n=_i(FT(l,e,t,s,o,a,u,i,r)).toVar();yi(n.lessThan(c.x),(()=>{c.y.assign(c.x),c.x.assign(n)})).elseif(n.lessThan(c.y),(()=>{c.y.assign(n)}))}))}))})),yi(r.equal(vi(0)),(()=>{c.assign(ea(c))})),c})),DT=ih([OT,PT]),VT=fi((([e,t,s])=>{const r=vi(s).toVar(),i=_i(t).toVar(),n=Mi(e).toVar(),o=vi().toVar(),a=vi().toVar(),u=vi().toVar(),l=Mi(Mf(n.x,o),Mf(n.y,a),Mf(n.z,u)).toVar(),c=Mi(1e6,1e6,1e6).toVar();return sc({start:-1,end:vi(1),name:"x",condition:"<="},(({x:e})=>{sc({start:-1,end:vi(1),name:"y",condition:"<="},(({y:t})=>{sc({start:-1,end:vi(1),name:"z",condition:"<="},(({z:s})=>{const n=_i(FT(l,e,t,s,o,a,u,i,r)).toVar();yi(n.lessThan(c.x),(()=>{c.z.assign(c.y),c.y.assign(c.x),c.x.assign(n)})).elseif(n.lessThan(c.y),(()=>{c.z.assign(c.y),c.y.assign(n)})).elseif(n.lessThan(c.z),(()=>{c.z.assign(n)}))}))}))})),yi(r.equal(vi(0)),(()=>{c.assign(ea(c))})),c})),GT=ih([UT,VT]);Cf.setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),Ef.setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),wf.setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),Ff.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"}]}),Bf.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"}]}),Uf.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"}]}),Lf.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"}]}),Pf.setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Df.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"}]}),Gf.setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),kf.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"}]}),$f.setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Hf.setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),Wf.setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),qf.setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]}),Yf.setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),Qf.setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),Zf.setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),Jf.setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),eT.setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),tT.setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),sT.setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),rT.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"}]}),iT.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"}]}),oT.setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),aT.setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),lT.setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),cT.setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]}),hT.setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),pT.setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),mT.setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),fT.setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),TT.setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),xT.setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]}),bT.setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),NT.setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),_T.setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),vT.setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]}),AT.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"}]}),RT.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"}]}),CT.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"}]}),ET.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"}]}),wT.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"}]}),MT.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"}]}),BT.setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),OT.setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),UT.setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),LT.setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),PT.setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),VT.setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]});const kT=fi((([e])=>{const t=Mi(e).toVar(),s=_i(t.x).toVar(),r=_i(t.y).toVar(),i=_i(t.z).toVar();yi(r.lessThan(1e-4),(()=>Mi(i,i,i))).else((()=>{s.assign(No(6,s.sub(sa(s))));const e=vi(Na(s)).toVar(),t=_i(s.sub(_i(e))).toVar(),n=_i(i.mul(bo(1,r))).toVar(),o=_i(i.mul(bo(1,r.mul(t)))).toVar(),a=_i(i.mul(bo(1,r.mul(bo(1,t))))).toVar();return yi(e.equal(vi(0)),(()=>Mi(i,a,n))).elseif(e.equal(vi(1)),(()=>Mi(o,i,n))).elseif(e.equal(vi(2)),(()=>Mi(n,i,a))).elseif(e.equal(vi(3)),(()=>Mi(n,o,i))).elseif(e.equal(vi(4)),(()=>Mi(a,n,i))),Mi(i,n,o)}))})),zT=fi((([e])=>{const t=Mi(e).toVar(),s=_i(t.x).toVar(),r=_i(t.y).toVar(),i=_i(t.z).toVar(),n=_i(Aa(s,Aa(r,i))).toVar(),o=_i(Ra(s,Ra(r,i))).toVar(),a=_i(o.sub(n)).toVar(),u=_i().toVar(),l=_i().toVar(),c=_i().toVar();return c.assign(o),yi(o.greaterThan(0),(()=>{l.assign(a.div(o))})).else((()=>{l.assign(0)})),yi(l.lessThanEqual(0),(()=>{u.assign(0)})).else((()=>{yi(s.greaterThanEqual(o),(()=>{u.assign(r.sub(i).div(a))})).elseif(r.greaterThanEqual(o),(()=>{u.assign(yo(2,i.sub(s).div(a)))})).else((()=>{u.assign(yo(4,s.sub(r).div(a)))})),u.mulAssign(1/6),yi(u.lessThan(0),(()=>{u.addAssign(1)}))})),Mi(u,l,c)}));kT.setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),zT.setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]});const $T=fi((([e])=>{const t=Mi(e).toVar(),s=Oi(Co(t,Mi(.04045))).toVar(),r=Mi(t.div(12.92)).toVar(),i=Mi(Ua(Ra(t.add(Mi(.055)),Mi(0)).div(1.055),Mi(2.4))).toVar();return ka(r,i,s)}));$T.setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]});const HT=(e,t)=>{e=_i(e),t=_i(t);const s=Ri(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Wa(e.sub(s),e.add(s),t)},WT=(e,t,s,r)=>ka(e,t,s[r].clamp()),jT=(e,t,s=mo())=>WT(e,t,s,"x"),qT=(e,t,s=mo())=>WT(e,t,s,"y"),XT=(e,t,s,r,i)=>ka(e,t,HT(s,r[i])),YT=(e,t,s,r=mo())=>XT(e,t,s,r,"x"),KT=(e,t,s,r=mo())=>XT(e,t,s,r,"y"),QT=(e=1,t=0,s=mo())=>s.mul(e).add(t),ZT=(e,t=1)=>(e=_i(e)).abs().pow(t).mul(e.sign()),JT=(e,t=1,s=.5)=>_i(e).sub(s).mul(t).add(s),ex=(e=mo(),t=1,s=0)=>dT(e.convert("vec2|vec3")).mul(t).add(s),tx=(e=mo(),t=1,s=0)=>gT(e.convert("vec2|vec3")).mul(t).add(s),sx=(e=mo(),t=1,s=0)=>{e=e.convert("vec2|vec3");return Ui(gT(e),dT(e.add(Ri(19,73)))).mul(t).add(s)},rx=(e=mo(),t=1)=>IT(e.convert("vec2|vec3"),t,vi(1)),ix=(e=mo(),t=1)=>DT(e.convert("vec2|vec3"),t,vi(1)),nx=(e=mo(),t=1)=>GT(e.convert("vec2|vec3"),t,vi(1)),ox=(e=mo())=>yT(e.convert("vec2|vec3")),ax=(e=mo(),t=3,s=2,r=.5,i=1)=>AT(e,vi(t),s,r).mul(i),ux=(e=mo(),t=3,s=2,r=.5,i=1)=>CT(e,vi(t),s,r).mul(i),lx=(e=mo(),t=3,s=2,r=.5,i=1)=>RT(e,vi(t),s,r).mul(i),cx=(e=mo(),t=3,s=2,r=.5,i=1)=>ET(e,vi(t),s,r).mul(i);function dx(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function hx(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}class px{constructor(){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparent=[],this.lightsNode=new xc([]),this.lightsArray=[],this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparent.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,r,i,n){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:r,renderOrder:e.renderOrder,z:i,group:n},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=r,o.renderOrder=e.renderOrder,o.z=i,o.group=n),this.renderItemsIndex++,o}push(e,t,s,r,i,n){const o=this.getNextRenderItem(e,t,s,r,i,n);!0===e.occlusionTest&&this.occlusionQueryCount++,(!0===s.transparent?this.transparent:this.opaque).push(o)}unshift(e,t,s,r,i,n){const o=this.getNextRenderItem(e,t,s,r,i,n);(!0===s.transparent?this.transparent:this.opaque).unshift(o)}pushLight(e){this.lightsArray.push(e)}getLightsNode(){return this.lightsNode.fromLights(this.lightsArray)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||dx),this.transparent.length>1&&this.transparent.sort(t||hx)}finish(){this.lightsNode.fromLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,l=a.height>>t;let c=e.depthTexture||i[t],d=!1;void 0===c&&(c=new N,c.format=e.stencilBuffer?ye:be,c.type=e.stencilBuffer?Ne:_e,c.image.width=u,c.image.height=l,i[t]=c),s.width===a.width&&a.height===s.height||(d=!0,c.needsUpdate=!0,c.image.width=u,c.image.height=l),s.width=a.width,s.height=a.height,s.textures=o,s.depthTexture=c,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==r&&(d=!0,c.needsUpdate=!0,s.sampleCount=r);const h={sampleCount:r};for(let e=0;e{if(e.removeEventListener("dispose",t),void 0!==o)for(let e=0;e0){const r=e.image;if(void 0===r);else if(!1===r.complete);else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=r;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(i.createTexture(e,t),s.isDefaultTexture=!1),!0===e.source.dataReady&&i.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),s.isDefaultTexture=!0}if(!0!==s.initialized){s.initialized=!0,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=xx){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),t.width=s.width,t.height=s.height,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let r;return r=e.isCompressedTexture?e.mipmaps.length:Math.floor(Math.log2(Math.max(t,s)))+1,r}needsMipmaps(e){return!!this.isEnvironmentTexture(e)||(!0===e.isCompressedTexture||e.minFilter!==_&&e.minFilter!==L)}isEnvironmentTexture(e){const t=e.mapping;return t===Se||t===Ae||t===Re||t===Ce}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class bx extends o{constructor(e,t,s,r=1){super(e,t,s),this.a=r}set(e,t,s,r=1){return this.a=r,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}const Nx=new bx;class _x extends js{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const r=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)r._clearColor.getRGB(Nx,this.renderer.currentColorSpace),Nx.a=r._clearColor.a;else if(!0===i.isColor)i.getRGB(Nx,this.renderer.currentColorSpace),Nx.a=1,n=!0;else if(!0===i.isNode){const s=this.get(e),n=i;Nx.copy(r._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=mn(Ui(n),{getUV:()=>Zu,getTextureLevel:e=>vp.mul(ou(e))}).mul(Sp);let t=Dl();t=t.setZ(t.w);const r=new cd;r.side=F,r.depthTest=!1,r.depthWrite=!1,r.fog=!1,r.vertexNode=t,r.fragmentNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new O(new Ee(1,32,32),r),o.frustumCulled=!1,o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=Ui(n),o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null)}if(!0===r.autoClear||!0===n){Nx.multiplyScalar(Nx.a);const e=s.clearColorValue;e.r=Nx.r,e.g=Nx.g,e.b=Nx.b,e.a=Nx.a,s.depthClearValue=r._clearDepth,s.stencilClearValue=r._clearStencil,s.clearColor=!0===r.autoClearColor,s.clearDepth=!0===r.autoClearDepth,s.clearStencil=!0===r.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}class vx{constructor(e,t,s,r,i,n,o,a=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=a,this.nodeAttributes=r,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=o,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){let s=t;!0!==t.shared&&(s=t.clone()),e.push(s)}return e}}class Sx extends js{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Dd,this.nodeBuilderCache=new Map,this.callHashCache=new Ds,this.groupsData=new Ds}updateGroup(e){const t=e.groupNode,s=t.name;if(s===co.name)return!0;if(s===lo.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===uo.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}const r=[t,e];let i=this.groupsData.get(r);return void 0===i&&this.groupsData.set(r,i={}),i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:r}=this,i=this.getForRenderCacheKey(e);if(s=r.get(i),void 0===s){const t=this.backend.createNodeBuilder(e.object,this.renderer,e.scene);t.material=e.material,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.toneMappingNode=this.getToneMappingNode(),t.clippingContext=e.clippingContext,t.build(),s=this._createNodeBuilderState(t),r.set(i,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const r=this.backend.createNodeBuilder(e,this.renderer);r.build(),s=this._createNodeBuilderState(r),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new vx(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.transforms)}getEnvironmentNode(e){return e.environmentNode||this.get(e).environmentNode||null}getBackgroundNode(e){return e.backgroundNode||this.get(e).backgroundNode||null}getFogNode(e){return e.fogNode||this.get(e).fogNode||null}getToneMappingNode(){return!1===this.isToneMappingState?null:this.renderer.toneMappingNode||this.get(this.renderer).toneMappingNode||null}getCacheKey(e,t){const s=[e,t],r=this.renderer.info.calls;let i=this.callHashCache.get(s);if(void 0===i||i.callId!==r){const n=this.getEnvironmentNode(e),o=this.getFogNode(e),a=this.getToneMappingNode(),u=[];t&&u.push(t.getCacheKey()),n&&u.push(n.getCacheKey()),o&&u.push(o.getCacheKey()),a&&u.push(a.getCacheKey()),i={callId:r,cacheKey:u.join(",")},this.callHashCache.set(s,i)}return i.cacheKey}updateScene(e){this.updateEnvironment(e),this.updateFog(e),this.updateBackground(e),this.updateToneMapping()}get isToneMappingState(){const e=this.renderer.getRenderTarget();return!e||!e.isCubeRenderTarget}updateToneMapping(){const e=this.renderer,t=this.get(e),s=e.toneMapping;if(this.isToneMappingState&&s!==W){if(t.toneMapping!==s){const r=t.rendererToneMappingNode||xg(s,xu("toneMappingExposure","float",e));r.toneMapping=s,t.rendererToneMappingNode=r,t.toneMappingNode=r,t.toneMapping=s}}else delete t.toneMappingNode,delete t.toneMapping}updateBackground(e){const t=this.get(e),s=e.background;if(s){if(t.background!==s){let e=null;if(!0===s.isCubeTexture)e=pc(s,Zu);else if(!0===s.isTexture){let t=null;s.mapping===Se||s.mapping===Ae?(t=Rc(),s.flipY=!1):t=Gc,e=uu(s,t).setUpdateMatrix(!0)}else s.isColor;t.backgroundNode=e,t.background=s}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){let e=null;s.isFogExp2?e=em(xu("color","color",s),xu("density","float",s)):s.isFog&&(e=Zg(xu("color","color",s),xu("near","float",s),xu("far","float",s))),t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){let e=null;!0===s.isCubeTexture?e=pc(s):!0===s.isTexture&&(e=uu(s)),t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,r=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=r,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}updateBefore(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateBeforeNodes)t.updateBeforeNode(e)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}dispose(){super.dispose(),this.nodeFrame=new Dd,this.nodeBuilderCache=new Map}}const Ax=new U,Rx=new a,Cx=new s,Ex=new we,wx=new l,Mx=new u;class Fx{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:r=!1,alpha:i=!0}=t;this.domElement=e.getDomElement(),this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=r,this.outputColorSpace=p,this.toneMapping=W,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=!0,this.stencil=!0,this.clippingPlanes=[],this.info=new tr,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new s(0,0,this._width,this._height),this._scissor=new s(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null;const n=!0===this.alpha?0:1;this._clearColor=new bx(0,0,0,n),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._handleObjectFunction=this._renderObjectDirect,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.shadowMap={enabled:!1,type:null},this.xr={enabled:!1}}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)=>{const s=this.backend;try{await s.init(this)}catch(e){return void t(e)}this._nodes=new Sx(this,s),this._animation=new Ps(this._nodes,this.info),this._attributes=new Qs(s),this._background=new _x(this,this._nodes),this._geometries=new er(this._attributes,this.info),this._textures=new yx(this,s,this.info),this._pipelines=new ar(s,this._nodes),this._bindings=new ur(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Ws(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new gx,this._renderContexts=new Tx,this._initialized=!0,e()}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){!1===this._initialized&&await this.init();const r=this._nodes.nodeFrame,i=r.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,u=!0===e.isScene?e:Ax;null===s&&(s=e);const l=this._renderTarget,c=this._renderContexts.get(s,t,l),d=this._activeMipmapLevel,h=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,r.renderId++,r.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new zs),c.clippingContext.updateGlobal(this,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,d);const e=this._textures.get(l);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;this._nodes.updateScene(u),this._background.update(u,p,c);const g=p.opaque,m=p.transparent,f=p.lightsNode;g.length>0&&this._renderObjects(g,t,u,f),m.length>0&&this._renderObjects(m,t,u,f),r.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){!1===this._initialized&&await this.init();const s=this._renderContext(e,t);await this.backend.resolveTimestampAsync(s,"render")}render(e,t){!1!==this._initialized&&this._renderContext(e,t)}_renderContext(e,t){const s=this._nodes.nodeFrame,r=s.renderId,i=this._currentRenderContext,n=this._currentRenderObjectFunction,o=!0===e.isScene?e:Ax,a=this._renderTarget,u=this._renderContexts.get(e,t,a),l=this._activeCubeFace,c=this._activeMipmapLevel;this._currentRenderContext=u,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,s.renderId=this.info.calls;const d=this.coordinateSystem;t.coordinateSystem!==d&&(t.coordinateSystem=d,t.updateProjectionMatrix()),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===this.info.autoReset&&this.info.reset();let h=this._viewport,p=this._scissor,g=this._pixelRatio;null!==a&&(h=a.viewport,p=a.scissor,g=1),this.getDrawingBufferSize(Rx),Cx.set(0,0,Rx.width,Rx.height);const m=void 0===h.minDepth?0:h.minDepth,f=void 0===h.maxDepth?1:h.maxDepth;u.viewportValue.copy(h).multiplyScalar(g).floor(),u.viewportValue.width>>=c,u.viewportValue.height>>=c,u.viewportValue.minDepth=m,u.viewportValue.maxDepth=f,u.viewport=!1===u.viewportValue.equals(Cx),u.scissorValue.copy(p).multiplyScalar(g).floor(),u.scissor=this._scissorTest&&!1===u.scissorValue.equals(Cx),u.scissorValue.width>>=c,u.scissorValue.height>>=c,u.clippingContext||(u.clippingContext=new zs),u.clippingContext.updateGlobal(this,t),o.onBeforeRender(this,e,t,a),wx.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),Ex.setFromProjectionMatrix(wx,d);const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==a){this._textures.updateRenderTarget(a,c);const e=this._textures.get(a);u.textures=e.textures,u.depthTexture=e.depthTexture,u.width=e.width,u.height=e.height,u.renderTarget=a,u.depth=a.depthBuffer,u.stencil=a.stencilBuffer}else u.textures=null,u.depthTexture=null,u.width=this.domElement.width,u.height=this.domElement.height,u.depth=this.depth,u.stencil=this.stencil;u.width>>=c,u.height>>=c,u.activeCubeFace=l,u.activeMipmapLevel=c,u.occlusionQueryCount=T.occlusionQueryCount,this._nodes.updateScene(o),this._background.update(o,T,u),this.backend.beginRender(u);const x=T.opaque,y=T.transparent,b=T.lightsNode;return x.length>0&&this._renderObjects(x,t,o,b),y.length>0&&this._renderObjects(y,t,o,b),this.backend.finishRender(u),s.renderId=r,this._currentRenderContext=i,this._currentRenderObjectFunction=n,o.onAfterRender(this,e,t,a),u}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)}getArrayBuffer(e){return this.getArrayBufferAsync(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.setSize(this._width,this._height,!1)}setDrawingBufferSize(e,t,s){this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,s=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,r){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,s,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,r,i=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,r),o.minDepth=i,o.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){let r=null;const i=this._renderTarget;null!==i&&(this._textures.updateRenderTarget(i),r=this._textures.get(i)),this.backend.clear(e,t,s,r)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}clearColorAsync(){return this.clearAsync(!0,!1,!1)}clearDepthAsync(){return this.clearAsync(!1,!0,!1)}clearStencilAsync(){return this.clearAsync(!1,!1,!0)}get currentColorSpace(){const e=this._renderTarget;if(null!==e){const t=e.texture;return(Array.isArray(t)?t[0]:t).colorSpace}return this.outputColorSpace}dispose(){this.info.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}async computeAsync(e){!1===this._initialized&&await this.init();const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.computeCalls++,t.renderId=this.info.calls,!0===this.info.autoReset&&this.info.resetCompute();const r=this.backend,i=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const t of a){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e),t.onInit({renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=i.getForCompute(t,s);r.compute(e,t,s,a)}r.finishCompute(e),await this.backend.resolveTimestampAsync(e,"compute"),t.renderId=s}hasFeatureAsync(e){return this.backend.hasFeatureAsync(e)}hasFeature(e){return this.backend.hasFeature(e)}copyFramebufferToTexture(e){const t=this._currentRenderContext;this._textures.updateTexture(e),this.backend.copyFramebufferToTexture(e,t)}readRenderTargetPixelsAsync(e,t,s,r,i){return this.backend.copyTextureToBuffer(e.texture,t,s,r,i)}_projectObject(e,t,s,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||Ex.intersectsSprite(e)){!0===this.sortObjects&&Mx.setFromMatrixPosition(e.matrixWorld).applyMatrix4(wx);const t=e.geometry,i=e.material;i.visible&&r.push(e,t,i,s,Mx.z,null)}}else if(e.isLineLoop);else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||Ex.intersectsObject(e))){const t=e.geometry,i=e.material;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Mx.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(wx)),Array.isArray(i)){const n=t.groups;for(let o=0,a=n.length;o0?i:"";t=`${s.name} {\n\t${r} ${e.name}[${n}];\n};\n`}else{t=`${this.getVectorType(e.type)} ${e.name};`,i=!0}const n=e.node.precision;if(null!==n&&(t=Wx[n]+" "+t),i){t="\t"+t;const s=e.groupNode.name;(r[s]||(r[s]=[])).push(t)}else t="uniform "+t,s.push(t)}let i="";for(const t in r){const s=r[t];i+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return i+=s.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Oe){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const r=s.array;!1==(r instanceof Uint32Array||r instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const r of e)t+=`layout( location = ${s++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){const t=[],s=e.getMemberTypes();for(let e=0;e0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${r.code}\n\t`,e===i&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${r.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${r.result};`)))}const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,r=null){const i=super.getUniformFromNode(e,t,s,r),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){if("texture"===t)o=new zx(i.name,i.node),this.bindings[s].push(o);else if("cubeTexture"===t)o=new $x(i.name,i.node),this.bindings[s].push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new Ix(e);t.name=e.name,this.bindings[s].push(t),o=t}else{const r=e.groupNode,n=r.name,a=this.uniformGroups[s]||(this.uniformGroups[s]={});let u=a[n];void 0===u&&(u=new Vx(s+"_"+n,r),a[n]=u,this.bindings[s].push(u)),o=this.getNodeUniform(i,t),u.addUniform(o)}n.uniformGPU=o}return i}}let Yx=null,Kx=null,Qx=null;class Zx{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null}async init(e){this.renderer=e}begin(e){}finish(e){}draw(e,t){}createProgram(e){}destroyProgram(e){}createBindings(e){}updateBindings(e){}createRenderPipeline(e){}createComputePipeline(e,t){}destroyPipeline(e){}needsRenderUpdate(e){}getRenderCacheKey(e){}createNodeBuilder(e){}createSampler(e){}createDefaultTexture(e){}createTexture(e){}copyTextureToBuffer(e,t,s,r,i){}createAttribute(e){}createIndexAttribute(e){}updateAttribute(e){}destroyAttribute(e){}getContext(){}updateSize(){}resolveTimestampAsync(e,t){}hasFeatureAsync(e){}hasFeature(e){}getInstanceCount(e){const{object:t,geometry:s}=e;return s.isInstancedBufferGeometry?s.instanceCount:t.isInstancedMesh?t.count:1}getDrawingBufferSize(){return Yx=Yx||new a,this.renderer.getDrawingBufferSize(Yx)}getScissor(){return Kx=Kx||new s,this.renderer.getScissor(Kx)}setScissorTest(e){}getClearColor(){const e=this.renderer;return Qx=Qx||new bx,e.getClearColor(Qx),Qx.getRGB(Qx,this.renderer.currentColorSpace),Qx}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Pe(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${V} 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)}}let Jx=0;class ey{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 ty{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:r}=s,i=e.array,n=e.usage||r.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let u,l=a.bufferGPU;if(void 0===l&&(l=this._createBuffer(r,t,i,n),a.bufferGPU=l,a.bufferType=t,a.version=o.version),i instanceof Float32Array)u=r.FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=r.SHORT;else if(i instanceof Uint32Array)u=r.UNSIGNED_INT;else if(i instanceof Int32Array)u=r.INT;else if(i instanceof Int8Array)u=r.BYTE;else if(i instanceof Uint8Array)u=r.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=r.UNSIGNED_BYTE}let c={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===r.INT||u===r.UNSIGNED_INT||e.gpuType===Oe,id:Jx++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(r,t,i,n);c=new ey(c,e)}s.set(e,c)}updateAttribute(e){const t=this.backend,{gl:s}=t,r=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,r);else{for(let e=0,t=a.length;e{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void r();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(i)}()}))}}let ay,uy,ly,cy=!1;class dy{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===cy&&(this._init(this.gl),cy=!0)}_init(e){ay={[ts]:e.REPEAT,[ss]:e.CLAMP_TO_EDGE,[rs]:e.MIRRORED_REPEAT},uy={[_]:e.NEAREST,[is]:e.NEAREST_MIPMAP_NEAREST,[ns]:e.NEAREST_MIPMAP_LINEAR,[L]:e.LINEAR,[os]:e.LINEAR_MIPMAP_NEAREST,[A]:e.LINEAR_MIPMAP_LINEAR},ly={[as]:e.NEVER,[us]:e.ALWAYS,[v]:e.LESS,[ls]:e.LEQUAL,[cs]:e.EQUAL,[ds]:e.GEQUAL,[hs]:e.GREATER,[ps]:e.NOTEQUAL}}filterFallback(e){const{gl:t}=this;return e===_||e===is||e===ns?t.NEAREST:t.LINEAR}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D,s}getInternalFormat(e,t,s,r,i=!1){const{gl:n,extensions:o}=this;if(null!==e&&void 0!==n[e])return n[e];let a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8)),t===n.RGB&&(s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=r===p&&!1===i?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_INT&&(a=n.DEPTH24_STENCIL8),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:r,backend:i}=this,{currentAnisotropy:n}=i.get(t);s.texParameteri(e,s.TEXTURE_WRAP_S,ay[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,ay[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,ay[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,uy[t.magFilter]);const o=t.isVideoTexture||t.minFilter!==L?t.minFilter:A;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,uy[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,ly[t.compareFunction])),!0===r.has("EXT_texture_filter_anisotropic")){if(t.magFilter===_)return;if(t.minFilter!==ns&&t.minFilter!==A)return;if(t.type===y&&!1===r.has("OES_texture_float_linear"))return;if(t.anisotropy>1||n!==t.anisotropy){const n=r.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.getMaxAnisotropy())),i.get(t).currentAnisotropy=t.anisotropy}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:r}=this,i=this.getGLTextureType(e);let n=r[i];void 0===n&&(n=t.createTexture(),s.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),r[i]=n),s.set(e,{textureGPU:n,glTextureType:i,isDefault:!0})}createTexture(e,t){const{gl:s,backend:r}=this,{levels:i,width:n,height:o,depth:a}=t,u=r.utils.convert(e.format,e.colorSpace),l=r.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,u,l,e.colorSpace,e.isVideoTexture),d=s.createTexture(),h=this.getGLTextureType(e);r.state.bindTexture(h,d),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,e.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,e.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE),this.setTextureParameters(h,e),e.isDataArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,i,c,n,o,a):e.isVideoTexture||s.texStorage2D(h,i,c,n,o),r.set(e,{textureGPU:d,glTextureType:h,glFormat:u,glType:l,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:s,backend:r}=this,{textureGPU:i,glTextureType:n,glFormat:o,glType:a}=r.get(t),{width:u,height:l}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(n,i),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,u,l,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:r,height:i}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:u,glInternalFormat:l}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const c=e=>e.isDataTexture?e.image.data:e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement?e:e.data;if(this.backend.state.bindTexture(o,n),e.isCompressedTexture){const r=e.mipmaps;for(let i=0;i0?(n&&n.isDepthTexture&&n.type===s.FLOAT&&(t=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,i,t,u,l)):s.renderbufferStorage(s.RENDERBUFFER,t,u,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else o&&a&&(i>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,i,s.DEPTH24_STENCIL8,u,l):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,u,l),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,r,i){const{backend:n,gl:o}=this,{textureGPU:a,glFormat:u,glType:l}=this.backend.get(e),c=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,c),o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,a,0);const d=this._getTypedArrayType(l),h=r*i,p=h*this._getBytesPerTexel(u),g=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.bufferData(o.PIXEL_PACK_BUFFER,p,o.STREAM_READ),o.readPixels(t,s,r,i,u,l,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await n.utils._clientWaitAsync();const m=new d(h);return o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,m),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(c),m}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e){const{gl:t}=this;return e===t.RGBA?4:e===t.RGB?3:e===t.ALPHA?1:void 0}}class hy{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)),t}has(e){return this.availableExtensions.includes(e)}}class py{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const gy={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"};class my extends Zx{constructor(e={}){super(e),this.isWebGLBackend=!0}init(e){super.init(e);const t=this.parameters,s=void 0!==t.context?t.context:e.domElement.getContext("webgl2");this.gl=s,this.extensions=new hy(this),this.capabilities=new py(this),this.attributeUtils=new ty(this),this.textureUtils=new dy(this),this.state=new ny(this),this.utils=new oy(this),this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.extensions.get("EXT_color_buffer_float"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this._currentContext=null}get coordinateSystem(){return gs}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.gl}beginRender(e){const{gl:t}=this,s=this.get(e);if(s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1),e.viewport?this.updateViewport(e):t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight),e.scissor){const{x:s,y:r,width:i,height:n}=e.scissorValue;t.scissor(s,r,i,n)}const r=e.occlusionQueryCount;r>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(r),s.occlusionQueryObjects=new Array(r),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,r=this.get(e).previousContext,i=e.textures;if(null!==i)for(let e=0;e0){const i=r.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,i),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n);for(let s=0;s0){if(n>this.get(e).occlusionQueryIndex){const{gl:e}=this;e.endQuery(e.ANY_SAMPLES_PASSED)}this.resolveOccludedAsync(e)}}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:r}=t;if(s&&r){const e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let o=0;for(let t=0;t0&&e.add(r[t]),s[t]=null,i.deleteQuery(n),o++))}o1?o.drawElementsInstanced(f,c.count,e.type,g,T):o.drawElements(f,c.count,e.type,g),t.update(d,s,1)}else{const e=h.attributes.position,s=p.count!==1/0?p.count:e.count;T>1?o.drawArraysInstanced(f,0,s,T):o.drawArrays(f,0,s),t.update(d,s,1)}o.bindVertexArray(null)}needsRenderUpdate(){return!1}getRenderCacheKey(e){return e.id}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}copyTextureToBuffer(e,t,s,r,i){return this.textureUtils.copyTextureToBuffer(e,t,s,r,i)}createSampler(){}destroySampler(){}createNodeBuilder(e,t,s=null){return new Xx(e,t,s)}createProgram(e){const t=this.gl,{stage:s,code:r}=e,i="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(i,r),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(){}createRenderPipeline(e,t){const s=this.gl,r=e.pipeline,{fragmentProgram:i,vertexProgram:n}=r,o=s.createProgram(),a=this.get(i).shaderGPU,u=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,u),s.linkProgram(o),this.set(r,{programGPU:o,fragmentShader:a,vertexShader:u}),null!==t&&this.parallel){const i=new Promise((t=>{const i=this.parallel,n=()=>{s.getProgramParameter(o,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),t()):requestAnimationFrame(n)};n()}));t.push(i)}else this._completeCompile(e,r)}_completeCompile(e,t){const s=this.gl,r=this.get(t),{programGPU:i,fragmentShader:n,vertexShader:o}=r;s.getProgramParameter(i,s.LINK_STATUS),s.useProgram(i),this._setupBindings(e.getBindings(),i),this.set(t,{programGPU:i})}createComputePipeline(e,t){const s=this.gl,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:i}=e,n=s.createProgram(),o=this.get(r).shaderGPU,a=this.get(i).shaderGPU,u=i.transforms,l=[],c=[];for(let e=0;egy[t]===e)),s=this.extensions;for(let e=0;e0){if(void 0===h){const r=[];h=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,h);const i=[],l=e.textures;for(let s=0;s,\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({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:by,stripIndexFormat:Py},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:by,stripIndexFormat:Py},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const r=t.format,{width:i,height:n}=t.size,o=this.getTransferPipeline(r),a=this.getFlipYPipeline(r),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:db,baseArrayLayer:s}),c=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:db,baseArrayLayer:0}),d=this.device.createCommandEncoder({}),h=(e,t,s)=>{const r=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=d.beginRenderPass({colorAttachments:[{view:s,loadOp:Fy,storeOp:wy,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(o,l,c),h(a,c,l),this.device.queue.submit([d.finish()]),u.destroy()}generateMipmaps(e,t,s=0){const r=this.getTransferPipeline(t.format),i=this.device.createCommandEncoder({}),n=r.getBindGroupLayout(0);let o=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:db,baseArrayLayer:s});for(let a=1;a1&&(c=Math.pow(2,Math.floor(Math.log2(c))),2===c&&(c=4));const d=e.isRenderTargetTexture?1:c;let h=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(h|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&(h|=GPUTextureUsage.RENDER_ATTACHMENT);const p={label:e.name,size:{width:i,height:n,depthOrArrayLayers:o},mipLevelCount:a,sampleCount:d,dimension:u,format:l,usage:h};if(e.isVideoTexture){const t=e.source.data,s=new VideoFrame(t);p.size.width=s.displayWidth,p.size.height=s.displayHeight,s.close(),r.externalTexture=t}else{if(void 0===l)return this.createDefaultTexture(e);r.texture=s.device.createTexture(p)}if(e.isRenderTargetTexture&&c>1){const e=Object.assign({},p);e.label=e.label+"-msaa",e.sampleCount=c,r.msaaTexture=s.device.createTexture(e)}r.initialized=!0,r.textureDescriptorGPU=p}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else this._generateMipmaps(t.texture,t.textureDescriptorGPU)}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.parameters.sampleCount,format:Dy.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!0){const s=this.backend,{width:r,height:i}=s.getDrawingBufferSize(),n=this.depthTexture,o=s.get(n).texture;let a,u;if(t?(a=ye,u=Ne):e&&(a=be,u=_e),void 0!==o){if(n.image.width===r&&n.image.height===i&&n.format===a&&n.type===u)return o;this.destroyTexture(n)}return n.name="depthBuffer",n.format=a,n.type=u,n.image.width=r,n.image.height=i,this.createTexture(n,{sampleCount:s.parameters.sampleCount,width:r,height:i}),s.get(n).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:r}=s;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture||e.isData3DTexture)this._copyBufferToTexture(t.image,s.texture,r,0,e.flipY);else if(e.isDataArrayTexture)for(let i=0;i]*\s*([a-z_0-9]+)?/i,wb=/[a-z_0-9]+|<(.*?)>+/gi,Mb={f32:"float"};class Fb extends Nf{constructor(e){const{type:t,inputs:s,name:r,inputsCode:i,blockCode:n}=(e=>{const t=(e=e.trim()).match(Eb);if(null!==t&&4===t.length){const s=t[2],r=[];let i=null;for(;null!==(i=wb.exec(s));)r.push(i);const n=[];let o=0;for(;o "+this.type:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class Bb extends bf{parseFunction(e){return new Fb(e)}}const Ob=self.GPUShaderStage,Ub={vertex:Ob?Ob.VERTEX:1,fragment:Ob?Ob.FRAGMENT:2,compute:Ob?Ob.COMPUTE:4},Lb={instance:!0,storageBuffer:!0},Ib={"^^":"threejs_xor"},Pb={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",imat2:"mat2x2",umat2:"mat2x2",bmat2:"mat2x2",mat3:"mat3x3",imat3:"mat3x3",umat3:"mat3x3",bmat3:"mat3x3",mat4:"mat4x4",imat4:"mat4x4",umat4:"mat4x4",bmat4:"mat4x4"},Db={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"threejs_mod_float",mod_vec2:"threejs_mod_vec2",mod_vec3:"threejs_mod_vec3",mod_vec4:"threejs_mod_vec4",equals_bool:"threejs_equals_bool",equals_bvec2:"threejs_equals_bvec2",equals_bvec3:"threejs_equals_bvec3",equals_bvec4:"threejs_equals_bvec4",lessThanEqual:"threejs_lessThanEqual",greaterThan:"threejs_greaterThan",inversesqrt:"inverseSqrt",bitcast:"bitcast"},Vb={threejs_xor:new Kn("\nfn threejs_xor( a : bool, b : bool ) -> bool {\n\n\treturn ( a || b ) && !( a && b );\n\n}\n"),lessThanEqual:new Kn("\nfn threejs_lessThanEqual( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x <= b.x, a.y <= b.y, a.z <= b.z );\n\n}\n"),greaterThan:new Kn("\nfn threejs_greaterThan( a : vec3, b : vec3 ) -> vec3 {\n\n\treturn vec3( a.x > b.x, a.y > b.y, a.z > b.z );\n\n}\n"),mod_float:new Kn("fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Kn("fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Kn("fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Kn("fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Kn("fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Kn("fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Kn("fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new Kn("fn threejs_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:new Kn("\nfn threejs_repeatWrapping( uv : vec2, dimension : vec2 ) -> vec2 {\n\n\tlet uvScaled = vec2( uv * vec2( dimension ) );\n\n\treturn ( ( uvScaled % dimension ) + dimension ) % dimension;\n\n}\n")};class Gb extends Pd{constructor(e,t,s=null){super(e,t,new Bb,s),this.uniformGroups={},this.builtins={}}needsColorSpaceToLinear(e){return!0===e.isVideoTexture&&e.colorSpace!==C}_generateTextureSample(e,t,s,r,i=this.shaderStage){return"fragment"===i?r?`textureSample( ${t}, ${t}_sampler, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureLod(e,t,s)}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`}_generateTextureSampleLevel(e,t,s,r,i,n=this.shaderStage){return"fragment"===n&&!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r} )`:this.generateTextureLod(e,t,s,r)}generateTextureLod(e,t,s,r="0"){this._include("repeatWrapping");return`textureLoad( ${t}, threejs_repeatWrapping( ${s}, ${`textureDimensions( ${t}, 0 )`} ), i32( ${r} ) )`}generateTextureLoad(e,t,s,r,i="0u"){return r?`textureLoad( ${t}, ${s}, ${r}, ${i} )`:`textureLoad( ${t}, ${s}, ${i} )`}generateTextureStore(e,t,s,r){return`textureStore( ${t}, ${s}, ${r} )`}isUnfilterable(e){return!0===e.isDataTexture&&e.type===y}generateTexture(e,t,s,r,i=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,"0",r,i):this._generateTextureSample(e,t,s,r,i),n}generateTextureCompare(e,t,s,r,i,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r} )`}generateTextureLevel(e,t,s,r,i,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,r,i,n),o}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,s=e.type;return"texture"===s||"cubeTexture"===s||"storageTexture"===s?t:"buffer"===s||"storageBuffer"===s?`NodeBuffer_${e.id}.${t}`:e.groupNode.name+"."+t}return super.getPropertyName(e)}_getUniformGroupCount(e){return Object.keys(this.uniforms[e]).length}getFunctionOperator(e){const t=Ib[e];return void 0!==t?(this._include(t),t):null}getUniformFromNode(e,t,s,r=null){const i=super.getUniformFromNode(e,t,s,r),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let r;const o=this.bindings[s];if("texture"===t||"cubeTexture"===t||"storageTexture"===t){let n=null;if("texture"===t||"storageTexture"===t?n=new zx(i.name,i.node):"cubeTexture"===t&&(n=new $x(i.name,i.node)),n.store=!0===e.isStoreTextureNode,n.setVisibility(Ub[s]),"fragment"===s&&!1===this.isUnfilterable(e.value)&&!1===n.store){const e=new yb(`${i.name}_sampler`,i.node);e.setVisibility(Ub[s]),o.push(e,n),r=[e,n]}else o.push(n),r=[n]}else if("buffer"===t||"storageBuffer"===t){const i=new("storageBuffer"===t?_b:Ix)(e);i.setVisibility(Ub[s]),o.push(i),r=i}else{const n=e.groupNode,a=n.name,u=this.uniformGroups[s]||(this.uniformGroups[s]={});let l=u[a];void 0===l&&(l=new Vx(a,n),l.setVisibility(Ub[s]),u[a]=l,o.push(l)),r=this.getNodeUniform(i,t),l.addUniform(r)}n.uniformGPU=r,"vertex"===s&&(this.bindingsOffset.fragment=o.length)}return i}isReference(e){return super.isReference(e)||"texture_2d"===e||"texture_cube"===e||"texture_depth_2d"===e||"texture_storage_2d"===e}getBuiltin(e,t,s,r=this.shaderStage){const i=this.builtins[r]||(this.builtins[r]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:s}),t}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(e.name+" : "+this.getType(e.type));return`fn ${t.name}( ${r.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n\treturn ${s.result};\n\n}`}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}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")}isFlipY(){return!1}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:r,type:i}of s.values())t.push(`@builtin( ${e} ) ${r} : ${i}`);return t.join(",\n\t")}getAttributes(e){const t=[];if("compute"===e&&this.getBuiltin("global_invocation_id","id","vec3","attribute"),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const s=this.getAttributesArray();for(let e=0,r=s.length;e`)}return t.join(",\n")}getStructs(e){const t=[],s=this.structs[e];for(let e=0,r=s.length;e","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,r=this.vars[e];for(let i=0;i";else if(!0===t.isDataArrayTexture)r="texture_2d_array";else if(!0===t.isDepthTexture)r="texture_depth_2d";else if(!0===t.isVideoTexture)r="texture_external";else if(!0===i.node.isStoreTextureNode){r="texture_storage_2d<"+Cb(t)+", write>"}else r="texture_2d";s.push(`@binding( ${o++} ) @group( 0 ) var ${i.name} : ${r};`)}else if("buffer"===i.type||"storageBuffer"===i.type){const e=i.node,t=this.getType(e.bufferType),s=e.bufferCount,n=s>0?", "+s:"",a=`\t${i.name} : array< ${t}${n} >\n`,u=e.isStorageBufferNode?"storage,read_write":"uniform";r.push(this._getWGSLStructBinding("NodeBuffer_"+e.id,a,u,o++))}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:o++,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))}let a=s.join("\n");return a+=r.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};for(const t in e){const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t);let r="// code\n\n";r+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${u}\n\t`),r+=`${i.code}\n\t`,e===n&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(a)s.returnType=o.nodeType,r+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar output : OutputStruct;\n\n",r+=`output.color = ${i.result};\n\n\treturn output;`}}s.flow=r}null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return Pb[e]||e}isAvailable(e){return!0===Lb[e]}_getWGSLMethod(e){return void 0!==Vb[e]&&this._include(e),Db[e]}_include(e){const t=Vb[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\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\n// uniforms\n${e.uniforms}\n\n// structs\n${e.structs}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// system\nvar instanceIndex : u32;\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = id.x;\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,s,r=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${r} ) @group( ${i} )\nvar<${s}> ${e} : ${n};`}}class kb{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=Dy.Depth24PlusStencil8:e.depth&&(t=Dy.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).texture.format}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):Dy.BGRA8Unorm,t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?fy:e.isLineSegments||e.isMesh&&!0===t.wireframe?Ty:e.isLine?xy:e.isMesh?yy:void 0}getSampleCount(e){return null!==e.textures?e.sampleCount:this.backend.parameters.sampleCount}}const zb=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),$b=new Map([[D,["float16"]]]),Hb=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class Wb{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),r=this.backend,i=r.get(s);let n=i.buffer;if(void 0===n){const e=r.device;let o=s.array;if((s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){s.itemSize=4,o=new o.constructor(4*s.count);for(let e=0;e1&&(v=Math.pow(2,Math.floor(Math.log2(v))),2===v&&(v=4));const S={vertex:Object.assign({},x,{buffers:p}),fragment:Object.assign({},y,{targets:T}),primitive:b,depthStencil:{format:_,depthWriteEnabled:r.depthWrite,depthCompare:N,stencilFront:m,stencilBack:{},stencilReadMask:r.stencilFuncMask,stencilWriteMask:r.stencilWriteMask},multisample:{count:v,alphaToCoverageEnabled:r.alphaToCoverage},layout:l.createPipelineLayout({bindGroupLayouts:[h.layout]})};if(null===t)d.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{d.pipeline=t,e()}))}));t.push(e)}}createComputePipeline(e,t){const s=this.backend,r=s.device,i=s.get(e.computeProgram).module,n=s.get(e),o=s.get(t);n.pipeline=r.createComputePipeline({compute:i,layout:r.createPipelineLayout({bindGroupLayouts:[o.layout]})})}_getBlending(e){let t,s;const r=e.blending;if(r===tt){const r=null!==e.blendSrcAlpha?e.blendSrcAlpha:Hy.One,i=null!==e.blendDstAlpha?e.blendDstAlpha:Hy.Zero,n=null!==e.blendEquationAlpha?e.blendEquationAlpha:Hy.Add;t={srcFactor:this._getBlendFactor(e.blendSrc),dstFactor:this._getBlendFactor(e.blendDst),operation:this._getBlendOperation(e.blendEquation)},s={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(i),operation:this._getBlendOperation(n)}}else{const i=(e,r,i,n)=>{t={srcFactor:e,dstFactor:r,operation:Wy},s={srcFactor:i,dstFactor:n,operation:Wy}};if(e.premultipliedAlpha)switch(r){case nt:i(Hy.SrcAlpha,Hy.OneMinusSrcAlpha,Hy.One,Hy.OneMinusSrcAlpha);break;case it:i(Hy.SrcAlpha,Hy.One,Hy.One,Hy.One);break;case rt:i(Hy.Zero,Hy.OneMinusSrc,Hy.Zero,Hy.One);break;case st:i(Hy.Zero,Hy.Src,Hy.Zero,Hy.SrcAlpha)}else switch(r){case nt:i(Hy.SrcAlpha,Hy.OneMinusSrcAlpha,Hy.One,Hy.OneMinusSrcAlpha);break;case it:i(Hy.SrcAlpha,Hy.One,Hy.SrcAlpha,Hy.One);break;case rt:i(Hy.Zero,Hy.OneMinusSrc,Hy.Zero,Hy.One);break;case st:i(Hy.Zero,Hy.Src,Hy.Zero,Hy.Src)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s}}_getBlendFactor(e){let t;switch(e){case ke:t=Hy.Zero;break;case ze:t=Hy.One;break;case $e:t=Hy.Src;break;case Xe:t=Hy.OneMinusSrc;break;case He:t=Hy.SrcAlpha;break;case Ye:t=Hy.OneMinusSrcAlpha;break;case je:t=Hy.Dst;break;case Ke:t=Hy.OneMinusDstColor;break;case qe:t=Hy.DstAlpha;break;case Qe:t=Hy.OneMinusDstAlpha;break;case We:t=Hy.SrcAlphaSaturated;break;case 211:t=Hy.Constant;break;case 212:t=Hy.OneMinusConstant}return t}_getStencilCompare(e){let t;switch(e.stencilFunc){case Ss:t=Ny;break;case vs:t=Ey;break;case _s:t=_y;break;case Ns:t=Sy;break;case bs:t=vy;break;case ys:t=Cy;break;case xs:t=Ay;break;case Ts:t=Ry}return t}_getStencilOperation(e){let t;switch(e){case Bs:t=Zy;break;case Fs:t=Jy;break;case Ms:t=eb;break;case ws:t=tb;break;case Es:t=sb;break;case Cs:t=rb;break;case Rs:t=ib;break;case As:t=nb}return t}_getBlendOperation(e){let t;switch(e){case De:t=Wy;break;case Ve:t=jy;break;case Ge:t=qy;break;case Us:t=Xy;break;case Os:t=Yy}return t}_getPrimitiveState(e,t,s){const r={},i=this.backend.utils;switch(r.topology=i.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?Iy:Py),s.side){case Fe:r.frontFace=By,r.cullMode=Ly;break;case F:r.frontFace=By,r.cullMode=Uy;break;case Me:r.frontFace=By,r.cullMode=Oy}return r}_getColorWriteMask(e){return!0===e.colorWrite?Qy:Ky}_getDepthCompare(e){let t;if(!1===e.depthTest)t=Ey;else{switch(e.depthFunc){case pt:t=Ny;break;case ht:t=Ey;break;case dt:t=_y;break;case ct:t=Sy;break;case lt:t=vy;break;case ut:t=Cy;break;case at:t=Ay;break;case ot:t=Ry}}return t}}class Xb extends Zx{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.antialias=!0===e.antialias,!0===this.parameters.antialias?this.parameters.sampleCount=void 0===e.sampleCount?4:e.sampleCount:this.parameters.sampleCount=1,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.adapter=null,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new kb(this),this.attributeUtils=new Wb(this),this.bindingUtils=new jb(this),this.pipelineUtils=new qb(this),this.textureUtils=new Rb(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters,s={powerPreference:t.powerPreference},r=await navigator.gpu.requestAdapter(s);if(null===r)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(Tb),n=[];for(const e of i)r.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits},a=await r.requestDevice(o),u=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.adapter=r,this.device=a,this.context=u;const l=t.alpha?"premultiplied":"opaque";this.context.configure({device:this.device,format:Dy.BGRA8Unorm,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:l}),this.updateSize()}get coordinateSystem(){return b}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;const t=this.parameters.antialias;if(null===e){const s=this.renderer;e={colorAttachments:[{view:null}],depthStencilAttachment:{view:this.textureUtils.getDepthBuffer(s.depth,s.stencil).createView()}};const r=e.colorAttachments[0];!0===t?r.view=this.colorBuffer.createView():r.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const s=e.colorAttachments[0];return!0===t?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),e}_getRenderPassDescriptor(e){const t=e.renderTarget,s=this.get(t);let r=s.descriptors;void 0===r&&(r=[],s.descriptors=r),s.width===t.width&&s.height===t.height&&s.activeMipmapLevel===t.activeMipmapLevel&&s.samples===t.samples||(r.length=0);let i=r[e.activeCubeFace];if(void 0===i){const n=e.textures,o=[];for(let t=0;t0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=s.createQuerySet({type:"occlusion",count:r}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(r),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e),this.initTimestampQuery(e,n),n.occlusionQuerySet=i;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;st.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),s>0){const r=8*s;let i=this.occludedResolveCache.get(r);void 0===i&&(i=this.device.createBuffer({size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(r,i));const n=this.device.createBuffer({size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,r),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.prepareTimestampBuffer(e,t.encoder),this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eeN&&((1/(e-eN)).toFixed(),await this._callback(e,{width:this.video.videoWidth,height:this.video.videoHeight})),eN=e,this.animationID=Zb((async()=>await this.animateLegacy()))}async animate(e,t){await this._callback(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initAnimate(){this.animateRef=async(e,t)=>await this.animate(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initLegacyAnimate(){this.animateLegacy()}start(){this.stop(),Qb?this.initAnimate():(eN=new Date,this.initLegacyAnimate()),this.running=!0}stop(){this.running=!1,Qb?this.animateRef=()=>{}:Jb(this.animationID&&this.animationID.data&&this.animationID.data.handleId||this.animationID)}}const sN="requestVideoFrameCallback"in HTMLVideoElement.prototype,rN=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,iN=window.cancelAnimationFrame||window.mozCancelAnimationFrame;let nN;class oN{constructor(e,t){this._callback=e,this.video=t,this.animationID=null,this.running=!1,this.updateNodesRef=()=>{}}set nodes(e){this._nodes=e,e&&(this.updateNodesRef=()=>{this._nodes.nodeFrame.update()})}set callback(e){this._callback=e}async animateLegacy(){const e=this.video.currentTime;e>nN&&((1/(e-nN)).toFixed(),this.updateNodesRef(),await this._callback(e,{width:this.video.videoWidth,height:this.video.videoHeight})),nN=e,this.animationID=rN((async()=>await this.animateLegacy()))}async animate(e,t){this.updateNodesRef(),await this._callback(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initAnimate(){this.animateRef=async(e,t)=>await this.animate(e,t),this.video.requestVideoFrameCallback(this.animateRef)}initLegacyAnimate(){this.animateLegacy()}start(){this.stop(),sN?this.initAnimate():(nN=new Date,this.initLegacyAnimate()),this.running=!0}stop(){this.running=!1,sN?this.animateRef=()=>{}:iN(this.animationID&&this.animationID.data&&this.animationID.data.handleId||this.animationID)}}export{_c as AONode,Lg as AfterImageNode,gm as AmbientLightNode,fc as AnalyticLightNode,Dg as AnamorphicNode,wr as ArrayElementNode,tn as AssignNode,on as AttributeNode,Wm as BRDF_GGX,Om as BRDF_Lambert,Kh as BitangentNode,Pp as BlendModeNode,ic as Break,Vl as BufferAttributeNode,du as BufferNode,Hp as BumpMapNode,un as BypassNode,hn as CacheNode,Mu as CameraNode,Tm as CheckerNode,Kn as CodeNode,Yp as ColorAdjustmentNode,Qa as ColorSpaceNode,nm as ComputeNode,Ed as CondNode,Ir as ConstNode,gn as ContextNode,rc as Continue,Mr as ConvertNode,hc as CubeTextureNode,jm as DFGApprox,Hm as D_GGX,dm as DirectionalLightNode,Jd as DiscardNode,ko as EPSILON,Mc as EnvironmentNode,Ac as EquirectUVNode,ru as ExpressionNode,Bm as F_Schlick,Jg as FogExp2Node,Yg as FogNode,Qg as FogRangeNode,od as FrontFacingNode,Gg as FunctionCallNode,to as FunctionNode,sh as FunctionOverloadingNode,Rf as GLSLNodeParser,Bg as GaussianBlurNode,$d as HashNode,mm as HemisphereLightNode,pm as IESSpotLightNode,zo as INFINITY,yi as If,Tn as IndexNode,Hl as InstanceNode,Nm as InstancedPointsNodeMaterial,Fr as JoinNode,am as LightNode,vc as LightingContextNode,bn as LightingModel,gc as LightingNode,xc as LightsNode,Cm as Line2NodeMaterial,vm as LineBasicNodeMaterial,Am as LineDashedNodeMaterial,tc as LoopNode,nh as MatcapUVNode,rl as MaterialNode,bu as MaterialReferenceNode,Go as MathNode,nu as MaxMipLevelNode,Fm as MeshBasicNodeMaterial,Dm as MeshLambertNodeMaterial,wm as MeshNormalNodeMaterial,Gm as MeshPhongNodeMaterial,cf as MeshPhysicalNodeMaterial,hf as MeshSSSNodeMaterial,uf as MeshStandardNodeMaterial,Gu as ModelNode,Pl as ModelViewProjectionNode,uc as MorphNode,Ar as Node,vn as NodeAttribute,Pd as NodeBuilder,dn as NodeCache,Cn as NodeCode,Dd as NodeFrame,Vd as NodeFunctionInput,En as NodeKeywords,ym as NodeLoader,cd as NodeMaterial,xf as NodeMaterialLoader,yf as NodeObjectLoader,lr as NodeShaderStage,dr as NodeType,Sn as NodeUniform,cr as NodeUpdateType,_r as NodeUtils,An as NodeVar,Rn as NodeVarying,rg as NormalMapNode,Xu as NormalNode,_u as Object3DNode,xo as OperatorNode,hh as OscNode,kd as OutputStructNode,$o as PI,Ho as PI2,Th as PackingNode,Xn as ParameterNode,vg as PassNode,Im as PhongLightingModel,of as PhysicalLightingModel,cm as PointLightNode,bp as PointUVNode,gf as PointsNodeMaterial,Ml as PositionNode,ng as PosterizeNode,wn as PropertyNode,rm as RangeNode,Tu as ReferenceNode,cc as ReflectVectorNode,Xh as ReflectorNode,bh as RemapNode,Ah as RotateNode,vh as RotateUVNode,_p as SceneNode,Xm as Schlick_to_F0,qg as ScriptableNode,zg as ScriptableValueNode,Ur as SetNode,li as ShaderNode,Jl as SkinningNode,Cc as SpecularMIPLevelNode,Or as SplitNode,hm as SpotLightNode,ff as SpriteNodeMaterial,Ch as SpriteSheetUVNode,Md as StackNode,wh as StorageArrayElementNode,Ap as StorageBufferNode,rp as TBNViewMatrix,jl as TangentNode,Er as TempNode,xp as TextureBicubicNode,au as TextureNode,Ep as TextureStoreNode,ah as TimerNode,Tg as ToneMappingNode,Fh as TriplanarTexturesNode,go as UVNode,no as UniformGroupNode,ho as UniformNode,gu as UniformsNode,Fp as UserDataNode,$m as V_GGX_SmithCorrelated,Nn as VarNode,rn as VaryingNode,op as VertexColorNode,tN as VideoAnimation,Kc as ViewportDepthNode,Xc as ViewportDepthTextureNode,Lc as ViewportNode,bg as ViewportSharedTextureNode,Hc as ViewportTextureNode,Is as WebGPU,Kb as WebGPUGLRenderer,Yb as WebGPURenderer,oN as WebGPUVideoAnimation,ha as abs,ca as acos,yo as add,Nc as addLightNode,Rr as addNodeClass,Vr as addNodeElement,dd as addNodeMaterial,Ig as afterImage,Wo as all,Vg as anamorphic,Mo as and,jo as any,bi as append,Qi as arrayBuffer,la as asin,sn as assign,da as atan,Sa as atan2,an as attribute,vp as backgroundBlurriness,Sp as backgroundIntensity,Uo as bitAnd,Lo as bitNot,Io as bitOr,Po as bitXor,Qh as bitangentGeometry,Zh as bitangentLocal,Jh as bitangentView,ep as bitangentWorld,va as bitcast,ki as bmat2,Wi as bmat3,Yi as bmat4,Ai as bool,hu as buffer,Gl as bufferAttribute,Wp as bumpMap,Dp as burn,wi as bvec2,Oi as bvec3,Pi as bvec4,ln as bypass,pn as cache,kg as call,Uu as cameraFar,Lu as cameraLogDepth,Ou as cameraNear,Pu as cameraNormalMatrix,Vu as cameraPosition,Fu as cameraProjectionMatrix,Bu as cameraProjectionMatrixInverse,Iu as cameraViewMatrix,Du as cameraWorldMatrix,Va as cbrt,ra as ceil,xm as checker,za as clamp,Ln as clearcoat,In as clearcoatRoughness,Qn as code,Ni as color,eu as colorSpaceToLinear,yh as colorToDirection,om as compute,wd as cond,mn as context,Ji as convert,aa as cos,Cr as createNodeFromType,hd as createNodeMaterialFromType,Oa as cross,pc as cubeTexture,Ta as dFdx,xa as dFdy,Wn as dashSize,pr as defaultBuildStages,hr as defaultShaderStages,Yo as degrees,em as densityFog,sd as depth,Rg as depthPass,id as depthPixel,rd as depthTexture,Fa as difference,Bn as diffuseColor,xh as directionToColor,th as discard,Ma as distance,_o as div,Vp as dodge,Ba as dot,kl as dynamicBufferAttribute,Zi as element,So as equal,qo as equals,Rc as equirectUV,Ko as exp,Qo as exp2,iu as expression,ud as faceDirection,ja as faceForward,_i as float,sa as floor,Kg as fog,na as fract,uo as frameGroup,dh as frameId,ad as frontFacing,_a as fwidth,jd as gain,jn as gapSize,Og as gaussianBlur,ui as getConstNodeType,xi as getCurrentStack,lm as getDistanceAttenuation,km as getGeometryRoughness,zm as getRoughness,jg as global,eo as glsl,ro as glslFn,Co as greaterThan,wo as greaterThanEqual,Hd as hash,Zp as hue,Vi as imat2,$i as imat3,qi as imat4,Wl as instance,yn as instanceIndex,zl as instancedBufferAttribute,$l as instancedDynamicBufferAttribute,vi as int,ta as inverseSqrt,Vn as iridescence,Gn as iridescenceIOR,kn as iridescenceThickness,Ci as ivec2,Fi as ivec3,Li as ivec4,Zn as js,fn as label,ga as length,Ga as lengthSq,Ro as lessThan,Eo as lessThanEqual,um as lightTargetDirection,Sc as lightingContext,yc as lights,bc as lightsNode,Ja as linearToColorSpace,tu as linearTosRGB,Zo as log,Jo as log2,sc as loop,Jp as lumaCoeffs,eg as luminance,Di as mat2,zi as mat3,ji as mat4,oh as matcapUV,il as materialAlphaTest,ml as materialClearcoat,Tl as materialClearcoatNormal,fl as materialClearcoatRoughness,nl as materialColor,al as materialEmissive,Nl as materialIridescence,_l as materialIridescenceIOR,vl as materialIridescenceThickness,El as materialLineDashOffset,Al as materialLineDashSize,Rl as materialLineGapSize,Sl as materialLineScale,Cl as materialLineWidth,pl as materialMetalness,gl as materialNormal,ul as materialOpacity,wl as materialPointWidth,Nu as materialReference,dl as materialReflectivity,xl as materialRotation,hl as materialRoughness,yl as materialSheen,bl as materialSheenRoughness,ol as materialShininess,ll as materialSpecularColor,cl as materialSpecularStrength,Ra as max,ou as maxMipLevel,Un as metalness,Aa as min,ka as mix,Ca as mod,ku as modelDirection,$u as modelNormalMatrix,Wu as modelPosition,ju as modelScale,zu as modelViewMatrix,qu as modelViewPosition,Dl as modelViewProjection,Hu as modelWorldMatrix,lc as morphReference,No as mul,HT as mx_aastep,ox as mx_cell_noise_float,JT as mx_contrast,ax as mx_fractal_noise_float,ux as mx_fractal_noise_vec2,lx as mx_fractal_noise_vec3,cx as mx_fractal_noise_vec4,kT as mx_hsvtorgb,ex as mx_noise_float,tx as mx_noise_vec3,sx as mx_noise_vec4,jT as mx_ramplr,qT as mx_ramptb,zT as mx_rgbtohsv,ZT as mx_safepower,YT as mx_splitlr,KT as mx_splittb,$T as mx_srgb_texture_to_lin_rec709,QT as mx_transform_uv,rx as mx_worley_noise_float,ix as mx_worley_noise_vec2,nx as mx_worley_noise_vec3,ma as negate,hi as nodeArray,gi as nodeImmutable,ci as nodeObject,di as nodeObjects,pi as nodeProxy,Yu as normalGeometry,Ku as normalLocal,ig as normalMap,Qu as normalView,Zu as normalWorld,ia as normalize,Bo as not,vu as objectDirection,co as objectGroup,Au as objectNormalMatrix,Cu as objectPosition,Eu as objectScale,Su as objectViewMatrix,wu as objectViewPosition,Ru as objectWorldMatrix,fa as oneMinus,Fo as or,Zc as orthographicDepthToViewZ,fh as oscSawtooth,ph as oscSine,gh as oscSquare,mh as oscTriangle,Hn as output,zd as outputStruct,Gp as overlay,ih as overloadingFn,Wd as parabola,ip as parallaxDirection,np as parallaxUV,Yn as parameter,Sg as pass,qd as pcurve,ed as perspectiveDepthToViewZ,Np as pointUV,qn as pointWidth,Fl as positionGeometry,Bl as positionLocal,Ll as positionView,Il as positionViewDirection,Ol as positionWorld,Ul as positionWorldDirection,og as posterize,Ua as pow,La as pow2,Ia as pow3,Pa as pow4,Mn as property,Xo as radians,im as range,Zg as rangeFog,ba as reciprocal,xu as reference,yu as referenceBuffer,wa as reflect,dc as reflectVector,Yh as reflector,Ha as refract,vo as remainder,Nh as remap,_h as remapClamp,lo as renderGroup,Rh as rotate,Sh as rotateUV,On as roughness,ya as round,su as sRGBToLinear,cu as sampler,$a as saturate,Kp as saturation,kp as screen,Xg as scriptable,$g as scriptableValue,Ti as setCurrentStack,mi as shader,gr as shaderStages,Pn as sheen,Dn as sheenRoughness,Do as shiftLeft,Vo as shiftRight,$n as shininess,pa as sign,oa as sin,Xd as sinc,ec as skinning,Wa as smoothstep,zn as specularColor,Ec as specularMIPLevel,en as split,Eh as spritesheetUV,ea as sqrt,Fd as stack,Ea as step,Rp as storage,Cp as storageObject,Ki as string,bo as sub,ua as tan,ql as tangentGeometry,Xl as tangentLocal,Yl as tangentView,Kl as tangentWorld,_n as temp,uu as texture,yp as textureBicubic,lu as textureLoad,Mp as textureStore,tg as threshold,ch as timerDelta,lh as timerGlobal,uh as timerLocal,xg as toneMapping,Da as transformDirection,tp as transformedBitangentView,sp as transformedBitangentWorld,tl as transformedClearcoatNormalView,Ju as transformedNormalView,el as transformedNormalWorld,Ql as transformedTangentView,Zl as transformedTangentWorld,Qd as triNoise3D,Oh as triplanarTexture,Bh as triplanarTextures,Na as trunc,fi as tslFn,Si as uint,Gi as umat2,Hi as umat3,Xi as umat4,po as uniform,oo as uniformGroup,mu as uniforms,Bp as userData,mo as uv,Ei as uvec2,Bi as uvec3,Ii as uvec4,nn as varying,Fn as varyingProperty,Ri as vec2,Mi as vec3,Ui as vec4,mr as vectorComponents,ap as vertexColor,xn as vertexIndex,Qp as vibrance,Qc as viewZToOrthographicDepth,Jc as viewZToPerspectiveDepth,Dc as viewport,Gc as viewportBottomLeft,zc as viewportBottomRight,Ic as viewportCoordinate,Yc as viewportDepthTexture,jc as viewportMipTexture,Pc as viewportResolution,Ng as viewportSharedTexture,Wc as viewportTexture,Vc as viewportTopLeft,kc as viewportTopRight,Jn as wgsl,io as wgslFn,Oo as xor}; diff --git a/build/webgpu-renderer.module.min.js.gz b/build/webgpu-renderer.module.min.js.gz index f768571..f1958d0 100644 Binary files a/build/webgpu-renderer.module.min.js.gz and b/build/webgpu-renderer.module.min.js.gz differ diff --git a/package-lock.json b/package-lock.json index e44eca8..265ffc3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -47,9 +47,9 @@ } }, "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", - "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", "dev": true, "engines": { "node": ">=6.0.0" @@ -65,9 +65,9 @@ } }, "node_modules/@jridgewell/source-map": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz", - "integrity": "sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==", + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.5.tgz", + "integrity": "sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==", "dev": true, "dependencies": { "@jridgewell/gen-mapping": "^0.3.0", @@ -81,21 +81,15 @@ "dev": true }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.18", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", - "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", "dev": true, "dependencies": { - "@jridgewell/resolve-uri": "3.1.0", - "@jridgewell/sourcemap-codec": "1.4.14" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", - "dev": true - }, "node_modules/@rollup/plugin-commonjs": { "version": "19.0.2", "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-19.0.2.tgz", @@ -147,20 +141,20 @@ } }, "node_modules/@rollup/plugin-strip": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-strip/-/plugin-strip-3.0.2.tgz", - "integrity": "sha512-L8Whin/DB5XsLE586+xcud6yX/pMVUlfalA999uAsC+dtwmBHSiUwtAxMl3eVvykX3N5BhdeAjStqDlzMmfUXw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-strip/-/plugin-strip-3.0.4.tgz", + "integrity": "sha512-LDRV49ZaavxUo2YoKKMQjCxzCxugu1rCPQa0lDYBOWLj6vtzBMr8DcoJjsmg+s450RbKbe3qI9ZLaSO+O1oNbg==", "dev": true, "dependencies": { "@rollup/pluginutils": "^5.0.1", "estree-walker": "^2.0.2", - "magic-string": "^0.27.0" + "magic-string": "^0.30.3" }, "engines": { "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0" + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { "rollup": { @@ -169,9 +163,9 @@ } }, "node_modules/@rollup/plugin-strip/node_modules/@rollup/pluginutils": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.0.2.tgz", - "integrity": "sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.0.tgz", + "integrity": "sha512-XTIWOPPcpvyKI6L1NHo0lFlCyznUEyPmPY1mc3KpPVDYulHSTvyeLNVW00QTLIAFNhR3kYnJTQHeGqU4M3n09g==", "dev": true, "dependencies": { "@types/estree": "^1.0.0", @@ -182,7 +176,7 @@ "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0" + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { "rollup": { @@ -191,27 +185,15 @@ } }, "node_modules/@rollup/plugin-strip/node_modules/@types/estree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.1.tgz", - "integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", + "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", "dev": true }, - "node_modules/@rollup/plugin-strip/node_modules/magic-string": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.27.0.tgz", - "integrity": "sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==", - "dev": true, - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.4.13" - }, - "engines": { - "node": ">=12" - } - }, "node_modules/@rollup/plugin-terser": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.3.tgz", - "integrity": "sha512-EF0oejTMtkyhrkwCdg0HJ0IpkcaVg1MMSf2olHb2Jp+1mnLM04OhjpJWGma4HobiDTF0WCyViWuvadyE9ch2XA==", + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz", + "integrity": "sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==", "dev": true, "dependencies": { "serialize-javascript": "^6.0.1", @@ -222,7 +204,7 @@ "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^2.x || ^3.x" + "rollup": "^2.0.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { "rollup": { @@ -260,10 +242,13 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.2.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.3.tgz", - "integrity": "sha512-pg9d0yC4rVNWQzX8U7xb4olIOFuuVL9za3bzMT2pu2SU0SNEi66i2qrvhE2qt0HvkhuCaWJu7pLNOt/Pj8BIrw==", - "dev": true + "version": "20.10.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.6.tgz", + "integrity": "sha512-Vac8H+NlRNNlAmDfGUP7b5h/KA+AtWIzuXy0E6OyP8f1tCLYAtPvKRRDJjAPqhpCb0t6U2j7/xqAuLEebW2kiw==", + "dev": true, + "dependencies": { + "undici-types": "~5.26.4" + } }, "node_modules/@types/resolve": { "version": "1.17.1", @@ -275,9 +260,9 @@ } }, "node_modules/acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -287,9 +272,9 @@ } }, "node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.1.tgz", + "integrity": "sha512-TgUZgYvqZprrl7YldZNoa9OciCAyZR+Ejm9eXzKCmjsF5IKp/wgQ7Z/ZpjpGTIUPwrHQIcYeI8qDh4PsEwxMbw==", "dev": true, "engines": { "node": ">=0.4.0" @@ -389,9 +374,9 @@ "dev": true }, "node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, "hasInstallScript": true, "optional": true, @@ -403,10 +388,13 @@ } }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/glob": { "version": "7.2.3", @@ -428,16 +416,16 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "node_modules/hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", "dev": true, "dependencies": { - "function-bind": "^1.1.1" + "function-bind": "^1.1.2" }, "engines": { - "node": ">= 0.4.0" + "node": ">= 0.4" } }, "node_modules/inflight": { @@ -457,12 +445,12 @@ "dev": true }, "node_modules/is-core-module": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.12.1.tgz", - "integrity": "sha512-Q4ZuBAe2FUsKtyQJoQHlvP8OvBERxO3jEmy1I7hcRXcJBGGHFh/aJBswbXuS9sgrDH2QUO8ilkwNPHvHMd8clg==", + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", "dev": true, "dependencies": { - "has": "^1.0.3" + "hasown": "^2.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -484,9 +472,9 @@ } }, "node_modules/magic-string": { - "version": "0.30.3", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.3.tgz", - "integrity": "sha512-B7xGbll2fG/VjP+SWg4sX3JynwIU0mjoTc6MPpKNuIvftk6u6vqhDnk1R80b8C2GBR6ywqy+1DcKBrevBg+bmw==", + "version": "0.30.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz", + "integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==", "dev": true, "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" @@ -553,12 +541,12 @@ } }, "node_modules/resolve": { - "version": "1.22.2", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.2.tgz", - "integrity": "sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g==", + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", "dev": true, "dependencies": { - "is-core-module": "^2.11.0", + "is-core-module": "^2.13.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -585,9 +573,9 @@ } }, "node_modules/rollup-plugin-gzip": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-gzip/-/rollup-plugin-gzip-3.1.0.tgz", - "integrity": "sha512-PFS9s6/w6dCra6/Z8PGD+ug3aaaqKLDCbr5y1Ek71Wd4rQSmMnOqCIIMgwbYxZ9A/gjP3pCN6rA4pAG47jxF0w==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-gzip/-/rollup-plugin-gzip-3.1.1.tgz", + "integrity": "sha512-KhRH3xc5TfbOFsnW0GrmMVf3KZF8oxXY8igqz0b/9JbY4WhRARq53isQPEYlrfgc8Mx3ofXoapfAPb7zyfyBeQ==", "dev": true, "engines": { "node": ">=10.0.0" @@ -646,9 +634,9 @@ } }, "node_modules/smob": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/smob/-/smob-1.1.1.tgz", - "integrity": "sha512-i5aqEBPnDv9d77+NDxfjROtywxzNdAVNyaOr+RsLhM28Ts+Ar7luIp/Q+SBYa6wv/7BBcOpEkrhtDxsl2WA9Jg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.4.1.tgz", + "integrity": "sha512-9LK+E7Hv5R9u4g4C3p+jjLstaLe11MDsL21UpYaCNmapvMkYhqCV4A/f/3gyH8QjMyh6l68q9xC85vihY9ahMQ==", "dev": true }, "node_modules/source-map": { @@ -690,13 +678,13 @@ } }, "node_modules/terser": { - "version": "5.17.6", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.17.6.tgz", - "integrity": "sha512-V8QHcs8YuyLkLHsJO5ucyff1ykrLVsR4dNnS//L5Y3NiSXpbK1J+WMVUs67eI0KTxs9JtHhgEQpXQVHlHI92DQ==", + "version": "5.26.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.26.0.tgz", + "integrity": "sha512-dytTGoE2oHgbNV9nTzgBEPaqAWvcJNl66VZ0BkJqlvp71IjO8CxdBx/ykCNb47cLnCmCvRZ6ZR0tLkqvZCdVBQ==", "dev": true, "dependencies": { - "@jridgewell/source-map": "^0.3.2", - "acorn": "^8.5.0", + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, @@ -707,6 +695,12 @@ "node": ">=10" } }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -736,9 +730,9 @@ } }, "@jridgewell/resolve-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", - "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", "dev": true }, "@jridgewell/set-array": { @@ -748,9 +742,9 @@ "dev": true }, "@jridgewell/source-map": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz", - "integrity": "sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==", + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.5.tgz", + "integrity": "sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==", "dev": true, "requires": { "@jridgewell/gen-mapping": "^0.3.0", @@ -764,21 +758,13 @@ "dev": true }, "@jridgewell/trace-mapping": { - "version": "0.3.18", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", - "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", "dev": true, "requires": { - "@jridgewell/resolve-uri": "3.1.0", - "@jridgewell/sourcemap-codec": "1.4.14" - }, - "dependencies": { - "@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", - "dev": true - } + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, "@rollup/plugin-commonjs": { @@ -822,20 +808,20 @@ } }, "@rollup/plugin-strip": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-strip/-/plugin-strip-3.0.2.tgz", - "integrity": "sha512-L8Whin/DB5XsLE586+xcud6yX/pMVUlfalA999uAsC+dtwmBHSiUwtAxMl3eVvykX3N5BhdeAjStqDlzMmfUXw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-strip/-/plugin-strip-3.0.4.tgz", + "integrity": "sha512-LDRV49ZaavxUo2YoKKMQjCxzCxugu1rCPQa0lDYBOWLj6vtzBMr8DcoJjsmg+s450RbKbe3qI9ZLaSO+O1oNbg==", "dev": true, "requires": { "@rollup/pluginutils": "^5.0.1", "estree-walker": "^2.0.2", - "magic-string": "^0.27.0" + "magic-string": "^0.30.3" }, "dependencies": { "@rollup/pluginutils": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.0.2.tgz", - "integrity": "sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.0.tgz", + "integrity": "sha512-XTIWOPPcpvyKI6L1NHo0lFlCyznUEyPmPY1mc3KpPVDYulHSTvyeLNVW00QTLIAFNhR3kYnJTQHeGqU4M3n09g==", "dev": true, "requires": { "@types/estree": "^1.0.0", @@ -844,26 +830,17 @@ } }, "@types/estree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.1.tgz", - "integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", + "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", "dev": true - }, - "magic-string": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.27.0.tgz", - "integrity": "sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==", - "dev": true, - "requires": { - "@jridgewell/sourcemap-codec": "^1.4.13" - } } } }, "@rollup/plugin-terser": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.3.tgz", - "integrity": "sha512-EF0oejTMtkyhrkwCdg0HJ0IpkcaVg1MMSf2olHb2Jp+1mnLM04OhjpJWGma4HobiDTF0WCyViWuvadyE9ch2XA==", + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz", + "integrity": "sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==", "dev": true, "requires": { "serialize-javascript": "^6.0.1", @@ -897,10 +874,13 @@ "dev": true }, "@types/node": { - "version": "20.2.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.3.tgz", - "integrity": "sha512-pg9d0yC4rVNWQzX8U7xb4olIOFuuVL9za3bzMT2pu2SU0SNEi66i2qrvhE2qt0HvkhuCaWJu7pLNOt/Pj8BIrw==", - "dev": true + "version": "20.10.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.6.tgz", + "integrity": "sha512-Vac8H+NlRNNlAmDfGUP7b5h/KA+AtWIzuXy0E6OyP8f1tCLYAtPvKRRDJjAPqhpCb0t6U2j7/xqAuLEebW2kiw==", + "dev": true, + "requires": { + "undici-types": "~5.26.4" + } }, "@types/resolve": { "version": "1.17.1", @@ -912,15 +892,15 @@ } }, "acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", "dev": true }, "acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.1.tgz", + "integrity": "sha512-TgUZgYvqZprrl7YldZNoa9OciCAyZR+Ejm9eXzKCmjsF5IKp/wgQ7Z/ZpjpGTIUPwrHQIcYeI8qDh4PsEwxMbw==", "dev": true }, "balanced-match": { @@ -994,16 +974,16 @@ "dev": true }, "fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, "optional": true }, "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", "dev": true }, "glob": { @@ -1020,13 +1000,13 @@ "path-is-absolute": "^1.0.0" } }, - "has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", "dev": true, "requires": { - "function-bind": "^1.1.1" + "function-bind": "^1.1.2" } }, "inflight": { @@ -1046,12 +1026,12 @@ "dev": true }, "is-core-module": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.12.1.tgz", - "integrity": "sha512-Q4ZuBAe2FUsKtyQJoQHlvP8OvBERxO3jEmy1I7hcRXcJBGGHFh/aJBswbXuS9sgrDH2QUO8ilkwNPHvHMd8clg==", + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", "dev": true, "requires": { - "has": "^1.0.3" + "hasown": "^2.0.0" } }, "is-module": { @@ -1070,9 +1050,9 @@ } }, "magic-string": { - "version": "0.30.3", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.3.tgz", - "integrity": "sha512-B7xGbll2fG/VjP+SWg4sX3JynwIU0mjoTc6MPpKNuIvftk6u6vqhDnk1R80b8C2GBR6ywqy+1DcKBrevBg+bmw==", + "version": "0.30.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz", + "integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==", "dev": true, "requires": { "@jridgewell/sourcemap-codec": "^1.4.15" @@ -1124,12 +1104,12 @@ } }, "resolve": { - "version": "1.22.2", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.2.tgz", - "integrity": "sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g==", + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", "dev": true, "requires": { - "is-core-module": "^2.11.0", + "is-core-module": "^2.13.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" } @@ -1144,9 +1124,9 @@ } }, "rollup-plugin-gzip": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-gzip/-/rollup-plugin-gzip-3.1.0.tgz", - "integrity": "sha512-PFS9s6/w6dCra6/Z8PGD+ug3aaaqKLDCbr5y1Ek71Wd4rQSmMnOqCIIMgwbYxZ9A/gjP3pCN6rA4pAG47jxF0w==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-gzip/-/rollup-plugin-gzip-3.1.1.tgz", + "integrity": "sha512-KhRH3xc5TfbOFsnW0GrmMVf3KZF8oxXY8igqz0b/9JbY4WhRARq53isQPEYlrfgc8Mx3ofXoapfAPb7zyfyBeQ==", "dev": true, "requires": {} }, @@ -1182,9 +1162,9 @@ } }, "smob": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/smob/-/smob-1.1.1.tgz", - "integrity": "sha512-i5aqEBPnDv9d77+NDxfjROtywxzNdAVNyaOr+RsLhM28Ts+Ar7luIp/Q+SBYa6wv/7BBcOpEkrhtDxsl2WA9Jg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.4.1.tgz", + "integrity": "sha512-9LK+E7Hv5R9u4g4C3p+jjLstaLe11MDsL21UpYaCNmapvMkYhqCV4A/f/3gyH8QjMyh6l68q9xC85vihY9ahMQ==", "dev": true }, "source-map": { @@ -1216,17 +1196,23 @@ "dev": true }, "terser": { - "version": "5.17.6", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.17.6.tgz", - "integrity": "sha512-V8QHcs8YuyLkLHsJO5ucyff1ykrLVsR4dNnS//L5Y3NiSXpbK1J+WMVUs67eI0KTxs9JtHhgEQpXQVHlHI92DQ==", + "version": "5.26.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.26.0.tgz", + "integrity": "sha512-dytTGoE2oHgbNV9nTzgBEPaqAWvcJNl66VZ0BkJqlvp71IjO8CxdBx/ykCNb47cLnCmCvRZ6ZR0tLkqvZCdVBQ==", "dev": true, "requires": { - "@jridgewell/source-map": "^0.3.2", - "acorn": "^8.5.0", + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", "commander": "^2.20.0", "source-map-support": "~0.5.20" } }, + "undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true + }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/package.json b/package.json index b8ab9a2..1ede393 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "three-webgpu-renderer", - "version": "0.155.0", + "version": "0.162.0", "description": "Three.js WebGPU Renderer", "main": "build/three-webgpu-renderer.js", "module": "build/webgpu-renderer.module.js", diff --git a/three.js b/three.js index acbf0b0..ef80ac7 160000 --- a/three.js +++ b/three.js @@ -1 +1 @@ -Subproject commit acbf0b0049560f0ff09cc92d47a14a79b2d5c4e6 +Subproject commit ef80ac74e6716a50104a57d8add6c8a950bff8d7